Raspberry Pi CAN Bus: SocketCAN & CAN-FD Setup (2025)

Updated at 14 Aug, 2025

- Wire up Pi + CAN HAT, enable SocketCAN, capture frames and stream to AutoPi Cloud. Includes sample code and troubleshooting tips.

Raspberry Pi CAN Bus: SocketCAN & CAN-FD Setup (2025)

The CAN bus, a robust communication protocol predominantly found in the automotive industry for linking ECUs, has expanded beyond its original scope. It was initially designed for vehicles, however, the versatile CAN bus now plays a crucial role in industrial automation, such as with CANopen, and in a variety of other applications.

Despite the Raspberry Pi's Broadcom SoCs lacking built-in CAN support, the functionality can be effectively added through the use of USB or SPI adapters, allowing this compact yet powerful computer to interface seamlessly with the CAN network.

Keep reading to discover how this integration is achieved.

Raspberry Pi CAN Bus Integration

The Raspberry Pi may be small - about the size of a deck of cards - but it's a complete computer that's become a favorite for DIY enthusiasts and educators alike. Its design is innovative: a single circuit board hosting SoCs that integrate the CPU and GPU, along with RAM, USB ports, and other necessary components, creating an all-encompassing package.

While it doesn't include built-in storage, the Raspberry Pi offers an SD card slot to house the operating system and files.

When it comes to CAN bus integration, the Raspberry Pi steps up through its supportive Linux kernel, which is equipped with SocketCAN drivers. These drivers are compatible with the Microchip MCP2515, a standalone CAN controller that communicates via an SPI interface.

For those looking to leverage the Raspberry Pi in automotive or industrial communications networks, there are specialized add-on boards such as the PiCAN2, PiCAN3, and other variants, including:

  • The 2-Channel Isolated CAN FD Expansion HAT.

  • The MCP2515 CAN Bus Module Board TJA1050.

These expansions unlock the Raspberry Pi's potential to engage with CAN bus systems, making it an even more versatile tool for several of projects.

We look deeper into the world of Raspberry Pi and its CAN bus capabilities, guiding you through how to harness this small device for robust communication tasks.

the raspberry pi board with multiple functionalities

Raspberry Pi Projects with CAN Bus HAT Integration

Integrating a CAN bus HAT with a Raspberry Pi isn't just about expanding capabilities; it's also about ease of use.

HATs, which stand for Hardware Attached on Top, were conceived with the Raspberry Pi in mind, offering a near seamless plug-and-play experience. Each HAT serves a specific purpose - whether it's measuring environmental pressure, powering the Raspberry Pi over ethernet, or facilitating communication over CAN networks.

In Raspberry Pi projects, CAN Bus HATs are particularly noteworthy. These specialized HATs connect to the Raspberry Pi's GPIO pins and interact with the SPI interface, enabling the RPi to join the CAN network with minimal fuss.

An example of such integration is the AutoPi TMU CM4, which is built upon the Raspberry Pi platform. It's a self-contained, scalable unit that uses the can0 protocol through a SocketCAN interface to communicate with vehicle systems.

The versatility of the CAN bus HAT with the Raspberry Pi extends to compatibility with vehicles from different manufacturers. It's designed to work with common protocols such as OBD-II, which is used for onboard diagnostics, and SAE J1939, a standard for truck and bus communication. This broad compatibility underscores the Raspberry Pi's suitability for a wide array of automotive applications, from custom car computers to fleet management systems.

Here are some ways this technology comes to life in Raspberry Pi projects with CAN Bus HAT integration:

  • Automotive Projects: By utilizing the AutoPi device or similar CAN bus HATs, the Raspberry Pi becomes a powerhouse for automotive enthusiasts professionals. It can access and interpret vehicle diagnostics, track real-time telemetry data, and even conduct fleet management.

  • Smart Home and Industrial Automation: The reliable communication facilitated by CAN bus HATs is essential in smart home systems and industrial settings, where the Raspberry Pi can control a wide array of devices, contributing to smarter automation and control.

  • Education and Prototyping: The Raspberry Pi with a CAN Bus HAT is an excellent educational tool for students and a valuable prototyping platform for developers. It allows them to experiment with and understand the intricacies of vehicle communication networks in a tangible, interactive way.

  • Robotics and IoT: In robotics, the precise control enabled by CAN Bus is critical. The Raspberry Pi's ability to serve as an IoT gateway, gathering data from the CAN network and connecting to the internet, paves the way for innovative uses in multiple domains.

The AutoPi device and other CAN bus HATs transform the Raspberry Pi into a highly adaptable device capable of engaging with complex communication systems, demonstrating the potential of this modest computer when merged with the robustness of CAN bus technology.

Whether for personal projects, educational purposes, or commercial applications, the CAN bus equipped with a Raspberry Pi HAT is a testament to the synergy between computing and communication.

How to Install CAN Bus HAT on Raspberry Pi

The integration of CAN bus with Raspberry Pi can seem like a complex task, given that the Raspberry Pi isn't naturally equipped for CAN bus communication. However, the process can be simplified with the right hardware and a bit of know-how.

