嵌入式linux读写can收发简单示例基于socket can

嵌入式linux读写can简单示例

1、查看是否又can驱动
ifconfig –a
2、配置速率
ip link set can0 type cantq 125 prop-seg 6phase-seg1 7 phase-seg2 2 sjw 1
或者
ip link set can0 type can bitrate 125000
3、查看状态
ip -details link show can0
或者
ip -details -statistics link show can0
4、使能
ifconfig can0 up

c编程
需要先配置好速率并启动can

can.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/can.h>
#include <linux/can/raw.h>

static int s;
static struct can_frame frame[2] = {
    
    {
    
    0}};

int can_init(char *dev)
{
    
    
	struct sockaddr_can addr;
 	struct ifreq ifr;
 	
 	s = socket(PF_CAN, SOCK_RAW, CAN_RAW);//创建套接字
	strcpy(ifr.ifr_name, dev);
 	ioctl(s, SIOCGIFINDEX, &ifr); //指定 can设备
 	addr.can_family = AF_CAN;
	addr.can_ifindex = ifr.ifr_ifindex;
	bind(s, (struct sockaddr *)&addr, sizeof(addr));//将套接字与 can绑定

	//禁用过滤规则,本进程不接收报文,只负责发送
	//setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
	//设置过滤规则
	 setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
}

int can_send(unsigned int id, unsigned char *buf, char dlc)
{
    
    
	int tmp = 0;
	
 	frame[0].can_id = id;
	frame[0]. can_dlc = dlc;
	while(tmp < dlc && tmp <= 8)
	{
    
    
			frame[0].data[tmp] = buf[tmp];
			tmp++;
	}
	tmp = 0;
	tmp = write(s, &frame[0], sizeof(frame[0])); //发送 frame[0]
	if(nbytes != sizeof(frame[0]))
	{
    
    
		return -1;
	}
}

int can_readrcv(struct can_frame *frame)
{
    
    
		int tmp = 0;
		
		tmp = read(s, &frame[1], sizeof(frame[1])); //接收报文
		*frame = frame[1];
		
		return tmp;
}

int can_close()
{
    
    
	close(s);
	return 0;
}

main.c

#include <stdio.h>
#include "can.h"

int main()
{
    
    
	unsigned char txbuf[8] = "hello";
	int tmp = 0;
	struct can_frame f_tmp;
	
	can_init("can0",);
	while(1)
	{
    
    
		can_send(0x12, txbuff, 8);
		tmp = can_readrcv(&f_tmp);
		if(tmp > 0)
		{
    
    
			printf("id=%d,dlc=%d,"f_tmp.id,f_tmp.dlc);
			char i = 0;
			while(i < 8)
			{
    
    
				printf("%x ",f_tmp.data[i]);
			}
			printf("\n ");
		}
		sleep(1);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u010835747/article/details/108543172
CAN