我有一个Raspberry Pi,通过SPI连接CAN总线。我已经安装了canutils
,如果我做了一个cansend,控制器会收到消息并应用,但是如果我通过代码执行它就不会。它必须是我在构建框架时做错的事情,所以如果有人可以帮我指出我的错误,我会很感激。
这是我发送的cansend消息。
cansend can0 01f801f2#1212121223232323
这是我发送相同消息的代码。代码在pthread中运行。
void *CANUpdate(void *userParam)
{
struct sockaddr_can addr;
struct ifreq ifr;
const char *ifname = "can0";
int can_s;
if ((can_s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
{
LogEntry(LOG_ERR, "Error while opening socket\n");
return 0;
}
strcpy(ifr.ifr_name, ifname);
ioctl(can_s, SIOCGIFINDEX, &ifr);
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
if (bind(can_s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
LogEntry(LOG_ERR, "Error in CAN socket bind\n");
return 0;
}
while (!stopServer)
{
if (can_s)
{
struct can_frame frame;
frame.can_id = 0x01f801f2;
frame.can_dlc = 8;
frame.data[0] = 0x12;
frame.data[1] = 0x12;
frame.data[2] = 0x12;
frame.data[3] = 0x12;
frame.data[4] = 0x34;
frame.data[5] = 0x34;
frame.data[6] = 0x34;
frame.data[7] = 0x34;
int res = write(can_s, &frame, sizeof(struct can_frame));
}
msleep(800);
}
}
答案 0 :(得分:0)
代码基本上有2个问题。 1.我应该使用canfd_frame结构,我应该对这些值进行操作。这是最后工作的代码
void *CANUpdate(void *userParam)
{
struct sockaddr_can addr;
struct ifreq ifr;
const char *ifname = "can0";
int can_s;
if ((can_s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
{
LogEntry(LOG_ERR, "Error while opening socket\n");
return 0;
}
strcpy(ifr.ifr_name, ifname);
ioctl(can_s, SIOCGIFINDEX, &ifr);
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
setsockopt(can_s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
if (bind(can_s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
LogEntry(LOG_ERR, "Error in CAN socket bind\n");
return 0;
}
while (!stopServer)
{
if (can_s)
{
struct canfd_frame frame;
memset(&frame, 0, sizeof(frame)); /* init CAN FD frame, e.g. LEN = 0 */
frame.can_id = 0x01f801f2;
frame.len = 8;
if (!(frame.can_id & CAN_ERR_FLAG)) /* 8 digits but no errorframe? */
frame.can_id |= CAN_EFF_FLAG; /* then it is an extended frame */
frame.data[0] = 0x12;
frame.data[1] = 0x12;
frame.data[2] = 0x12;
frame.data[3] = 0x12;
frame.data[4] = 0x34;
frame.data[5] = 0x34;
frame.data[6] = 0x34;
frame.data[7] = 0x34;
if(write(can_s, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame);
LogEntry(LOG_ERR, "Unable to write CAN message\n");
}
msleep(800);
}
}