【完美体育·(中国)手机网页版MYD-Y6ULX-V2开发板】CAN自动发送数据
文章来源: 发布日期:2023.2.24 浏览次数:699 次 |
由评测者“华仔stm32”提供。
前面实现了手工用CAN发送数据的测试,下面用C编程来发送数据。
1、新建can.c:
#include #include #include #include #include #include #include #include #include int main(int argc, char const *argv[]) { int s, nbytes; struct sockaddr_can addr; struct ifreq ifr; struct can_frame frame[2] = {{0}};
s = socket(PF_CAN, SOCK_RAW, CAN_RAW); if (s == -1){ printf("open can error!"); return -1;
} strcpy(ifr.ifr_name, "can0"); ioctl(s, SIOCGIFINDEX, &ifr);
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex; bind(s , (struct sockaddr *)&addr, sizeof(addr)); //禁用过滤规则,本进程不接收报文,只负责发送 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
frame[0].can_id = 0x11;
frame[0].can_dlc = 1;
frame[0].data[0] = 0x11;
frame[1].can_id =0x22;
frame[1].can_dlc = 1;
frame[1].data[0] = 0x22; while(1)
{
nbytes = write(s, &frame[0], sizeof(frame[0])); if(nbytes != sizeof(frame[0]))
{ printf("Send Error frame[0]!\n"); break;
} sleep(1);
nbytes = write(s, &frame[1], sizeof(frame[1])); if(nbytes != sizeof(frame[1]))
{ printf("Send Error frame[1]!\n"); break;
} sleep(1);
} close(s); return 0;
}
交叉编译后上传给开发板,打开CAN分析仪。开发板上手工开启can0:
root@myd-y6ull14x14:~# ip link set can0 type can bitrate 500000
root@myd-y6ull14x14:~# ifconfig can0 up
[ 3303.387293] IPv6: ADDRCONF(NETDEV_CHANGE): can0: link becomes ready
运行cat_test_send: