can20-bus-scanner.ino
C program using the Linux kernel SocketCAN API to read frames on the board's CAN2.0 ports.
The BPI-5202 has two CAN2.0 ports. Under Loongnix, activate the interface with 'ip link set can0 up type can bitrate 500000'. Compile with gcc. This scanner is essential for debugging industrial CAN networks.
can20-bus-scanner.ino
#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>
int main() {
int s;
struct ifreq ifr;
struct can_frame frame;
struct sockaddr_can addr;
// Créer une socket CAN brute
s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (s < 0) {
perror("Socket");
return 1;
}
// Configurer l'interface CAN (ex: can0)
strcpy(ifr.ifr_name, "can0");
if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
perror("SIOCGIFINDEX");
close(s);
return 1;
}
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("Bind");
close(s);
return 1;
}
printf("Scanner CAN activé sur can0...\n");
printf("ID DLC Data\n");
printf("-------------------\n");
while (1) {
int nbytes = read(s, &frame, sizeof(frame));
if (nbytes < 0) {
perror("Read");
break;
}
if (nbytes == sizeof(struct can_frame)) {
printf("%03X %d ", frame.can_id, frame.can_dlc);
for (int i = 0; i < frame.can_dlc; i++) {
printf("%02X ", frame.data[i]);
}
printf("\n");
}
}
close(s);
return 0;
}