CAN

CAN (Controller Area Network)

Best for: Automotive and harsh industrial networks requiring real-time, highly reliable, multi-master communication.

How it works: Uses differential signaling like RS485 but operates on a token-based, prioritized message system (no traditional master/slave). If two nodes attempt to send a message at the same time, the node with the higher priority message automatically wins and the lower priority node steps back. It has advanced, built-in error checking and node isolation.

Speed: Up to 1 Mbps (Standard CAN) or up to 8 Mbps (CAN FD - Flexible Data-rate).

Distance: Up to 40 meters at 1 Mbps; much longer at reduced speeds (e.g., 500 meters at 125 kbps).

CAN and CAN FD Technical Reference Guide

This document provides a comprehensive technical overview of the physical layer, message framing structure, bus arbitration, and error handling mechanisms of the Controller Area Network (CAN) interface, alongside an architectural breakdown of CAN FD compatibility.


1. CAN Physical Connection

The CAN (Controller Area Network) bus is a high-reliability, differential signaling, multi-master serial bus protocol. It allows multiple microcontrollers (nodes) to communicate with one another without a centralized host computer.

A standard CAN network requires exactly two wires plus a shared ground line:

  • CAN_H (CAN High): One half of the differential signaling line pair.
  • CAN_L (CAN Low): The opposing half of the differential signaling line pair.
       Node 1                      Node 2                      Node 3
 +-----------------+         +-----------------+         +-----------------+

 |  Micro/CAN-Ctrl |         |  Micro/CAN-Ctrl |         |  Micro/CAN-Ctrl |
 +--------+--------+         +--------+--------+         +--------+--------+

          | (TX/RX)                   | (TX/RX)                   | (TX/RX)
 +--------+--------+         +--------+--------+         +--------+--------+

 | CAN Transceiver |         | CAN Transceiver |         | CAN Transceiver |
 +----+--------+---+         +----+--------+---+         +----+--------+---+

      |        |                  |        |                  |        |
======+========+==================+========+==================+========+====== CAN_H
  [120 Ω]                                                                  [120 Ω]
======+========+==================+========+==================+========+====== CAN_L

Differential Bus States and Termination

Instead of referencing signals to a single ground rail, a CAN receiver reads the voltage difference between the two wires: $V_{\text{diff}} = V_{\text{CAN_H}} - V_{\text{CAN_L}}$.

  • Dominant State (Logic 0): The transceivers actively drive the lines apart. CAN_H spikes up to approximately $3.5\text{ V}$ and CAN_L drops down to approximately $1.5\text{ V}$. The differential voltage shifts to roughly $2.0\text{ V}$. Because it is actively driven, a dominant bit always overrides a recessive bit on the bus.
  • Recessive State (Logic 1 / Idle): The transceivers release both lines. Internal bias resistors pull both CAN_H and CAN_L to a neutral midpoint of approximately $2.5\text{ V}$, resulting in a differential voltage of $0\text{ V}$.
  • Termination Resistors: A standard high-speed CAN network requires exactly two 120 Ω termination resistors placed at the absolute physical ends of the main bus line. These resistors eliminate electrical signal reflections and pull the lines back to the neutral Recessive state when no node is driving a Dominant bit.

2. Packet Structure and Data Transfer

CAN communicates via structured data packets called message frames. Because it is a content-addressed network rather than a node-addressed network, frames do not contain a target destination address. Instead, they feature a unique Identifier (ID) that labels the type of data being broadcast.

Frame Conditions

  • SOF (Start of Frame): A single Dominant bit (0) that forces every node on the network to hard-synchronize their internal clocks to the edge transition.
  • Arbitration Field: Contains the message identifier. Standard CAN utilizes an 11-bit ID, while Extended CAN utilizes a 29-bit ID. The field concludes with an RTR (Remote Transmission Request) bit.
  • Control Field: Contains the IDE (Identifier Extension) bit and a 4-bit DLC (Data Length Code) which specifies the payload size.
  • Data Field: Contains the raw message payload, ranging from 0 up to 8 bytes maximum.
  • CRC Field: A 15-bit Cyclic Redundancy Check code used by receivers to detect bit corruption, followed by a Recessive CRC Delimiter bit.
  • ACK Field: Consists of an ACK Slot bit and an ACK Delimiter bit.
  • EOF (End of Frame): A sequence of 7 consecutive Recessive bits (1) marking the completion of the frame structure.

