首页 > 代码库 > CAN bus的移植

CAN bus的移植

CAN bus的移植
一、首先要阅读相关的文档了解can bus协议;
二、驱动移植,内核中一般是自带相关的can驱动,如果没有可以自行加入;
三、测试,首先下载can bus套件:


fulinux ~$git clone https://git.gitorious.org/linux-can/can-utils.git
fulinux ~$cd can-utils
fulinux ~$ls**** candump.c ***fulinux ~$make


make后有candump执行程序。如果没有can设备,可以通过下面的linux命令来创建一个虚拟的can设备:


fulinux ~$ modprobe can
fulinux ~$ modprobe can_raw
fulinux ~$ modprobe vcan
fulinux ~$ sudo ip link add dev vcan0 type vcan
fulinux ~$ sudo ip link set up vcan0
fulinux ~$ ip link show vcan0
3: vcan0: <NOARP,UP,LOWER_UP> mtu 16 qdisc noqueue state UNKNOWN 
link/can


在编写一个小程序candump-client,配合candump程序一同测试:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h> 
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h> 
#include <linux/can.h>
#include <linux/can/raw.h> 
int
main(void)
{
int s;
int nbytes;
struct sockaddr_can addr;
struct can_frame frame;
struct ifreq ifr; 
char *ifname = "vcan0"; 
if((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
perror("Error while opening socket");
return -1;
} 
strcpy(ifr.ifr_name, ifname);
ioctl(s, SIOCGIFINDEX, &ifr); 
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex; 
printf("%s at index %d\n", ifname, ifr.ifr_ifindex); 
if(bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("Error in socket bind");
return -2;
} 
frame.can_id = 0x123;
frame.can_dlc = 2;
frame.data[0] = 0x11;
frame.data[1] = 0x22; 
nbytes = write(s, &frame, sizeof(struct can_frame)); 
printf("Wrote %d bytes\n", nbytes); 
return 0;
}

同时修改makefile文件,将candump-client程序加入到makefile文件中一起编译:


PROGRAMS = can-calc-bit-timing candump candump-client cansniffer cansend canplayer cangen canbusloadcandump.o: lib.h
candump-client.o: lib.h
candump: candump.o lib.o
candump-client: candump-client.o lib.o


编译:
fulinux ~$make

在两个终端上执行:
fulinux ~$./candump vcan0
fulinux ~$./candump-client

执行结果:


by fulinux
blog: blog.csdn.net/fulinus


CAN bus的移植