Hardware setup
Required components
| Component | Recommended model |
|---|---|
| Microcontroller | Arduino Mega 2560 |
| CAN module | MCP2515 + TJA1050 breakout board |
| Bus terminators | 2× 120 Ω resistor |
| Wiring | Twisted pair for CAN_H / CAN_L |
Wiring diagram
The MCP2515 communicates with the Arduino over SPI. On the Arduino Mega, the hardware SPI pins are:
| Arduino Mega | MCP2515 module |
|---|---|
| 5V | VCC |
| GND | GND |
| pin 52 | SCK (SPI clock) |
| pin 51 | SI (MOSI) |
| pin 50 | SO (MISO) |
| pin 53 | CS (Chip Select) |
| pin 2 | INT (interrupt, optional) |
The CS pin is configurable in code. This implementation uses pin 53, the hardware SPI CS on the Mega.
Initialization code
cpp
#include <SPI.h>
#include <mcp_can.h>
const int SPI_CS_PIN = 53;
MCP_CAN CAN(SPI_CS_PIN);
void setup() {
while (CAN_OK != CAN.begin(MCP_ANY, CAN_250KBPS, MCP_8MHZ)) {
delay(100);
}
CAN.setMode(MCP_NORMAL);
}
CAN.begin() parameters:
| Parameter | Value | Description |
|---|---|---|
MCP_ANY |
— | No mask filter (receive all) |
CAN_250KBPS |
250 kbps | Standard J1939 speed for heavy vehicles |
MCP_8MHZ |
8 MHz | Crystal frequency on the module |
Installing the library
Install mcp_can by Cory Fowler from the Arduino IDE library manager, or clone directly:
bash
cd ~/Documents/Arduino/libraries
git clone https://github.com/coryjfowler/MCP_CAN_lib
Important
Always place a 120 Ω resistor between CAN_H and CAN_L at each end of the bus. Without terminators, signal reflections will make the bus unstable.