The CAN (Controller Area Network) BUS module is an electronic communication interface used for connecting multiple microcontrollers in applications without a host computer. It is commonly used in automotive and industrial systems for allowing microcontrollers and devices to communicate with each other within a vehicle or machinery without a central computer.
Pin Number | Name | Description |
---|---|---|
1 | VCC | Power supply (5V) |
2 | GND | Ground connection |
3 | CANH | CAN High |
4 | CANL | CAN Low |
5 | RX | Receive data (optional, for some modules) |
6 | TX | Transmit data (optional, for some modules) |
#include <SPI.h>
#include <mcp_can.h>
// Initialize CAN BUS module with CS pin
MCP_CAN CAN(10);
void setup() {
Serial.begin(115200);
// Initialize CAN BUS module at 500kbps speed
if (CAN_OK == CAN.begin(CAN_500KBPS)) {
Serial.println("CAN BUS Shield init ok!");
}
else {
Serial.println("CAN BUS Shield init fail");
Serial.println("Init CAN BUS Shield again");
delay(100);
}
}
void loop() {
// Check if data is available to read
unsigned char len = 0;
unsigned char buf[8];
if (CAN_MSGAVAIL == CAN.checkReceive()) {
CAN.readMsgBuf(&len, buf); // Read data, len: data length, buf: data buffer
unsigned long canId = CAN.getCanId();
Serial.println("-----------------------------");
Serial.print("Get data from ID: 0x");
Serial.println(canId, HEX);
for (int i = 0; i < len; i++) { // Print each byte of the data
Serial.print(buf[i], HEX);
Serial.print("\t");
}
Serial.println();
}
}
Q: Can I use the CAN BUS module with a 3.3V system? A: Some CAN BUS modules are 3.3V compatible, but you must check the specific module's datasheet.
Q: How many devices can be connected to a CAN BUS? A: The CAN specification allows up to 112 nodes, but practical limits are lower and depend on the total bus length and the transceiver used.
Q: What is the maximum length of a CAN BUS network? A: The maximum length depends on the baud rate; for example, at 1 Mbps, the maximum length is typically around 40 meters.
Q: Do I need to use termination resistors? A: Yes, proper termination is critical for preventing reflections and ensuring signal integrity on the CAN bus.