TWAI - Espressif's Built-in CAN Bus Controller
What is TWAI?
TWAI (Two-Wire Automotive Interface) is Espressif's implementation of the CAN (Controller Area Network) bus protocol, built directly into many ESP32 chips. It is compatible with the ISO 11898-1 standard, which means it can communicate on the same bus as other CAN 2.0 devices commonly found in automotive, industrial and robotics applications.
TWAI supports both Standard frames (11-bit identifiers) and Extended frames (29-bit identifiers), with a data payload of up to 8 bytes per frame.
Note: TWAI is not compatible with CAN FD (Flexible Data-Rate) frames. The controller will interpret FD frames as errors.
How Does It Work?
The TWAI controller uses two signal lines - TX and RX - which can be assigned to any available GPIO pins on your board. These pins connect to an external transceiver (see below), which converts the controller's single-ended logic signals into the differential signals used on a CAN bus.
CAN bus uses a multi-master architecture, meaning any node on the bus can transmit without needing a central controller. Messages are prioritised by their identifier - lower IDs have higher priority. This makes it well-suited for real-time systems where some messages are more time-critical than others.
Typical bus speeds range from 25 Kbit/s up to 1 Mbit/s, depending on cable length and bus configuration.
External Hardware Required
The ESP32 does not have a built-in CAN transceiver - it only has the CAN controller. You need an external CAN transceiver module to connect to a physical CAN bus. The transceiver handles converting between the 3.3V logic levels of the ESP32 and the differential signalling on the bus.
Common CAN Transceivers
| Transceiver | Voltage | Notes |
|---|---|---|
| SN65HVD230 (TI) | 3.3V | Popular choice, works directly with ESP32 3.3V logic |
| TJA1050 (NXP) | 5V | Requires a voltage divider or level shifter on the RX line back to the ESP32 |
| TJA1051 (NXP) | 3.3V / 5V | Available in 3.3V variant (TJA1051T/3), good for direct connection |
| MCP2551 (Microchip) | 5V | Common and cheap, but needs level shifting for the RX line |
If using a 5V transceiver, you must level-shift or use a resistor divider on the transceiver's RX output to bring it down to 3.3V before it reaches the ESP32 GPIO. Feeding 5V into an ESP32 pin will damage it.
3.3V transceivers like the SN65HVD230 are the simplest option as they connect directly without any level shifting.
Wiring
The basic wiring is straightforward:
- ESP32 TX GPIO → Transceiver TX input
- Transceiver RX output → ESP32 RX GPIO
- Transceiver CANH / CANL → CAN bus
- 120 ohm termination resistor across CANH and CANL (required at each end of the bus)
Which ESP32 Chips Support TWAI?
| Chip | TWAI Support |
|---|---|
| ESP32 | Yes |
| ESP32-S2 | Yes |
| ESP32-S3 | Yes |
| ESP32-C6 | Yes |
All Unexpected Maker boards based on these chips have TWAI available. You just need to pick two free GPIO pins and connect a transceiver.