CAN bus dashboard (MCP2515)
Read engine-speed frames from another node on a CAN bus, show them, and send a status frame back.
Communication · Advanced
In a real product: Car dashboard (Automotive): The cluster reads engine speed from the CAN bus and reports its own status back.
A car's engine, brakes, doors and dashboard share one pair of wires: the CAN bus. Every node hears every frame, and each frame's identifier says what it carries. An MCP2515 module puts an Arduino on that bus.
What you'll learn
- Setting a CAN controller's bit rate for its crystal and the bus speed
- Sending and receiving frames, and filtering by identifier
- Why a node alone on a bus cannot send: acknowledgement and error counters
How it works
The CAN node in the circuit is another ECU: every 100 ms it sends identifier 0x0C0 with the engine speed in its first two bytes (high byte first). The sketch sets 500 kbit/s for the module's 8 MHz crystal, receives frames, and keeps only 0x0C0. Above 4000 rpm it lights the shift light and sends a status frame, 0x3E8, with one byte: 1 for "shift".
A frame needs at least one other node to acknowledge it. Remove the CAN node and every send fails, while the module's transmit error counter climbs to error passive: that is the first thing to check on a silent bus.
Try this
- Click the CAN node while it runs and raise its value past 4000 rpm: the LED lights and the node receives 0x3E8.
- Set the module's crystal to 16 MHz without changing the sketch: the bit rate is off and nothing gets through.
- Use
setFilterMask()andsetFilter()so the MCP2515 itself drops every frame but 0x0C0.
sketch.ino
// A CAN dashboard: MCP2515 on SPI (CS 10) at 500 kbit/s, 8 MHz crystal. Reads rpm from 0x0C0, shift light on 7.
#include <SPI.h>
#include <mcp2515.h>
MCP2515 can(10);
struct can_frame frame;
bool shift = false;
void setup() {
Serial.begin(9600);
pinMode(7, OUTPUT);
can.reset();
can.setBitrate(CAN_500KBPS, MCP_8MHZ);
can.setNormalMode();
Serial.println("Listening on the CAN bus");
}
void sendStatus(bool on) {
struct can_frame status;
status.can_id = 0x3E8;
status.can_dlc = 1;
status.data[0] = on;
if (can.sendMessage(&status) != MCP2515::ERROR_OK) Serial.println("Status frame not sent");
}
void loop() {
if (can.readMessage(&frame) != MCP2515::ERROR_OK) return;
if (frame.can_id != 0x0C0 || frame.can_dlc < 2) return;
unsigned int rpm = (frame.data[0] << 8) | frame.data[1];
Serial.print("Engine ");
Serial.print(rpm);
Serial.println(" rpm");
bool now = rpm > 4000;
if (now != shift) {
shift = now;
digitalWrite(7, shift);
sendStatus(shift);
}
}