gpt4 book ai didi

c++ - CAN BUS 帧不通过代码发送

转载 作者:太空宇宙 更新时间:2023-11-04 12:48:09 26 4
gpt4 key购买 nike

我有一个通过 SPI 连接 CAN 总线的 Raspberry Pi。我已经安装了 canutils,如果我执行 cansend, Controller 会收到消息并应用,但如果我通过代码执行,则不会。这一定是我在构建框架时做错了什么,所以如果有人能帮助我指出我的错误,我将不胜感激。

这是我发送的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);
}
}

最佳答案

代码基本上有 2 个问题。1. 我应该使用 canfd_frame 结构,并且我应该将值设为 0。这是最后有效的代码

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);
}
}

关于c++ - CAN BUS 帧不通过代码发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50343741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com