Site Information

 Loading... Please wait...

Blog

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...

CAN, SAE J1939, and NMEA 2000 Development with Raspberry Pi and PiCAN HATs

The Raspberry Pi has evolved far beyond its origins as an educational computer. Today, it serves as a powerful platform for industrial automation, vehicle networking, marine electronics, telematics, data logging, and rapid embedded systems prototyping. When combined with the PiCAN family of Raspberry Pi HATs available from Copperhill Technologies, the Raspberry Pi becomes a versatile CAN [...]

Read More »


ESP32 TWAI Driver Explained: A Practical Guide to CAN Bus Programming

The ESP32 has become one of the most popular microcontrollers for CAN bus applications. Whether you are building industrial controllers, SAE J1939 devices, NMEA 2000 products, robotics systems, or automotive prototypes, the ESP32 provides a powerful and cost-effective platform with a built-in CAN controller. Yet, many developers are confused when they encounter the term TWAI in [...]

Read More »


ESP32S3 CAN & LIN-Bus Board – Accelerating CAN-to-LIN Gateway Development

Modern vehicles and industrial machines increasingly rely on multiple communication networks. While CAN Bus serves as the backbone for critical control systems, LIN (Local Interconnect Network) provides a low-cost solution for intelligent sensors, switches, actuators, and body electronics. In many applications, engineers need a reliable method to exchange data between these two networks. The ESP32S3 CAN [...]

Read More »


Why CAN Bus Refuses to Die: What CAN FD and CAN XL Reveal About the Strength of Classical CAN

For more than 25 years, I have been working with CAN (Controller Area Network) technology. During that time, I have lost count of how many times industry experts, analysts, and technology journalists predicted its imminent demise. First, it was Ethernet. Then came FlexRay. Later, it was Automotive Ethernet. More recently, CAN FD and now CAN XL have been presented [...]

Read More »


CANPico V2 with Pico WH Pre-Installed: Powerful CAN Bus Development in an Ultra-Compact Form Factor

When developing CAN Bus applications, engineers often face a familiar challenge: balancing processing power, development speed, hardware complexity, and physical size. The CANPico V2 with Raspberry Pi Pico WH pre-installed solves all four challenges in a remarkably compact package. Combining the powerful Raspberry Pi Pico WH with a sophisticated CAN interface, the CANPico V2 provides an [...]

Read More »


LIN Bus Development Made Easy: Integrating Automotive LIN Networks with Any UART-Based Embedded System

Modern automobiles contain dozens of electronic control units (ECUs) that communicate with each other to manage everything from engine performance to seat adjustments. While high-speed networks such as CAN Bus handle critical vehicle functions, many automotive subsystems rely on a simpler and less expensive communication technology: the Local Interconnect Network, better known as LIN Bus. For [...]

Read More »


Building NMEA 2000 Devices Has Never Been Easier: Meet the Teensy 4.0 with IPS LCD and NMEA 2000 Connector

Developing NMEA 2000 devices often involves a frustrating combination of custom hardware, display integration, network connectivity, and endless testing. Many engineers and hobbyists spend more time wiring components together than actually developing their applications. The Teensy 4.0 with NMEA 2000 Connector and 240×240 IPS LCD changes that equation completely. By combining a powerful microcontroller, integrated NMEA [...]

Read More »


SAE J1939, CAN Bus, and Embedded Networking — All in One Place

If you work with heavy-duty vehicles, mobile machinery, marine systems, or industrial equipment, chances are you have encountered SAE J1939. Whether you are developing embedded firmware, integrating third-party ECUs, or troubleshooting complex vehicle networks, reliable information and robust tools are essential. That is exactly why we created jcom1939.com. A Dedicated Platform for J1939 Engineering JCOM1939.com was designed as [...]

Read More »


Mastering CAN Bus: Essential Guide to Understanding and Troubleshooting Vehicle Networks

In today’s world of connected vehicles and industrial automation, understanding the details of networked communication protocols has become a pivotal skill for engineers and technicians alike. The book Mastering CAN Scratch: Understanding & Troubleshooting (ISBN/ASIN B0G24Z25RZ) steps into this space by offering a comprehensive, hands-on guide to the widely used Controller Area Network (CAN) bus [...]

Read More »