- 积分
- 15
贡献99
飞刀26 FD
注册时间2023-2-28
在线时间3 小时
扫一扫,手机访问本帖
|
CAN无法接收
#define CAN0_DEV "can0" //CAN设备映射节点
/** 打开CAN0**/
#define IP_CMD_CAN_OPEN "ifconfig can0 up"
/** 将CAN0波特率设置为500000 bps**/
#define IP_CMD_SET_CAN_PARAMS "ip link set can0 up type can bitrate 500000 sample-point 0.75 dbitrate 4000000 dsample-point 0.8 fd on"
/** 关闭CAN0**/
#define IP_CMD_CAN_CLOSE "ifconfig can0 down"
int can_init(char *dev)
{
struct ifreq ifr = {0};
struct sockaddr_can can_addr = {0};
int ret;
/** 通过system调用ip命令设置CAN波特率**/
system(IP_CMD_CAN_CLOSE); // 必须先关闭CAN,才能成功设置CAN波特率
system(IP_CMD_SET_CAN_PARAMS);
system(IP_CMD_CAN_OPEN);
printf("Set can baud rate success\n");
/** 打开套接字**/
can_fd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if(0 > can_fd) {
perror("socket");
return -1;
}
printf("Open socket success\n");
/** 是否开启回环功能**/
int loopback = 0; // 0 = disabled, 1 = enabled (default)
setsockopt(can_fd, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
/** 指定can0设备**/
strcpy(ifr.ifr_name, CAN0_DEV);
ret = ioctl(can_fd, SIOCGIFINDEX, &ifr);
if(0 > ret){
perror("SIOCGIFINDEX");
close(can_fd);
return -1;
}
can_addr.can_family = AF_CAN;
can_addr.can_ifindex = ifr.ifr_ifindex;
printf("Iotcl SIOCGIFINDEX success\n");
/** 将can0与套接字进行绑定**/
ret = bind(can_fd, (struct sockaddr *)&can_addr, sizeof(can_addr));
if (0 > ret) {
perror("bind");
close(can_fd);
return -1;
}
printf("Bind can success\n");
/** 设置过滤规则**/
setsockopt(can_fd, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0); //禁用过滤规则
printf("Setsockopt success\n");
return 0;
}
int main(void)
{
struct can_frame frame = {0};
int nread, i, ret, len;
struct sockaddr_can addr;
printf("Welcome to can test\n");
if(can_init(CAN0_DEV) == FALSE){
printf("Failed to can initial\n");
return -1;
}
printf("Can initial success\n");
while(1)
{
nread = read(can_fd, &frame, sizeof(frame));
if(nread > 0)
{
printf("[%d] ", frame.can_dlc);
/** 打印数据**/
for (i = 0; i < frame.can_dlc; i++)
printf("%02x ", frame.data[i]);
printf("\n");
nread = 0;
}
}
// close(can_fd);
// return 0;
} |
|