Site Information

 Loading... Please wait...

Programming PiCAN Boards with Python: A Practical Guide for Raspberry Pi CAN Applications

Posted by Wilfried Voss on

Programming PiCAN Boards with PythonThe Raspberry Pi has become one of the most popular platforms for developing CAN bus applications. Whether you are working with industrial equipment, agricultural machinery, marine electronics, automotive systems, or SAE J1939 networks, combining a Raspberry Pi with a PiCAN board provides a powerful and cost-effective development platform.

One of the biggest advantages of this setup is the ability to write CAN applications in Python. Python's simplicity, extensive library ecosystem, and rapid development capabilities make it an excellent choice for CAN bus monitoring, data logging, diagnostics, gateways, and IoT applications.

In this article, we will explore how to program PiCAN boards using Python and the SocketCAN interface available on Linux-based systems.

What Is a PiCAN Board?

PiCAN boards are CAN bus interface boards designed specifically for the Raspberry Pi. They typically connect directly to the Raspberry Pi's GPIO header and provide one or more CAN interfaces.

Popular PiCAN models include:

Most PiCAN boards are based on the Microchip MCP2515 CAN controller for Classical CAN or the MCP2517FD/MCP2518FD controllers for CAN FD applications.

Once installed and configured, the board appears as a standard Linux CAN network interface.

For example:

can0

or

can1

This allows applications to use the standard SocketCAN API.


Why Use Python?

Python offers several advantages for CAN development:

  • Fast development time
  • Excellent readability
  • Large selection of libraries
  • Easy integration with databases and cloud services
  • Ideal for prototyping and production systems alike

Typical applications include:

  • CAN bus monitoring
  • SAE J1939 data collection
  • Data logging
  • CAN-to-MQTT gateways
  • Fleet management systems
  • Predictive maintenance
  • CAN protocol testing
  • Industrial automation

Preparing the Raspberry Pi

Before writing Python code, the PiCAN board must be configured.

After enabling the PiCAN driver and rebooting, verify the interface:

ifconfig

or

ip link show

You should see:

can0

Configure the CAN interface:

sudo ip link set can0 up type can bitrate 250000

Verify operation:

ip -details link show can0

If everything is working correctly, the interface is ready for Python applications.


Installing the Python CAN Library

The most widely used Python CAN library is:

python-can

Installation is simple:

pip install python-can

Verify installation:

python -c "import can"

If no errors appear, the library is ready.


Receiving CAN Messages

The following example continuously listens for CAN messages.

import can

bus = can.interface.Bus(
    channel='can0',
    interface='socketcan'
)

while True:
    message = bus.recv()

    if message:
        print(message)

Typical output:

Timestamp: 1749068205.123456
ID: 18F00400
DLC: 8
Data: FF FF FF FF FF FF FF FF

This creates a simple CAN bus monitor using only a few lines of code.


Sending CAN Messages

Transmitting messages is equally straightforward.

import can

bus = can.interface.Bus(
    channel='can0',
    interface='socketcan'
)

msg = can.Message(
    arbitration_id=0x123,
    data=[1,2,3,4,5,6,7,8],
    is_extended_id=False
)

bus.send(msg)

print("Message sent")

The message immediately appears on the CAN bus.


Working with Extended CAN Identifiers

Many industrial protocols use 29-bit identifiers.

Examples include:

  • SAE J1939
  • NMEA 2000
  • ISOBUS

Sending an extended frame:

msg = can.Message(
    arbitration_id=0x18F00400,
    data=[0,0,0,0,0,0,0,0],
    is_extended_id=True
)

bus.send(msg)

The key parameter is:

is_extended_id=True

Without it, the message would be transmitted as an 11-bit identifier.


Message Filtering

Instead of processing every message, you can filter for specific identifiers.

Example:

filters = [
    {"can_id": 0x18F00400,
     "can_mask": 0x1FFFFFFF,
     "extended": True}
]

bus.set_filters(filters)

Now only matching messages are received.

This dramatically reduces CPU load on busy networks.


Logging CAN Traffic

One common application is data logging.

import can

bus = can.interface.Bus(
    channel='can0',
    interface='socketcan'
)