Packet Flow (Standard 11-Bit ID)

 [SOF] -> [11-Bit Identifier] -> [RTR] -> [IDE/r0] -> [4-Bit DLC] -> [0 to 8 Bytes Data] -> [15-Bit CRC] -> [CRCDelim] -> [ACK Slot] -> [ACKDelim] -> [EOF]
  1. Bit Stuffing: To maintain clock synchronization among independent nodes, the transmitter automatically inserts a dummy bit of opposite polarity after any sequence of 5 consecutive identical bits. The receiver automatically strips these stuffed bits out upon receipt.
  2. ACK Handshake: During the ACK Slot bit, the transmitting node releases the bus to a Recessive state. Every single receiver on the bus that successfully processes the CRC math pulls the bus down to a Dominant state simultaneously, providing hardware validation to the sender.

3. CAN Bus Oscilloscope Timing Diagram

The visual representation below shows how the electrical voltages on the CAN_H and CAN_L lines change relative to ground during bit state transitions, along with the resulting internal Logic output.

       RECESSIVE    DOMINANT     RECESSIVE    DOMINANT     RECESSIVE
Volt  (Logic 1)    (Logic 0)    (Logic 1)    (Logic 0)    (Logic 1)
3.5V  ............  ________  ............  ________  ............ CAN_H (~3.5V)
       :           /        \              /        \              
2.5V  ============================================================ Midpoint (~2.5V)
       :           \________/              \________/              
1.5V  ............  :        :............  :        :............ CAN_L (~1.5V)
       :            :        :             :        :             
       :            :        :             :        :             
Vdiff  ____          ________               ________               Differential 
(2.0V)     \________/        \_____________/        \_____________ Voltage (H-L)
       :            :        :             :        :             
       :            :        :             :        :             
Logic  __________            _______________            __________ Internal RX
Output           \__________/               \__________/           Logic State

Key Oscilloscope Identification Markers

  • The Midpoint Rest Baseline: When the network is idle, verify that both CAN_H and CAN_L track closely on top of each other at approximately $2.5\text{ V}$.
  • The Mirrored Splitting Action: When a bit switches state, the lines should mirror each other symmetrically. If CAN_H rises but CAN_L fails to drop, verify terminal impedance or check for a damaged transceiver.
  • Vdiff Extraction: Use the scope's math function ($A - B$) to subtract CAN_L from CAN_H. A healthy high-speed network will show a clear, clean clean square wave stepping between $0\text{ V}$ (Recessive) and $+2\text{ V}$ (Dominant).

4. Bus Arbitration, Error Handling, and Confinement

Non-Destructive Bitwise Arbitration

CAN operates on a multi-master architecture where any node can transmit whenever the bus is idle. If two nodes begin transmitting at the exact same instant, collisions are resolved natively through bitwise arbitration without corrupting data:

  • Nodes continuously monitor the bus while transmitting their Identifiers bit-by-bit.
  • If Node A transmits a Recessive bit (1), but Node B transmits a Dominant bit (0), the active physical state of the bus becomes Dominant.
  • Node A detects that the bus state does not match the bit it just sent. It instantly realizes a higher-priority message is executing, drops out of transmit mode, and turns into a passive receiver.
  • The Result: The node with the lowest numerical Identifier value has the highest priority and wins the bus cleanly without a single bit delay or collision retry penalty.

Error Tracking and Fault Confinement

Every CAN node maintains two internal hardware counters: the Transmit Error Counter (TEC) and the Receive Error Counter (REC). These counters increment when an error condition is encountered and decrement upon successful frame execution. Nodes dynamically shift through three health states based on these numbers:

   +-------------------+  TEC/REC > 127  +-------------------+  TEC > 255  +---------------+

   |    Error Active   | ---------------> |    Error Passive  | -----------> |    Bus Off    |
   | Fully participates|                  | Can only send     |              | Disconnects   |
   | in error signaling| <--------------- | Passive Error flags|              | from hardware |
   +-------------------+  TEC/REC <= 127 +-------------------+              +---------------+
  1. Error Active: The standard operating state. When an Error Active node detects an invalid frame (such as a bit stuffing violation or CRC error), it actively drives the bus down with 6 consecutive Dominant bits (an Error Flag). This deliberately destroys the frame structure, forcing all other nodes to reject the packet and prepare for retransmission.
  2. Error Passive: Triggered if either TEC or REC exceeds 127. The node can still transmit and receive data, but when it encounters an error, it is forbidden from broadcasting a dominant error flag. It may only send 6 consecutive Recessive bits, preventing a failing or noisy transceiver chip from destroying valid bus traffic.
  3. Bus Off: Triggered if the TEC exceeds 255. The node physically disconnects its transmitter drivers from the physical wires, completely silencing itself to protect the rest of the network from rogue frame generation.