Here's how you can install a CAN bus HAT on your Raspberry Pi and how we've designed a customized solution with the AutoPi TMU device.

To quantify the gains from an integrated platform, we benchmarked an AutoPi TMU CM4 against a “DIY stack” consisting of a Raspberry Pi 5, MCP2518FD HAT, USB LTE dongle, and discrete buck converter. Both systems ran the same 6.6-kernel and python-can 4.3 stack, logging classic CAN at 500 kbps and CAN FD at 2 Mbps while uploading frames to a cloud collector. The table below shows average results collected over a four-hour drive loop and 24-hour idle soak.

Metric DIY Pi + HAT AutoPi TMU CM4 Delta
Hardware install time ≈ 50 min 8 min -84 %
Boot-to-logging delay 42 s 18 s -57 %
Max CAN FD throughput
(2 Mbps, frames/s)
9 800 11 200 +14 %
LTE upload latency
(128-frame batch, ms)
620 390 -37 %
Average power draw
(logging, W)
5.8 4.1 -29 %
MTBF (24 h soak, faults) 1 kernel hang 0 watchdog ✓

Across all metrics the AutoPi TMU CM4 shows faster deployment, lower latency, and higher reliability, making it the clear choice for production fleets where installation time, power budget, and data continuity matter.

Let's Get Started with Your Raspberry Pi CAN Bus HAT

To get started with CAN bus on your Raspberry Pi, you'll need a CAN bus HAT like an automotive data logger. This device is designed to bridge the gap between your Raspberry Pi and the CAN bus, allowing your projects to communicate effectively with vehicle networks. The Raspberry Pi, renowned for its versatility, does not come ready for CAN bus integration out of the box. Both the hardware (GPIOs) and the default software (Raspbian) do not support CAN bus natively.

Step-by-Step Guide for Installation

Step-by-Step Guide of how Pi CAN Bus is installed via HAT.
  1. Select the Right CAN bus HAT: For our AutoPi device, we've designed a proprietary HAT that includes the necessary IOs to facilitate communication. This HAT utilizes the MCP2518FD CAN controller, which is compatible with Linux and Raspbian, to ensure seamless integration.

  2. Prepare Your Raspberry Pi: Before attaching your CAN bus HAT, make sure your Raspberry Pi is powered off to avoid any electrical damage. Prepare your workspace with all the necessary tools and components within reach.

  3. Attach the CAN bus HAT: Gently align the HAT with the GPIO pins on your Raspberry Pi and press down to secure the connection. Be cautious not to bend any pins.

  4. Install the Necessary Software: With our AutoPi TMU, we've streamlined the software installation process. The SPI Bus acts as a bridge between the Raspberry Pi and the CAN bus, and by employing the MCP2518FD CAN controller, the AutoPi TMU HAT is ready to support CAN FD, which is a faster and more reliable version of the standard CAN protocol.

  5. Configure Your Raspberry Pi: Once the HAT is in place, you'll need to configure your Raspberry Pi to communicate with the HAT. This typically involves enabling the SPI interface and installing the appropriate drivers that are compatible with the MCP2518FD.

  6. Test the Connection: After installing and configuration, it's crucial to test the connection to ensure that the Raspberry Pi is communicating correctly with the CAN bus HAT. Send a test message to check if the setup is functioning as expected.

Manual Step-by-Step SocketCAN Setup

The three code blocks below form a complete SocketCAN integration flow for a Raspberry Pi equipped with an MCP2518FD HAT. The first script handles kernel-overlay activation, module loading, and CAN FD interface bring-up at 500 kbps / 2 Mbps. The second example shows how to read and transmit frames programmatically with python-can, giving you direct access to arbitration IDs, DLC, and payload bytes. The final snippet extends this by streaming each frame—timestamp, ID, DLC, and data—in real time to AutoPi Cloud through the public REST API, enabling remote dashboards, alerts, and long-term storage. Follow the steps in order or copy individual segments to fit your own logging, telematics, or bench-test workflow.


# 1. Enable the SPI bus and MCP2518FD overlay (Pi OS 6.x)
sudo raspi-config nonint do_spi 0
echo "dtoverlay=mcp2518fd,spi0-0,interrupt=25,oscillator=40000000" | \
  sudo tee -a /boot/config.txt
sudo reboot

# 2. After reboot, load kernel modules and confirm detection
sudo modprobe mcp251xfd          # CAN-FD driver
ls /sys/class/net                # should list can0

# 3. Bring up the CAN FD interface at 500 kbps nominal, 2 Mbps data
sudo ip link set can0 down
sudo ip link set can0 up type can \
     bitrate 500000 dbitrate 2000000 \
     fd on sample-point 0.875
ip -details link show can0       # verify settings

# 4. Capture frames (classic + FD) and log to file
candump -L can0 > raw.log &
# … drive or transmit frames …
pkill candump

Parsing Frames in Python


import can

#
# Connect to SocketCAN channel 'can0'.
# python-can auto-detects FD capable interface.
#
bus = can.interface.Bus(channel="can0", bustype="socketcan")

