Arduino library · Communication

mcp_can: CAN bus through an MCP2515 module

mcp_can, coryjfowler’s version, drives the common blue MCP2515 and TJA1050 module. The MCP2515 is a CAN controller on SPI: the Arduino tells it the bus speed and its crystal frequency, then hands it frames to send and reads the frames it has received. Car hackers use it to read OBD-II data, and robot builders to link motor controllers.

Built in on Mokxi: #include <mcp_can.h> and it builds, with nothing to install. Free, and no account needed.

What mcp_can does

A CAN frame has an ID, 11 bits standard or 29 bits extended, and up to eight data bytes. begin() takes an ID mode, the bit rate and the crystal; setMode(MCP_NORMAL) then takes the chip out of the loopback mode it starts in. sendMsgBuf() sends a frame, checkReceive() tells you one is waiting and readMsgBuf() fetches it. Masks and filters let the chip discard frames you do not care about.

In Mokxi the library compiles for every board except the ATtiny, and the CAN_send example runs on an Uno, but no MCP2515 part is simulated yet. begin() finds no chip answering on the SPI bus and returns CAN_FAILINIT, saying why once, so the sketch prints its own error line and every send fails, just as it would with the module unplugged.

Library Manager namemcp_can
Authorcoryjfowler
Include#include <mcp_can.h>
#include <mcp_can_dfs.h>
Boardsevery board Mokxi compiles for but ATtiny85
In the simulatorBuilds and runs, and says plainly that the hardware behind it is not simulated.

Install it

It builds on every board Mokxi compiles for but ATtiny85.

In Mokxi it is built in: #include <mcp_can.h> and the sketch compiles, with no download, no zip and no Library Manager.

On a real board, install "mcp_can" by coryjfowler from the Arduino IDE’s Library Manager (Sketch, Include Library, Manage Libraries), or add mcp_can to lib_deps in PlatformIO. Mokxi follows the calls of release 1.5.1, so a sketch written here builds there too.

What to know in the simulator: No MCP2515 part is simulated yet: begin() finds no chip on the SPI bus and returns CAN_FAILINIT, saying why once, so the sketch’s own error line prints, and every send fails.

The calls you will use

In the order a sketch meets them.

MCP_CAN CAN0(10)

Creates the controller with its chip select on pin 10, the usual wiring on an Uno.

CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_8MHZ)

Sets up the chip: accept any ID, 500 kbit/s, an 8 MHz crystal. Returns CAN_OK on success, CAN_FAILINIT if the chip did not answer.

CAN0.setMode(MCP_NORMAL)

Leaves configuration and loopback for normal mode, where frames really go on the bus. MCP_LISTENONLY receives without ever sending an acknowledgment.

CAN0.sendMsgBuf(0x100, 0, 8, data)

Sends a frame with ID 0x100, a standard ID (0, or 1 for extended), eight bytes from data. Returns CAN_OK when it was sent.

CAN0.checkReceive()

Returns CAN_MSGAVAIL when a frame is waiting. Wiring the module’s INT pin and reading it is the faster alternative.

CAN0.readMsgBuf(&rxId, &len, rxBuf)

Reads the waiting frame into an ID, a length and an 8-byte buffer. An extended ID comes back with 0x80000000 set.

if (CAN0.checkReceive() == CAN_MSGAVAIL) {
  CAN0.readMsgBuf(&rxId, &len, rxBuf);
  Serial.println(rxId, HEX);
}

CAN0.init_Mask(0, 0, 0x07FF0000)

Sets mask 0 so all 11 ID bits are compared. Use it with filters and begin() in MCP_STDEXT mode.

CAN0.init_Filt(0, 0, 0x01000000)

Sets filter 0 to pass only ID 0x100 under that mask. The chip has two masks and six filters.

Example: CAN_send: a frame every 100 ms, and what happens with no MCP2515 on the bus

On the Arduino Uno R3. It runs in the browser exactly as printed.

sketch.ino · Arduino Uno R3
// CAN Send Example
//

#include <mcp_can.h>
#include <SPI.h>

MCP_CAN CAN0(10);     // Set CS to pin 10

void setup()
{
  Serial.begin(115200);

  // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
  if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK) Serial.println("MCP2515 Initialized Successfully!");
  else Serial.println("Error Initializing MCP2515...");

  CAN0.setMode(MCP_NORMAL);   // Change to normal mode to allow messages to be transmitted
}

byte data[8] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};

void loop()
{
  // send data:  ID = 0x100, Standard CAN Frame, Data length = 8 bytes, 'data' = array of data bytes to send
  byte sndStat = CAN0.sendMsgBuf(0x100, 0, 8, data);
  if(sndStat == CAN_OK){
    Serial.println("Message Sent Successfully!");
  } else {
    Serial.println("Error Sending Message...");
  }
  delay(100);   // send data per 100ms
}

/*********************************************************************************************************
  END FILE
*********************************************************************************************************/

Open it in the editor, wired and ready to run

Common errors and how to fix them

Error Initializing MCP2515...

begin() got no answer over SPI. Check the wiring (SCK 13, MISO 12, MOSI 11 and CS on an Uno), that the CS pin in the constructor matches, and that the module has 5V. In Mokxi this always prints, because the MCP2515 is not simulated yet.

begin() succeeds but no frames arrive, or the bus speed seems wrong

The crystal argument does not match the module. Most cheap blue boards carry an 8 MHz crystal, so MCP_16MHZ makes every bit rate half or double what you asked. Read the marking on the crystal and pass MCP_8MHZ or MCP_16MHZ to match.

Error Sending Message... on every frame

CAN needs at least one other node to acknowledge each frame, and 120 ohm termination at both ends of the bus. With a single module and nothing else on the bus, every send fails; connect a second node or test first in MCP_LOOPBACK mode.

Questions and answers

Can I read my car’s OBD-II port with this?

Yes, most cars since 2008 use CAN at 500 kbit/s on pins 6 and 14 of the OBD-II connector. You send a request frame to ID 0x7DF and read the answer from 0x7E8. Use listen-only mode while you learn, to avoid disturbing the car.

Try mcp_can without installing anything

Open the example, change the sketch, and keep your version in a free account.