Simple Circuit for CANBUS (TWAI) Communication with Arduino NANO/ESP32 Dev Kit
To create a simple circuit for CANBUS (TWAI) communication using an Arduino NANO or ESP32 Dev Kit, follow these steps:
- Connect the MCP2515 CAN controller to the Arduino/ESP32.
- Connect the terminated CAN bus to the MCP2515.
- Use the appropriate TWAI library for your device.
The Circuit and TWAI Library
The MCP_CAN_lib works perfectly for an Arduino NANO and other AVR-based boards.
However, when using the same library for an ESP32 Dev Kit, you might encounter issues. This is because the SPI pins used by the MCP_CAN_lib for AVR-based boards do not match the ESP32's.
To overcome this, use the library TWAI_Library, specifically designed for the ESP32. The circuit remains the same for both devices.
MCP2515 (CAN controller)
-----------------------------
CS: <----- SPI CS pin
MOSI: <----- SPI MOSI pin
MISO: <----- SPI MISO pin
SCK: <----- SPI SCK pin
INT: <----- interrupt request pin
Setting Up the Arduino IDE
To set up your development environment, follow these steps:
- Install the TWAI_Library in your Arduino IDE.
- Select "ESP32 Dev Module" as your board in the Tools > Board menu.
- Select the appropriate port in the Tools > Port menu.
The Issue
A user reported that their TWAI (CANBUS) library is not working on the ESP32 Dev Kit.
Troubleshooting
Begin by:
- Double-checking your wiring.
- Checking for any issues with the TWAI_Library installation.
#include <TWAI.h>
TWAI twai = TWAI(CS_PIN, MOSI_PIN, MISO_PIN, SCK_PIN, INT_PIN);
void setup() {
Serial.begin(115200);
if (!twai.begin()) {
Serial.println("Failed to initialize TWAI!");
while (1);
}
}
void loop() {
twai.setFilter(TWAI_FILTER_CAN_ID | TWAI_FILTER_MASK_CAN_ID, 0, 0, TWAI_FILTER_MODE_ACCEPT_ALL);
twai.sendMsg(0x15, 0, "Hello World!");
}
- Use the MCP_CAN_lib link for an Arduino NANO/AVR-based boards.
- Use the TWAI_Library link for an ESP32 Dev Kit.
- If your circuit is set up correctly and the TWAI library is installed correctly, and your code still fails, seek further assistance on the Tech Support Site.
References
- TWAI_Library. (2021, June 12). TWAI Library for ESP32. Retrieved from https://github.com/kriswiner/TWAI_Library
- MCP_CAN_lib. (2021, June 12). MCP_CAN_lib. Retrieved from https://github.com/autowp/MCP_CAN_lib