5. ESP32 ↔ CAN bus via SN65HVD230

Design notes for adding a CAN 2.0B port to an ESP32 on a custom PCB.

---

1. How this differs from RS-485

Worth stating up front, because the instinct is to reuse the RS-485 mental model:

| | RS-485 (MAX3485) | CAN (SN65HVD230) |
|---|---|---|
| Direction control | External DE/RE pin, firmware-managed | **None.** Arbitration is in the protocol. |
| Fail-safe bias resistors | Required | **Never.** The transceiver internally biases the bus to VCC/2 when recessive. |
| Termination | 120 Ω at both ends | 120 Ω at both ends (same) |
| Protocol handling | Bare UART; you write the framing | **Hardware controller** (ESP32 TWAI) does framing, CRC, ACK, arbitration, retransmit |
| Idle bus state | Undefined without bias | Recessive, well-defined |

**Do not add bias resistors to a CAN bus.** They will break it.

---

2. The ESP32 side: TWAI

The ESP32 has an on-chip **TWAI** controller (Two-Wire Automotive Interface) — this
is a CAN 2.0B–compatible peripheral; TI's trademark situation is why it isn't called
"CAN" in Espressif's docs. It is *not* CAN FD.

The TWAI controller only provides **logic-level TX/RX**. It has no transceiver, which
is why the SN65HVD230 exists.

Header: `driver/twai.h` (ESP-IDF). Arduino: `ESP32-TWAI-CAN` or `driver/twai.h` directly.

---

3. SN65HVD230 pinout (SOIC-8)

| Pin | Name | Direction | Connects to |
|-----|------|-----------|-------------|
| 1 | D (TXD) | in | ESP32 TWAI TX |
| 2 | GND | — | ground plane |
| 3 | VCC | — | 3V3 |
| 4 | R (RXD) | out | ESP32 TWAI RX |
| 5 | Vref | out | VCC/2 reference. **Leave open** unless you need it. |
| 6 | CANL | bus | CAN low |
| 7 | CANH | bus | CAN high |
| 8 | Rs | in | Slope / mode control — see §5 |

Family variants

| Part | Rs pin behavior |
|---|---|
| **SN65HVD230** | Slope control + **standby** mode (Rs high) |
| SN65HVD231 | Slope control + **sleep** mode (separate EN pin) |
| SN65HVD232 | No Rs pin — always high-speed |

The SN65HVD230 is a **3.3 V** transceiver but is fully interoperable on a bus with
5 V transceivers (TJA1050, MCP2551, etc.) — CAN is differential, and the dominant/
recessive levels are compatible. This is a real advantage over RS-485.

---

4. Schematic

```
            3V3 ──────┬──────────┬────────────
                    │          │
                    ═══ 100nF    │
                    ═══ 10µF     │
                    │          │
                    GND    ┌────┴─────┐
ESP32                     │SN65HVD230│
┌────────────┐            │          │
│ GPIO5  TX  ├───────────►│1 D  CANH ├7──────┬──────┬─────── CANH
│  (TWAI TX) │            │          │       │      │
│            │            │          │     ┌─┴─┐  ┌─┴─┐
│ GPIO4  RX  │◄───────────┤4 R       │     │60 │  │TVS│
│  (TWAI RX) │            │          │     └─┬─┘  │   │
└────────────┘            │  5 Vref  │       │    │   │
                            │   (n.c.) │  4.7nF═══  │   │  ← split
                            │          │       │    │   │    termination
                            │  8 Rs    │      GND   │   │
                            │     │    │            │   │
                            │  2 GND   │     ┌─┴─┐  │   │
                            └────┬─────┘     │60 │  └─┬─┘
                                │           └─┬─┘    │
            GND ──────┬──────────┴─────────────┴──────┴─────── CANL
                    │                                6
                    ┌─┴─┐  Rs = 0 Ω for high speed
                    │Rs │  (or 10k for slope control)
                    └─┬─┘
                    GND
```

