CAN数据解析

 汽车领域免不了与CAN打交道,作为一名软件开发人员,时常遇到要解析CAN消息的情形。

CAN报文的数据结构可以自行学习,本文记录下如何从dbc文件 -> C代码 -> 拿到所需信号的物理值。dbc本身是一种文本文件,以一定格式记录各个信号的ID, byte偏移,bit偏移,factor,offset等属性。

解析时可以按照dbc里定义的”结构“定义一个struct,然后将CAN报文的payload memcpy到这个struct,注意字节对齐和字节序就行。而需要解析的数据量较大时,手动写struct就太难受了。

安利一个开源工具,可以将dbc自动转换为c代码,使用时直接调其API就行。按照readme编译,需要注意的是这个工具使用了c++17, 你的编译器最好8.0以上。

编译完直接运行就行

$ ./coderdbc <dbc file path> <directory for generated source files (existable)> <prefix (driver name) which will be used for naming dirver parts>

例如:

$ ./dbccoder /home/user/docs/driveshaft.dbc /home/user/docs/gen/ drivedb

使用时需要注意把dbccodeconf.h中的浮点类型定义打开(为了能解析出某些小数类型的signal)

// when USE_SIGFLOAT enabed the sigfloat_t must be defined
typedef double sigfloat_t;

同时打开v2x-config.h中的这个宏

#define V2X_USE_SIGFLOAT

使用时:

v2x_rx_t can_sigs;

int id = v2x_Receive(&can_sigs, frame.data, frame.can_id, frame.len);

switch (id) {
case 0x187:
    printf("speed: %f\n", can_sigs.GW_187.ESP_VehicleSpeed_phys);
    break;
case 0x188:
    // TODO
    break;

default:
    break;
}

猜你喜欢

转载自blog.csdn.net/Drknown/article/details/120066675
CAN