几个调试SocketCAN的命令

本文介绍如何配置CAN总线接口的波特率,并通过示例代码演示如何使用Linux系统下的socket API进行CAN消息的发送与接收。

设置波特率:

echo 125000 > /sys/class/net/can0/can_bittiming/bitrate


启动can接口:

ifconfig can0 up


查看统计:

cat /proc/net/can/stats


查看can设备的中断统计:

cat /proc/interrupts


另附一段简单的测试代码:

[cpp]  view plain  copy
  1. #include <stdio.h>  
  2. #include <sys/types.h>  
  3. #include <sys/socket.h>  
  4. #include <sys/ioctl.h>  
  5. #include <net/if.h>  
  6.    
  7. #include <linux/can.h>  
  8. #include <linux/can/raw.h>  
  9. #include <string.h>  
  10.    
  11. /* At time of writing, these constants are not defined in the headers */  
  12. #ifndef PF_CAN  
  13. #define PF_CAN 29  
  14. #endif  
  15.    
  16. #ifndef AF_CAN  
  17. #define AF_CAN PF_CAN  
  18. #endif  
  19.    
  20. /* ... */  
  21.    
  22. /* Somewhere in your app */  
  23. int main()  
  24. {   
  25.    /* Create the socket */  
  26.    int skt = socket( PF_CAN, SOCK_RAW, CAN_RAW );  
  27.    
  28.    /* Locate the interface you wish to use */  
  29.    struct ifreq ifr;  
  30.    strcpy(ifr.ifr_name, "can0");  
  31.    ioctl(skt, SIOCGIFINDEX, &ifr); /* ifr.ifr_ifindex gets filled  
  32.                                   * with that device's index */  
  33.    
  34.    /* Select that CAN interface, and bind the socket to it. */  
  35.    struct sockaddr_can addr;  
  36.    addr.can_family = AF_CAN;  
  37.    addr.can_ifindex = ifr.ifr_ifindex;  
  38.    bind( skt, (struct sockaddr*)&addr, sizeof(addr) );  
  39.    
  40.    /* Send a message to the CAN bus */  
  41.    struct can_frame frame;  
  42.    frame.can_id = 0x123;  
  43.    strcpy( frame.data, "foo" );  
  44.    frame.can_dlc = strlen( frame.data );  
  45.    int bytes_sent = write( skt, &frame, sizeof(frame) );  
  46.    
  47.    printf("CAN send %d bytes.\n", bytes_sent);  
  48.   
  49.    /* Read a message back from the CAN bus */  
  50. //   int bytes_read = read( skt, &frame, sizeof(frame) );  
  51. //   printf("CAN recv %d bytes.\n", bytes_read);  
  52.   
  53.    return 0;  
  54. }  
 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值