CAN Laboratuvarları
Bu sayfanın teknik içeriği İngilizcedir.
SocketCAN exposes CAN controllers as Linux network interfaces. Applications bind an AF_CAN socket to an interface index. A CAN_RAW socket reads or writes controller-level frame objects, with optional receive filters, error reports and FD support. ip configures the interface, while can-utils and the example program below use those sockets for traffic. Linux SocketCAN API.
Use a Linux host or Linux VM with iproute2 and can-utils. The first three exercises use an explicitly named virtual interface. The Raspberry Pi exercise uses a separate, isolated two-node bench.
Create a virtual CAN link
Run these commands on Linux with administrative access. If vcan is built into the kernel, skip the module load. If the interface name already exists, stop and use a fresh lab environment. Continue only after ip confirms the link kind is vcan and the flags include UP.
sudo modprobe vcan
sudo ip link add dev vcan-wire type vcan
sudo ip link set dev vcan-wire up
ip -details link show dev vcan-wire
Start the receiver first in terminal A. It exits after two frames. Send in terminal B.
# Terminal A
candump -L -n 2 vcan-wire
# Terminal B
cansend vcan-wire 123#1122
cansend vcan-wire 00000123#3344
Look for timestamped lines ending in 123#1122 and 00000123#3344. The textual widths distinguish the 11-bit and 29-bit formats even though the numeric identifiers match. If the receiver missed one, restart it and repeat both sends. Virtual CAN exercises the Linux API and log format. It has no physical bitrate, arbitration, ACK slot, termination, or on-wire error behavior. See the SocketCAN documentation and can-utils command sources.
Optional FD check on an FD-capable virtual link. Check the reported MTU before transmitting. If it is 16, configure it for CAN FD with these commands. If your kernel refuses the MTU change, skip this step.
sudo ip link set dev vcan-wire down
sudo ip link set dev vcan-wire mtu 72
sudo ip link set dev vcan-wire up
ip -details link show dev vcan-wire
Start candump -L -n 1 vcan-wire before sending cansend vcan-wire 321##10102030405060708090A0B0C. The double hash introduces the FD flags nibble 1 (BRS), followed by 12 bytes. Check that the log preserves the FD marker and flag. The virtual link does not switch a physical bit rate. See the CAN FD reference.
Generate, log, filter and replay
Use the virtual interface created above. In terminal A, create a fresh directory and start the receiver. In terminal B, generate exactly ten Classical frames. The filter matches identifier 123 in standard data format. Mask bits 0x80000000 and 0x40000000 require EFF and RTR to be clear.
# Terminal A
lab_dir=$(mktemp -d)
cd "$lab_dir"
candump -L -n 10 vcan-wire,123:C00007FF > lab.log
# Terminal B
cangen vcan-wire -g 100 -I 123 -L 2 -D 1122 -n 10
After the receiver exits, run wc -l lab.log. Expect ten lines for 123#1122 and intervals around 100 ms. Analyze lab.log in the capture analyzer and check for ten frames, nine intervals and a single standard data stream. OS scheduling and timestamping can shift the intervals.
Start another candump -L -n 10 vcan-wire in terminal B, then replay from the directory containing lab.log. The explicit interface mapping keeps replay on the virtual device. Compare the frame sequence and timestamp differences between the original and replay.
canplayer -I lab.log vcan-wire=vcan-wire
If you generate fewer frames or filter them out, stop the receiver with Ctrl+C. Keep the log for comparison or remove it when finished. Avoid replaying a bench recording through physical interfaces.
Send and receive one frame through the Linux API
Save socketcan-lab.c on the Linux host. It opens and binds a raw CAN socket to vcan-wire, installs an exact standard data-frame filter, and reads or writes a Classical struct can_frame. Build with your system C compiler.
cc -std=c11 -Wall -Wextra -Werror socketcan-lab.c -o socketcan-lab
# Terminal A
./socketcan-lab rx
# Terminal B, within ten seconds
./socketcan-lab tx
Expect 123#1122 in each terminal. TX output confirms that Linux accepted the write and RX confirms delivery to the receiving socket. Repeat with strace -e trace=socket,bind,setsockopt,read,write ./socketcan-lab rx in terminal A. Identify the CAN socket's file descriptor and follow it from socket to bind and the 16-byte frame read. If the receive times out, start it again and send within ten seconds. See Execmap's runtime analysis guide to distinguish process activity from protocol evidence.
After the virtual exercises, stop any remaining captures with Ctrl+C and delete the interface you created. Retain or remove the compiled binary and lab log as needed.
sudo ip link delete dev vcan-wire
Raspberry Pi 4 and MCP2515 on an isolated Classical CAN bench
Use a Pi 4, a documented MCP2515 SPI module with a suitable high-speed CAN transceiver, and a second known-good high-speed Classical CAN node that can transmit and ACK. The Pin Atlas Raspberry Pi 4 board profile identifies the Pi header and SPI alternate functions. Use your module's specific schematic and component markings for the other end of each connection. The MCP2515 is a Classical CAN controller. Any FD-capable peer in this exercise must send Classical frames.
- Verify logic and power before making connections. Check the module revision, oscillator marking, regulator and supply requirements, the controller's I/O voltage, logic translation in each direction, and the transceiver supply and normal-mode configuration. Verify that every signal driven into the Pi, including MISO and interrupt, is 3.3 V compatible. Allow for module boards that combine a 5 V transceiver with different logic arrangements. If documentation cannot establish compatibility, choose a documented module before powering the Pi.
- Map SPI with power off. Verify SPI clock, MOSI, MISO, chip select, interrupt, power and ground against the module schematic and Pin Atlas. Write down the selected SPI chip select and the BCM GPIO number for interrupt. Check for assignments already used by the OS or other hardware. Keep SPI leads short.
- Wire and measure the trunk. Connect CAN_H to CAN_H and CAN_L to CAN_L using a short twisted pair. Follow both transceivers' reference and grounding requirements, including isolation boundaries, and add the required reference connection on a non-isolated bench. Keep this bench separate from vehicle, industrial or other operational networks. Confirm one 120 Ω termination at each end, accounting for onboard resistors. On an unpowered conventional trunk, expect around 60 Ω across CAN_H and CAN_L.
- Configure the device tree. Back up the active Raspberry Pi boot configuration. On Raspberry Pi OS see the boot configuration reference for
/boot/firmware/config.txt. Check the installed overlay help withdtoverlay -h mcp2515-can0for SPI0 CE0 or the alternative that matches your wiring. For SPI0 CE0 the template below is illustrative. Replace every uppercase placeholder with verified values before saving. Choose an SPI speed within the module/controller limits for your voltage and setup, and give the actual oscillator frequency in Hz. Reboot and confirm the driver bound.dtparam=spi=on dtoverlay=mcp2515-can0,oscillator=OSCILLATOR_HZ,interrupt=BCM_GPIO,spimaxfrequency=SPI_HZip -brief linkshould list a CAN interface. Checksudo dmesg | grep -Ei 'mcp251|spi'for driver probe errors. Resolve SPI, power, oscillator and IRQ configuration before testing the CAN pair. - Bring up both nodes at the same nominal rate. Use 125 kbit/s if both nodes support it for this bench. Substitute the interface you identified for
can0. Start the peer in normal mode so it can ACK. Take a snapshot of both nodes' timing and error counters before sending.sudo ip link set dev can0 down sudo ip link set dev can0 type can bitrate 125000 restart-ms 0 sudo ip link set dev can0 up ip -details -statistics link show dev can0 - Verify reception in both directions. Start
candump -L 'can0,0:0,#FFFFFFFF'on the receiving node using its own interface name. From the other node sendcansend can0 123#1122with the sender's interface. Expect123#1122in the peer's log. Reverse the roles and send124#3344. Check that the counters stay stable. If the exchange fails, bring the sender down to stop any retries and follow the troubleshooting workflow.
Stop the captures, bring the lab CAN interfaces down and shut down power before rewiring or disconnecting anything. If the overlay was temporary, restore the boot configuration for your next boot. The lab confirms this specific two-node setup. Use the Microchip MCP2515 datasheet, Raspberry Pi overlay reference, and TI CAN physical layer report for component and topology checks.
Inspect controller error counters
On the isolated two-node bench, distinguish the controller’s current state and transmit/receive error counters from cumulative Linux interface statistics. Use an already working link with an identified CAN interface and a second node in normal mode. Substitute the bench interface for can0.
# Capture terminal
candump -e -d 'can0,0:0,#FFFFFFFF'
# Measurement terminal
ip -details -statistics link show dev can0 > counters-before.txt
cansend can0 123#1122
ip -details -statistics link show dev can0 > counters-after.txt
diff -u counters-before.txt counters-after.txt
Confirm that the peer captured the known frame. A healthy exchange typically leaves the controller error-active and error counters stable while transmit or receive packet totals increase. Look for changes in bus-errors, error-pass, bus-off and socket drop notices. berr-counter tx and rx report current error confinement counters where the driver exposes them. Successful transfers can reduce those counters. Socket drops describe capture delivery, while bus errors come from the controller or driver.
If the driver omits counters or error reports, record that limitation and use the peer capture and physical measurements. Use the error-state workflow if the state changes. Stop candump with Ctrl+C and save or remove the two snapshots. Follow the bench shutdown steps after the exercise. See the SocketCAN device statistics and error message documentation.