#
# Read 100 frames and print ID, DLC, and payload.
#
for _ in range(100):
    msg = bus.recv(timeout=1)      # blocks up to 1 s
    if msg:
        print(f"ID:0x{msg.arbitration_id:X}  DLC:{msg.dlc}  "
              f"FD:{msg.is_fd}  Data:{msg.data.hex()}")

#
# Transmit a CAN FD frame (ID 0x123, 64-byte payload)
#
tx = can.Message(
    arbitration_id=0x123,
    data=bytes.fromhex("00 " * 64),
    is_fd=True,
    bitrate_switch=True
)
bus.send(tx)

Streaming to AutoPi Cloud


import requests, json, time, os

API_KEY    = os.getenv("AUTOPI_API_KEY")
DEVICE_ID  = os.getenv("AUTOPI_DEVICE_ID")
UPLOAD_URL = f"https://api.autopi.io/v1/dongle/devices/{DEVICE_ID}/canlog/"

headers = {"Authorization": f"Api-Key {API_KEY}"}

def push_frame(msg):
    payload = {
        "ts": int(msg.timestamp * 1000),
        "arbid": msg.arbitration_id,
        "dlc":   msg.dlc,
        "data":  msg.data.hex(),
        "fd":    msg.is_fd
    }
    requests.post(UPLOAD_URL, headers=headers, json=payload, timeout=5)

for frame in bus:
    push_frame(frame)
    time.sleep(0.01)  # throttle API calls

With these snippets you can configure the SPI-attached MCP2518FD HAT, bring up a CAN FD interface under SocketCAN, log traffic for offline review, and stream live frames to AutoPi Cloud for remote analytics and dashboard visualisation.

How the AutoPi TMU Device Simplifies the Process

Setting up a Raspberry Pi for automotive data logging usually involves a stack of add-ons: a CAN controller HAT, a 12 V-to-5 V power regulator, an RTC for voltage-safe shutdown, a GPS module for time-stamping, and then hours of kernel configuration to get SocketCAN and LTE working in harmony. Cable management can become a science project, and every custom wire increases the chance of intermittent faults or electromagnetic interference.

The AutoPi TMU device condenses all of that complexity into a single, automotive-grade enclosure. Inside you’ll find a Raspberry Pi Compute Module 4 paired with dual CAN FD transceivers, an automotive power-conditioning circuit rated from 9 V to 32 V, a GNSS/LTE combo modem, and dedicated GPIO for ignition sensing and safe power-down. The on-board firmware ships with pre-enabled SocketCAN drivers and a watchdog that restarts critical services if anything hangs, so the interface you just brought up in ip link stays up.

Cloud integration is equally streamlined. Once the TMU’s LTE SIM is provisioned, the device registers itself with AutoPi Cloud, exposing secure REST and MQTT endpoints for real-time telemetry, remote firmware updates, and Docker container deployment. That means the Python and cURL examples above can push CAN frames to your dashboard without extra firewall rules or reverse tunnels.

In short, the AutoPi TMU removes the friction points of hardware assembly, power safety, driver configuration, and remote access. You focus on parsing CAN payloads and building applications, while the device handles voltage transients, deep-sleep scheduling, OTA updates, and secure data transport. The next sections dive into exactly how those subsystems work together to turn a weekend wiring project into a production-ready telematics node.

Infographic highlighting Raspberry Pi CAN Bus impact on fleet efficiency and global connectivity.

With the AutoPi TMU device, the complexities of hardware and software integration are significantly reduced. Our device, which capitalizes on the robust Raspberry Pi technology, comes with a custom-made HAT that is outfitted with the required IOs. This HAT ensures that your Raspberry Pi is connected to the CAN Bus and can communicate with vehicles of any origin.

The AutoPi TMU is not just a hardware component; it's a gateway to several of functionalities. It enables your vehicle to connect to the cloud, unlocking a suite of capabilities ranging from GPS tracking and trip logging to remote diagnostics and automation features.

AutoPi Devices

AutoPi Cloud with Device Management

Gain cutting-edge insights - see how AutoPi redefines device management.

Other posts you will like

Build a Raspberry Pi Touchscreen Car Computer (Step-by-Step)
Raspberry Pi DIY

Build a Raspberry Pi Touchscreen Car Computer (Step-by-Step)

Assemble a Pi-based carputer with touchscreen, power, mounting and software setup. Parts list, wiring tips and configuration for a reliable in-car sys ...

J1939 Explained (2025): PGNs, SPNs & Heavy-Duty Diagnostics
Guides

J1939 Explained (2025): PGNs, SPNs & Heavy-Duty Diagnostics

Learn J1939 basics‚ PGNs, SPNs, addressing and tools for heavy-duty trucks and machinery. Examples and troubleshooting tips included.

CAN Bus Explained (2025): Frames, Arbitration & Tools
Guides

CAN Bus Explained (2025): Frames, Arbitration & Tools

Understand identifiers, arbitration, error handling and analyzers used in automotive systems. Practical examples and diagrams.

STILL HAVE QUESTIONS?

Get in touch with us – We're ready to answer any and all questions.

* Mandatory fields

Email our engineers

We are here to help!