Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

初始化CAN设备:

Code Block
int can_fd; 
struct
sockaddr_can addr; 
struct ifreq ifr;

can_fd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (can_fd < 0) {
   perror("Socket");
   return 1;
}


设置使用指定的can接口,这里选择can0设备。

Code Block
struct ifreq ifr;

strcpy(ifr.ifr_name, "can0");

/* determine the interface index */
ioctl(s, SIOCGIFINDEX, &ifr);


绑定can接口

Code Block
struct sockaddr_can addr; 

addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
/* bind the socket to a CAN interface */
bind(s, (struct sockaddr *)&addr, sizeof(addr));



收发操作:

CAN设备收发数据是以Frame的结构,在Linux中表示如下:

...

Code Block
struct can_filter {
	canid_t can_id;
	canid_t can_mask;
};

struct can_filter rfilter[1];
rfilter[0].can_id   = 0x550;
rfilter[0].can_mask = 0xFF0;
//rfilter[1].can_id   = 0x200;
//rfilter[1].can_mask = 0x700;

setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));