【新提醒】【米尔王牌产品MYD-Y6ULX-V2开发板试用体验】测试CAN通讯 - 米尔科技 - 电子技术william hill官网
- 广受欢迎的专业电子william hill官网
! (elecfans.com)
前面实现了手工用CAN发送数据的测试,下面用C编程来发送数据。
1、新建can.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/can.h>
#include <linux/can/raw.h>
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:
这样就实现自动给can总结发送数据了。
更多回帖