CAN-BUS Raspberry-pi
From emboxit
- RPi CANBus at http://elinux.org
- integrate improved SPI with less latencies by using RealTime threads
Simple C++ Code
- Simple read/write to CANbus
- Compiled in R-Pi with GCC
<cpp>
#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> #include <iostream> using namespace std; int main(void) { int s; int i; int nbytes; struct sockaddr_can addr; struct can_frame frame; struct ifreq ifr; char *ifname = "can0"; if((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) { cout<<"Error while opening socket"<<endl;
return -1;
} strcpy(ifr.ifr_name, ifname); ioctl(s, SIOCGIFINDEX, &ifr); addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; cout<<ifname<<"at index"<<std::dec<<ifr.ifr_ifindex<<endl; if(bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { cout<<"Error in socket bind"<<endl; return -2; } //write data no remote request frame.can_id = 0x802D1012; frame.can_dlc = 1; frame.data[0] = 0xFF; frame.data[1] = 0x22; nbytes = write(s, &frame, sizeof(struct can_frame)); cout<<"Wrote "<<std::dec<<nbytes<< "bytes"<<endl; nbytes = read(s, &frame, sizeof(struct can_frame)); cout<<"READ FRAME "<<std::dec<<nbytes<< "bytes"<<endl; cout<<"CANID "<<std::hex<<frame.can_id<<endl; cout<<"NUMBER OF DATA "<<std::dec<<(int)frame.can_dlc<<endl; for (i=(int)frame.can_dlc;i>0;i--)
cout<<"DATA PACKAGE["<<std::dec<<(int)frame.can_dlc-i<<"]:"<<std::hex<<(int)frame.data[(int)frame.can_dlc-i]<<endl;
//write data remote request frame.can_id = 0xC02C0005; frame.can_dlc = 0; frame.data[0] = 0x11; frame.data[1] = 0x22; nbytes = write(s, &frame, sizeof(struct can_frame)); cout<<"Wrote "<<std::dec<<nbytes<< "bytes"<<endl; nbytes = read(s, &frame, sizeof(struct can_frame)); cout<<"READ FRAME "<<std::dec<<nbytes<< " bytes"<<endl; cout<<"CANID "<<std::hex<<frame.can_id<<endl; cout<<"NUMBER OF DATA "<<std::dec<<(int) frame.can_dlc<<" "<<endl; for (i=(int)frame.can_dlc;i>0;i--)
cout<<"DATA PACKAGE["<<std::dec<<(int)frame.can_dlc-i<<"]:"<<std::hex<<(int)frame.data[(int)frame.can_dlc-i]<<endl;
return 0; }
</cpp>
Gallery