- 在本例中,有两个进程,其中一个进程负责报文的发送(标识符为0x11和0x22),另一个进程负责报文的接收和过滤(只接收标识符为0x11的
- 报文)。
- /* 1.报文发送程序 */
- #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 s, nbytes;
- struct sockaddr_can addr;
- struct ifreq ifr;
- struct can_frame frame[2] = {{0}};
- s = socket(PF_CAN, SOCK_RAW, CAN_RAW); //创建套接字
- strcpy(ifr.ifr_name, "can0" );
- ioctl(s, SIOCGIFINDEX, &ifr); //指定can0设备
- addr.can_family = AF_CAN;
- addr.can_ifindex = ifr.ifr_ifindex;
- bind(s, (struct sockaddr *)&addr, sizeof(addr)); //将套接字与can0绑定
- //禁用过滤规则,本进程不接收报文,只负责发送
- setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
- //生成两个报文
- frame[0].can_id = 0x11;
- frame[0]. can_dlc = 1;
- frame[0].data[0] = 'Y';
- frame[0].can_id = 0x22;
- frame[0]. can_dlc = 1;
- frame[0].data[0] = 'N';
- //循环发送两个报文
- while(1) {
- nbytes = write(s, &frame[0], sizeof(frame[0])); //发送frame[0]
- if (nbytes != sizeof(frame[0])) {
- printf("Send Error frame[0]\n!");
- break; //发送错误,退出
- }
- sleep(1);
- nbytes = write(s, &frame[1], sizeof(frame[1])); //发送frame[1]
- if (nbytes != sizeof(frame[0])) {
- printf("Send Error frame[1]\n!");
- break;
- }
- sleep(1);
- }
- close(s);
- return 0;
- }
- /* 2. 报文过滤接收程序 */
- #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 s, nbytes;
- struct sockaddr_can addr;
- struct ifreq ifr;
- struct can_frame frame;
- struct can_filter rfilter[1];
- s = socket(PF_CAN, SOCK_RAW, CAN_RAW); //创建套接字
- strcpy(ifr.ifr_name, "can0" );
- ioctl(s, SIOCGIFINDEX, &ifr); //指定can0设备
- addr.can_family = AF_CAN;
- addr.can_ifindex = ifr.ifr_ifindex;
- bind(s, (struct sockaddr *)&addr, sizeof(addr)); //将套接字与can0绑定
- //定义接收规则,只接收表示符等于0x11的报文
- rfilter[0].can_id = 0x11;
- rfilter[0].can_mask = CAN_SFF_MASK;
- //设置过滤规则
- setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
- while(1) {
- nbytes = read(s, &frame, sizeof(frame)); //接收报文
- //显示报文
- if (nbytes > 0) {
- printf(“ID=0x%X DLC=%d data[0]=0x%X\n”, frame.can_id,
- frame.can_dlc, frame.data[0]);
- }
- }
- close(s);
- return 0;
- }
CAN总线开发实例
最新推荐文章于 2024-06-21 09:36:03 发布