码迷,mamicode.com
首页 > 其他好文 > 详细

CAN bus的移植

时间:2014-07-23 13:09:16      阅读:352      评论:0      收藏:0      [点我收藏+]

标签:can   bus   can-utils   candump   

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

执行结果:
bubuko.com,布布扣

by fulinux
blog: blog.csdn.net/fulinus


CAN bus的移植

标签:can   bus   can-utils   candump   

原文地址:http://blog.csdn.net/fulinus/article/details/38060373

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!