Example Code for Arduino-Basic CAN BUS Interrupt Mode
Demonstrates basic CAN BUS receiving and sending functions using interrupt mode. The receiving node uses interrupts to detect incoming data, which is more efficient than polling for fast data.
Hardware Preparation
| Item | SKU / Model | Qty | Link |
|---|---|---|---|
| Arduino UNO | Arduino UNO | 2 | Purchase |
| CAN-BUS Shield V2 | DFR0370 | 2 | Purchase |
| Dupont Cable | — | 4 | — |
Software Preparation
| Item | Version / Description | Link |
|---|---|---|
| Arduino IDE | v1.6.5 | Download |
| CAN-BUS Shield Library | MCP2515 (v2.0) | GitHub |
| Installation Tutorial | Arduino IDE Library Installation | View Guide |
Wiring Diagram

Other Preparation Work
Same as Basic CAN BUS Polling Mode, plus connect the interrupt pin (INT0) of the shield to the Arduino's digital pin 2.
Sample Code
Receiver Code
/***********************************************************
*demo: CAN-BUS Shield, receive data with interrupt mode
* when in interrupt mode, the data coming can't be too fast, must >20ms, or else you can use check mode
* Jansion, 2015-5-27
***********************************************************/
#include <SPI.h>
#include "df_can.h"
const int SPI_CS_PIN = 10;
MCPCAN CAN(SPI_CS_PIN); // Set CS pin
unsigned char flagRecv = 0;
unsigned char len = 0;
unsigned char buf[8];
char str[20];
void setup()
{
Serial.begin(115200);
int count = 50; // the max numbers of initializint the CAN-BUS, if initialize failed first!.
do {
CAN.init(); //must initialize the Can interface here!
if(CAN_OK == CAN.begin(CAN_500KBPS)) // init can bus : baudrate = 500k
{
Serial.println("DFROBOT's CAN BUS Shield init ok!");
break;
}
else
{
Serial.println("DFROBOT's CAN BUS Shield init fail");
Serial.println("Please Init CAN BUS Shield again");
delay(100);
if (count <= 1)
Serial.println("Please give up trying!, trying is useless!");
}
}while(count--);
attachInterrupt(0, MCP2515_ISR, FALLING); // start interrupt
}
void MCP2515_ISR()
{
flagRecv = 1;
}
void loop()
{
if(flagRecv)
{ // check if get data
flagRecv = 0; // clear flag
// iterate over all pending messages
while (CAN_MSGAVAIL == CAN.checkReceive())
{
CAN.readMsgBuf(&len, buf);
for(int i = 0; i<len; i++)
{
Serial.print(buf[i]);Serial.print("\t");
}
Serial.println();
}
}
}
Sender Code
Same as Basic CAN BUS Polling Mode.
Result
Receiver serial port output shows incoming data frame:

Additional Information
Use this mode for data transmission intervals >20ms. For faster data, use polling mode.
Was this article helpful?