logfile = open("canlog.txt", "w")

while True:
    msg = bus.recv()

    if msg:
        logfile.write(str(msg) + "\n")
        logfile.flush()

This creates a simple CAN recorder.

For production systems, consider storing data in:

  • SQLite
  • PostgreSQL
  • InfluxDB
  • MySQL

Decoding SAE J1939 Messages

Many PiCAN users work with heavy-duty vehicles and industrial equipment.

A J1939 identifier contains:

  • Priority
  • PGN
  • Source Address

Example:

can_id = 0x18F00400

pgn = (can_id >> 8) & 0x3FFFF

print(hex(pgn))

Output:

0xF004

PGN 61444 represents:

Electronic Engine Controller 1 (EEC1)

which contains Engine Speed.

Using Python, developers can quickly build custom J1939 monitors, gateways, and diagnostic tools.


Building a CAN-to-MQTT Gateway

Python excels at IoT applications.

A common architecture is:

Vehicle CAN Bus
        │
     PiCAN
        │
 Raspberry Pi
        │
     Python
        │
      MQTT
        │
 Cloud Server

Applications include:

  • Remote diagnostics
  • Fleet management
  • Predictive maintenance
  • Equipment monitoring

Python libraries such as:

python-can
paho-mqtt

make implementation relatively straightforward.


Multithreaded CAN Applications

Production applications often separate:

  • Message reception
  • Data processing
  • Database storage
  • Network communication

Python's threading module can help:

import threading

This prevents CAN reception from being blocked by slower tasks such as database writes or cloud communication.


CAN FD Considerations

If you are using a PiCAN FD board, additional configuration may be required.

Example:

sudo ip link set can0 up \
type can bitrate 500000 \
dbitrate 2000000 fd on

Python-CAN supports CAN FD frames through additional message parameters.

Example:

msg = can.Message(
    arbitration_id=0x123,
    data=bytes(range(32)),
    is_fd=True
)

This enables payloads larger than the traditional 8-byte CAN frame.


Debugging Tools

Useful Linux tools include:

Receive messages:

candump can0

Send messages:

cansend can0 123#1122334455667788

Monitor interface statistics:

ip -details -statistics link show can0

These tools are invaluable when troubleshooting hardware and software issues.


Performance Expectations

The Raspberry Pi can handle surprisingly heavy CAN workloads.

Typical applications include:

  • Thousands of messages per second
  • Real-time monitoring
  • Protocol gateways
  • Data logging
  • Cloud connectivity

However, developers should remember that Linux is not a hard real-time operating system.

For deterministic timing requirements, a microcontroller-based solution may be more appropriate.


Conclusion

Combining a Raspberry Pi, a PiCAN board, and Python provides one of the fastest and most flexible ways to develop CAN bus applications. Thanks to Linux SocketCAN and the Python-CAN library, developers can build sophisticated CAN monitoring, logging, diagnostics, gateway, and IoT solutions with relatively little code.

Whether you are working with SAE J1939, NMEA 2000, ISOBUS, industrial CAN systems, or proprietary protocols, Python on a Raspberry Pi offers an excellent platform for experimentation, prototyping, and even deployment-grade applications.

The combination of low hardware cost, extensive software support, and rapid development capabilities explains why Raspberry Pi and PiCAN boards have become a favorite platform among CAN bus developers worldwide.


Python 3: The Comprehensive Guide to Hands-On Python ProgrammingPython 3: The Comprehensive Guide to Hands-On Python Programming

Master Python with this comprehensive guide for both beginners and experienced programmers. Learn the fundamentals of Python 3, including functions, modules, object-oriented programming, and data types, then progress to advanced topics such as GUI development, networking, Django, debugging, and optimization. Packed with practical examples and downloadable source code, this hands-on reference provides everything you need to build professional Python applications.

Highlights

  • Complete coverage of Python 3 fundamentals
  • Functions, classes, modules, and data structures
  • Practical use of Python’s Standard Library
  • Advanced topics including GUIs, networking, Django, and scientific computing
  • Downloadable code examples for hands-on learning

Whether you're writing your first script or developing complex applications, this guide will help you become a confident Python programmer. More information...