Skip to content

Demo Code

This page provides the complete Waveshare demo code for both CAN bus and RS-485, in Python and C. These examples are the canonical starting point for verifying your hardware setup.

Terminal window
wget https://files.waveshare.com/upload/4/4e/RS485_CAN_HAT_Code.zip
unzip RS485_CAN_HAT_Code.zip
RS485_CAN_HAT_Code/
├── CAN/
│ ├── python/
│ │ ├── send.py
│ │ └── receive.py
│ └── wiringPi/
│ ├── send/
│ │ ├── can_send.c
│ │ └── Makefile
│ └── receive/
│ ├── can_receive.c
│ └── Makefile
└── 485/
├── python/
│ ├── send.py
│ └── receive.py
└── WiringPi/
├── send/
│ ├── 485_send.c
│ └── Makefile
└── receive/
├── 485_receive.c
└── Makefile

The CAN examples use SocketCAN, the Linux kernel’s native CAN framework. The Python version wraps it with the python-can library; the C version uses raw CAN sockets directly.

CAN/python/send.py
import os
import can
os.system('sudo ip link set can0 type can bitrate 100000')
os.system('sudo ifconfig can0 up')
can0 = can.interface.Bus(channel='can0', bustype='socketcan')
msg = can.Message(arbitration_id=0x123, data=[0, 1, 2, 3, 4, 5, 6, 7], is_extended_id=False)
can0.send(msg)
os.system('sudo ifconfig can0 down')
CAN/python/receive.py
import os
import can
os.system('sudo ip link set can0 type can bitrate 100000')
os.system('sudo ifconfig can0 up')
can0 = can.interface.Bus(channel='can0', bustype='socketcan')
msg = can0.recv(10.0)
print(msg)
if msg is None:
print('Timeout occurred, no message.')
os.system('sudo ifconfig can0 down')

The RS-485 examples use the Pi’s UART (/dev/ttyS0) with GPIO 4 controlling the transceiver direction. The Python version uses pyserial and RPi.GPIO; the C version uses the wiringPi library.

485/python/send.py
import RPi.GPIO as GPIO
import serial
EN_485 = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(EN_485, GPIO.OUT)
GPIO.output(EN_485, GPIO.HIGH)
t = serial.Serial("/dev/ttyS0", 115200)
print(t.portstr)
strInput = input('enter some words:')
n = t.write(strInput.encode())
print(n)
str = t.read(n)
print(str)
485/python/receive.py
import RPi.GPIO as GPIO
import serial
EN_485 = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(EN_485, GPIO.OUT)
GPIO.output(EN_485, GPIO.LOW)
ser = serial.Serial("/dev/ttyS0", 115200, timeout=1)
while True:
str = ser.readall()
if str:
print(str)

Each C example includes a Makefile. To compile:

Terminal window
cd RS485_CAN_HAT_Code/CAN/wiringPi/send
make
sudo ./can_send

The CAN C examples link against standard system libraries. The RS-485 C examples require wiringPi to be installed:

Terminal window
sudo apt-get install wiringpi

For the Python examples, install the required packages:

Terminal window
pip install python-can RPi.GPIO pyserial