Hello,
I'm trying to use the peak CAN/USB adapter. I've been using the chardev
device, but am trying to switch to the netdev method.
Hello,
I actually do the same jobs as you for the pcan(usb).
First: warning : In NETDEV mode compilation of the pcan driver access to
/dev/pcan32 (for example) work for writing but not any more for reading
! (it's notify in the pcan documentation).
As far as I can tell this means that I've installed the driver and device
correctly.
As I have no idea how to use the netdev method I have no way of reading/writing
CAN Frames.
Is there an example I can download someplace? Documentation I can read?
Normally, in the Linux documentation directory you'll find everything
you need to use SocketCAN (browse to linux/Documentation/networking/can.txt)
A basic sample code for you :
#include <fcntl.h>
#include <linux/socket.h>
#include <linux/if.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#include <linux/can/error.h>
in main for example :
// #define NON_BLOCK 1 // Uncomment if you want non blocking
socket (for read/write)
int sfd;
struct sockaddr_can addr;
struct ifreq ifr;
// open part SocketCAN
sfd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if(sfd<0){
perror("socket : ");
return -1;
}
#if NON_BLOCK // Define socket as non-blocking socket
fcntl(sfd, F_SETFL , O_NONBLOCK);
#endif
strcpy(ifr.ifr_name, "can0"); // "can0" is the name of the CAN
network interface
ioctl(sfd, SIOCGIFINDEX, &ifr);
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
// Bind the socket
if(bind(sfd, (struct sockaddr *)&addr, sizeof(addr))<0){
perror("bind: ");
close(sfd);
return -1;
}
// Part if you want the CAN_ERROR frames for reading
can_err_mask_t err_mask = CAN_ERR_MASK;
setsockopt(sfd, SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &err_mask,
sizeof(err_mask));
//-- To send and receive frame: --
ssize_t nbytes=0;
// Frame to send (example)
struct can_frame frame_wr = {
.can_id=0x264,
.can_dlc=2,
.data = { 0x11, 0x22 },
};
struct can_frame frame_rd;
nbytes = write(sfd, &frame_wr, sizeof(struct can_frame)); // Send a
CAN frame
....
// You can you select or other standard API for waiting CAN frame
to read for example..
....
nbytes = read(sfd, &frame_rd, sizeof(struct can_frame)); // Read a
CAN frame
...
// Close the SocketCAN
close(sfd);
It work perfectly with a PCAN USB and other CAN driver that allow using
SocketCAN
I hope this example will help you,
Vincent BRACH
_______________________________________________
Socketcan-users mailing list
[email protected]
https://lists.berlios.de/mailman/listinfo/socketcan-users