MCP2515芯片的使用
樹莓派作為大眾開源硬件转锈,一些高級功能是需要擴(kuò)展的至会,剛剛用到了MCP2515擴(kuò)展CAN總線妇斤,現(xiàn)在總結(jié)如下:
前提:使用內(nèi)核自帶的MCP2515驅(qū)動
1茎截、打開SPI總線
在raspi-config中使能SPI總線
2、修改內(nèi)核啟動文件
dtparam=spi=on
dtoverlay=mcp2515-can0,oscillator=8000000,interrupt=25,spimaxfrequency=1000000
然后重啟系統(tǒng)
3油狂、例程是基于wiringPi
1、初始化代碼如下
int mcp2515_init()
{
memset(&frame, 0, sizeof(struct can_frame));
system("sudo ifconfig can0 down");
delay(10);
system("sudo ip link set can0 type can bitrate 250000");
system("sudo ifconfig can0 up");
//1.Create socket
s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (s < 0) {
perror("socket PF_CAN failed");
return 1;
}
//2.Specify can0 device
strcpy(ifr.ifr_name, "can0");
ret = ioctl(s, SIOCGIFINDEX, &ifr);
if (ret < 0) {
perror("ioctl failed");
return 1;
}
//3.Bind the socket to can0
addr.can_family = PF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
ret = bind(s, (struct sockaddr *)&addr, sizeof(addr));
if (ret < 0) {
perror("bind failed");
return 1;
}
//4.Define receive rules
struct can_filter rfilter[1];
rfilter[0].can_id = 0x18feca33;
rfilter[0].can_mask = CAN_SFF_MASK;
setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
return 0;
}
其中比較重要的幾點(diǎn)就是波特率的設(shè)置寸癌,接收濾波器的設(shè)置
2专筷、接收濾波器設(shè)置
struct can_filter rfilter[1];
rfilter[0].can_id = 0x18feca33;
rfilter[0].can_mask = CAN_SFF_MASK;
經(jīng)此設(shè)置后,MCP2515僅接受擴(kuò)展ID為0x18feca33的報(bào)文
3蒸苇、發(fā)送設(shè)置
發(fā)送部分的代碼摘錄如下:
int mcp2515_write(canframe dataTemp)
{
canframe frame;
frame.can_id = CAN_EFF_FLAG|dataTemp.can_id;
frame.can_dlc = 8;
for (int i = 0; i < 8; i++)
{
frame.data[i]=dataTemp.data[i];
}
nbytes = write(s, &frame, sizeof(frame));
if(nbytes != sizeof(frame)) {
return 0;
}
return 1;
}
CAN_EFF_FLAG表示當(dāng)前發(fā)送擴(kuò)展幀磷蛹,無此項(xiàng)時(shí)為標(biāo)準(zhǔn)幀
4、接收部分
canframe mcp2515_read()
{
canframe dataTemp;
for (int i = 0; i < 100; i++)
{
nbytes = read(s, &frame, sizeof(frame));
if(nbytes > 0) {
dataTemp.can_id=frame.can_id&0x1fffffff;
for (int i = 0; i < 8; i++)
{
dataTemp.data[i]=frame.data[i];
}
return dataTemp;
}
}
}
接收部分最高位為1時(shí)溪烤,表示接收的為擴(kuò)展幀味咳,程序使用的是在線程中查詢接收。