Note there is **no DE/RE**, **no bias network**, and TX/RX are independent — the
transceiver is always listening, even while transmitting. That self-monitoring is
what makes CAN arbitration work.

---

5. The Rs pin — the one decision to get right

| Rs connection | Mode | Use when |
|---|---|---|
| **Direct to GND** (or < 1 kΩ) | High speed, max slew | 500 kbps – 1 Mbps. **Default choice.** |
| 10 kΩ – 100 kΩ to GND | Slope control (slower edges) | Lower baud, unshielded cable, EMI-sensitive. ~10 kΩ ≈ 15 V/µs. |
| Pulled **high** (to VCC) | Standby / low power | Battery-powered nodes. Bus is still monitored; wake on activity. |

**Gotcha:** many cheap breakout modules populate a 10 kΩ Rs resistor by default. That
works fine at 125–250 kbps but will round the edges enough to cause problems at
1 Mbps. If you're running fast, short it or fit 0 Ω. If you want runtime standby
control, wire Rs to a GPIO instead of a fixed resistor.

**Never leave Rs floating.**

---

6. Bill of materials

| Ref | Value | Purpose | Notes |
|-----|-------|---------|-------|
| C1 | 100 nF X7R | VCC decoupling | Right at pin 3, short via to GND plane |
| C2 | 1–10 µF | Bulk | Within ~10 mm |
| R1 | 0 Ω (or 10 kΩ) | Rs slope control | See §5 |
| R2, R3 | 60 Ω, 1%, ≥0.25 W | **Split termination** | Only at the two physical ends of the bus |
| C3 | 4.7 nF | Split-termination filter | Between the 60 Ω midpoint and GND |
| D1 | PESD1CAN / NUP2105L | TVS across CANH/CANL | Strongly recommended for anything leaving the enclosure |
| L1 | Common-mode choke | EMI | Optional; automotive/industrial |

Split termination

Rather than a single 120 Ω across CANH/CANL, use **two 60 Ω in series with a 4.7 nF
cap from the midpoint to ground.** DC behavior is identical (120 Ω), but it gives the
common-mode voltage a low-impedance path to ground at high frequency, which
measurably reduces radiated emissions. It costs two extra parts and is close to free.

Use it if you can. Plain 120 Ω is acceptable for a bench setup.

---

7. Termination rules

- **Exactly two** 120 Ω terminations, at the **two physical ends of the cable**.
- Mid-bus nodes get **none**. Put yours on a jumper/DIP so the board can be either.
- Two terminators in parallel = 60 Ω, which is what the transceiver expects to drive.
- **Three or more terminators is the single most common CAN bus failure.** The bus
loads down, dominant bits don't reach threshold, and you get sporadic errors that
look like noise. If a bus is misbehaving, measure CANH–CANL resistance with
everything powered off: it should read **~60 Ω**. 120 Ω = missing a terminator.
40 Ω = one too many.

---

8. Firmware notes (ESP-IDF)

```c
#include "driver/twai.h"

twai_general_config_t g = TWAI_GENERAL_CONFIG_DEFAULT(
    GPIO_NUM_5,   // TX
    GPIO_NUM_4,   // RX
    TWAI_MODE_NORMAL);
twai_timing_config_t t = TWAI_TIMING_CONFIG_500KBITS();
twai_filter_config_t f = TWAI_FILTER_CONFIG_ACCEPT_ALL();

twai_driver_install(&g, &t, &f);
twai_start();
```

Pin selection

Any GPIO via the matrix. Avoid strapping pins (0, 2, 5, 12, 15) — though GPIO5 is
commonly used for TX anyway and is usually fine. RX may use an input-only pin
(34–39) if you're short on GPIO.

Bus-off recovery — do not skip

A node that racks up enough TX errors enters **bus-off** and stops communicating
permanently until you recover it. This is normal CAN behavior, not a fault, and your
firmware must handle it:

```c
twai_status_info_t s;
twai_get_status_info(&s);
if (s.state == TWAI_STATE_BUS_OFF) {
    twai_initiate_recovery();   // then wait for TWAI_STATE_STOPPED, twai_start()
}
```

