OK3568 CAN无法接收
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);
printf("\n");
nread = 0;
}
}
// close(can_fd);
// return 0;
} 首先确认您手上的底板CAN功能是否正常,短接两路can的H和H、L和L,使用命令行candump命令和cansend命令测试本身通讯是否正常,借此确认一下是您手上底板的硬件问题还是您应用用法的问题。 兵兵兵兵鸭 发表于 2023-3-23 10:25
首先确认您手上的底板CAN功能是否正常,短接两路can的H和H、L和L,使用命令行candump命令和cansend命令测试 ...
使用candump和cansend进行测试,正常;但还是不能接收 运行有什么报错吗?将if(can_init(CAN0_DEV) == FALSE)改为if(can_init(CAN0_DEV) != 0)吧 可以看下https://www.cnblogs.com/eaggle/p/7651856.html这个连接,或许对你有所帮助
页:
[1]