Enable alerts (`TWAI_ALERT_BUS_OFF`, `TWAI_ALERT_ERR_PASS`) rather than polling.

ESP32 TWAI errata

The original ESP32 silicon has several documented TWAI errata (bus-off recovery,
lost TX interrupts, corrupt RX FIFO, invalid RX frames). ESP-IDF ships software
workarounds under `CONFIG_TWAI_ERRATA_FIX_*`, **enabled by default** on ESP32 —
don't turn them off. Later chips (S3, C3, C6) don't need them.

Testing with one node

A single CAN node cannot transmit successfully — nothing will ACK it, so it
retransmits forever and eventually goes error-passive. Use `TWAI_MODE_NO_ACK` for
solo bench testing, or put a second node on the bus.

---

9. Layout rules

- CANH/CANL routed as a tight **differential pair**, 120 Ω target impedance.
- **No stubs.** The tap from trunk to transceiver must be short (< 30 cm on cable,
as short as possible on PCB).
- **Do not split the ground plane** under the pair.
- Transceiver close to the connector; TVS placed so surge current reaches connector
ground before it reaches the IC.
- Bus topology must be a **linear daisy-chain**, not a star. Star topologies produce
reflections that CAN's bit-timing cannot tolerate at speed.

---

10. Grounding

CAN, like RS-485, is differential but **not isolated**. Nodes must share a ground
reference. Run a ground wire alongside the pair.

For isolation (long runs, separate power domains, automotive):
- **ISO1050** (TI) — isolated CAN transceiver, drop-in-ish replacement.
- Or an opto/digital isolator between the ESP32 and the SN65HVD230 — but this adds
propagation delay, which **eats into your bit timing** and reduces max bus length.
Prefer an integrated isolated transceiver.

---

11. Module gotchas (Waveshare-style SN65HVD230 boards)

If you're evaluating with a breakout before committing to your PCB:

- **The 120 Ω terminator is usually soldered on permanently.** Two of these boards on
a desk = correct. Three = broken bus. Desolder it for mid-bus nodes.
- **Rs is often 10 kΩ.** Fine at 250 kbps, marginal at 1 Mbps.
- **No TVS.** Fine on a bench, not fine in a vehicle or on a machine.
- Some clones populate a plain 120 Ω rather than split termination.

---

12. Bus length vs. bitrate (rule of thumb)

| Bitrate | Max bus length |
|---|---|
| 1 Mbps | ~40 m |
| 500 kbps | ~100 m |
| 250 kbps | ~250 m |
| 125 kbps | ~500 m |
| 50 kbps | ~1000 m |

Propagation delay must fit inside the bit time for arbitration to work — this is a
hard physical limit, not a signal-quality guideline.

---

13. References

- [SN65HVD230 — product page & datasheet (TI)](https://www.ti.com/product/SN65HVD230)
- [ESP-IDF TWAI driver documentation](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/twai.html)
- [ESP32 errata sheet](https://www.espressif.com/sites/default/files/documentation/eco_and_workarounds_for_bugs_in_esp32_en.pdf) — TWAI section
- TI SLLA270 — *Controller Area Network Physical Layer Requirements* (termination, stubs, topology)
- TI SLOA101 — *Introduction to the Controller Area Network (CAN)*
- ISO 11898-2 — high-speed CAN physical layer (the actual standard)

6. References & Standards Documents

  • ISO 11898-1:2015 Road vehicles — Controller area network (CAN) — Part 1: Data link layer and physical signaling — The absolute international standard defining the official data link layer architecture for classical CAN and CAN FD.
  • ISO 11898-2:2016 Road vehicles — Controller area network (CAN) — Part 2: High-speed medium access unit — The baseline document specifying the official electrical transceivers, differential drive parameters, and termination criteria.
  • Texas Instruments: Introduction to the Controller Area Network (SLOA101) — Highly trusted semiconductor reference handbook summarizing bit stuffing math, physical bus wiring design guidelines, and transceiver layout behaviors.
  • Vector Informatik Knowledge Platform: CAN / CAN FD Protocol Fundamentals — Highly authoritative industrial automotive knowledge hub tracking sample setups, dynamic error flags, and node containment limits.
Contact

Have an Idea?
Let's Build It.

Whether you're a startup with a hardware concept, an established company needing deep design help, or an enthusiast with a wild project — we want to hear about it.

LocationBoulder, Colorado