HomeAbout UsContact Us

CAN Bus Errors: Bit, Stuff, CRC, ACK, Bus Off Recovery

By Jithin Tom
Published in Embedded Concepts
November 18, 2026
9 min read
CAN Bus Errors: Bit, Stuff, CRC, ACK, Bus Off Recovery

Table Of Contents

01
Problem: Node Disappears from Bus After Brief Operation
02
CAN Error Types: Reading the Last Error Code (LEC)
03
Diagnostic Procedure: From Symptoms to Root Cause
04
Automatic vs. Manual Bus-Off Recovery
05
Error Warning Interrupt: Catch Problems Before Bus-Off
06
Single-Node Development: Loopback Mode
07
Zephyr CAN Subsystem: Error Handling
08
Embedded Linux: SocketCAN Error Handling and Bus-Off Recovery
09
Common Scenarios and Fixes
10
Practical Debugging Checklist
11
Summary
12
Related Reading
13
References
14
Frequently Asked Questions

A CAN controller stops transmitting, and the STM32 bxCAN Error Status Register (CAN_ESR) indicates BOFF. This is a CAN fault-confinement response, not necessarily a software crash. Repeated transmission failures can eventually push the Transmit Error Counter (TEC) past the bus-off threshold, at which point the controller stops participating on the bus. The exact counter progression depends on the error type and the CAN error-handling exceptions.

For example, an isolated CAN node that cannot receive an ACK typically becomes error-passive, but an ACK-only failure does not inevitably send it bus-off: the protocol suspends TEC increases for an error-passive transmitter that observes no dominant bits during its passive error flag. By contrast, actual bus faults, incompatible bit timing, or bit monitoring failures may cause repeated errors leading to bus-off.

This guide covers classical CAN fault confinement and practical diagnostics across the physical layer, STM32 bxCAN (not the separate FDCAN peripheral), Zephyr RTOS, and Linux SocketCAN. It distinguishes protocol requirements from controller-specific recovery and supplies patterns for collecting evidence without performing blocking work inside interrupt handlers.

Problem: Node Disappears from Bus After Brief Operation

A newly assembled CAN board transmits but cannot exchange frames with other nodes. On a scope, the transceiver may drive CANH and CANL, yet no other controller acknowledges the frame. Repeated retries and error frames consume bandwidth, and the CAN peripheral reports an increasing TEC and eventually error-passive operation.

If the sole problem is that no second node drives the ACK slot dominant, a standards-conforming transmitter generally stops increasing TEC for ACK errors after reaching error-passive, provided it sees no dominant bits during its passive error flag. Do not diagnose bus-off from missing ACKs alone. If BOFF actually becomes set, investigate additional bit errors, wiring faults, incompatible timing, or another error condition.

Root Cause: The Asymmetric Error Counter Design

Classical CAN fault confinement tracks two controller-local error counters:

  • TEC (Transmit Error Counter): Typically increases by 8 for transmission-related errors and decreases by 1 after a successful transmission, subject to specific protocol exceptions.
  • REC (Receive Error Counter): Typically increases by 1 for detected reception errors and decreases on successful reception; the standard specifies additional rules for some error-flag conditions and for REC values above 127. It is not simply a counter that permanently caps at 127.

The larger transmitter penalty helps isolate faulty nodes. However, these values are not universal on every error event. The ACK-error exception is especially important: a transmitter that is already error-passive does not increment TEC for an ACK error when it observes no dominant bit while transmitting its passive error flag.

+--------------------------------------------------------------------------+
| CAN ERROR STATE MACHINE (Classical CAN) |
| |
| ERROR ACTIVE: TEC < 128 AND REC < 128 |
| | Either counter reaches 128 |
| v |
| ERROR PASSIVE: TEC >= 128 OR REC >= 128; TEC <= 255 |
| | Both counters drop below 128 -> ERROR ACTIVE |
| | TEC exceeds 255 due to applicable transmission errors |
| v |
| BUS OFF: controller does not transmit, ACK, or send error flags |
| | Recover: detect 128 instances of 11 recessive bits |
| | (automatic or initiated by software, by controller policy) |
| v |
| ERROR ACTIVE after completed bus-off recovery |
| |
| EXCEPTION: ACK errors alone may stop raising TEC at 128 |
| for an isolated error-passive transmitter. |
+--------------------------------------------------------------------------+

The three operating states are:

StateConditionController behaviour
Error-activeTEC < 128 and REC < 128Normally sends an active (dominant) error flag when it detects a protocol error.
Error-passiveTEC >= 128 or REC >= 128, while not bus-offSends a passive (recessive) error flag; additional 8-bit Suspend Transmission applies when this node transmits following intermission.
Bus-offTEC crosses the bus-off threshold (> 255)Stops communicating on the bus, including sending ACKs. Re-entry requires the specified recovery sequence and controller/driver policy.

[!NOTE] The TEC is conceptually driven beyond 255 on entry to bus-off, but on STM32 bxCAN the exposed TEC register field is only 8 bits. Do not expect to read 256 from CAN_ESR. Inspect BOFF for the bus-off state. A high REC can make a node error-passive but does not by itself cause bus-off.

CAN Error Types: Reading the Last Error Code (LEC)

Classical CAN detects bit, stuff, form, ACK and CRC errors. STM32 bxCAN records the most recent classified protocol error in CAN_ESR.LEC[2:0] (bits 6:4). It is a last-error indicator, not a cumulative error histogram or proof of a single physical cause. Successful transfers and software writes can change its value.

+--------------------------------------------------------------------------+
| STM32 bxCAN CAN_ESR BIT FIELDS |
| |
| 31 ........ 24 | 23 ........ 16 | 15 ...... 7 | 6 .. 4 | 3 | 2 1 0 |
| REC[7:0] | TEC[7:0] | Reserved | LEC | R | B P W |
| |
| B = BOFF (bit 2), P = EPVF (bit 1), W = EWGF (bit 0) |
| LEC = Last Error Code; R = reserved (bit 3) |
+--------------------------------------------------------------------------+

STM32 bxCAN LEC Register Decoding

For STM32 bxCAN, the LEC field is defined as follows (refer to your exact STM32 reference manual):

LECBitsMeaningHow to interpret it
0000No errorNo detected error since the most recent reset/clear condition.
1001Stuff errorBit-stuffing rule was violated in a field where it applies.
2010Form errorA fixed-format field such as a delimiter or EOF had an invalid value.
3011ACK errorTransmitter did not see a dominant ACK slot. This can mean no suitable active peer, not necessarily a defective bus.
4100Bit recessive errorRecessive bit sent but dominant bit observed, outside specified arbitration/ACK exceptions.
5101Bit dominant errorDominant bit sent but recessive bit observed.
6110CRC errorReceived CRC sequence differs from locally calculated CRC, not from the CRC delimiter.
7111Set by softwareSoftware sentinel for recognizing a subsequent new hardware error.

A compact diagnostic using a single ESR snapshot avoids mixing counters from different moments:

#include "stm32f4xx_hal.h"
#include <stdint.h>
#include <stdio.h>
void can_inspect_status(const CAN_HandleTypeDef *hcan)
{
const uint32_t esr = hcan->Instance->ESR;
const uint32_t tec = (esr >> 16) & 0xFFU;
const uint32_t rec = (esr >> 24) & 0xFFU;
const uint32_t lec = (esr >> 4) & 0x07U;
static const char *const lec_names[8] = {
"No Error", "Stuff Error", "Form Error", "ACK Error",
"Bit Recessive Error", "Bit Dominant Error",
"CRC Error", "Set by Software"
};
printf("ESR=%08lX BOFF=%u EPVF=%u EWGF=%u "
"TEC=%lu REC=%lu LEC=%lu (%s)\n",
(unsigned long)esr, (unsigned)((esr >> 2) & 1U),
(unsigned)((esr >> 1) & 1U), (unsigned)(esr & 1U),
(unsigned long)tec, (unsigned long)rec,
(unsigned long)lec, lec_names[lec]);
}
/* Optional: set LEC to 111 to detect the next hardware error.
* On bxCAN, LEC is the writable portion of ESR. Do not use
* a read-modify-write of live status bits just to set LEC. */
static inline void can_mark_lec_unknown(CAN_HandleTypeDef *hcan)
{
hcan->Instance->ESR = (7U << 4);
}

[!IMPORTANT] A single node and an oscilloscope are not two CAN nodes. With no other active controller to ACK a valid frame, a standalone normal-mode transmitter detects ACK errors and retries. After approximately 16 failures it can reach error-passive (TEC = 128); under the CAN ACK-error exception it may keep retrying without ever entering bus-off. A receiving node generally ACKs a correctly received frame even if its acceptance filter rejects delivery to application code. Silent/listen-only controllers do not ACK.

Diagnostic Procedure: From Symptoms to Root Cause

Correlate TEC/REC progression, the current error state, the latest LEC, and a differential-bus measurement. None of these signals alone uniquely identifies the faulty component.

+--------------------------------------------------------------------------+
| DIAGNOSTIC DECISION FLOW |
| |
| Read BOFF / EPVF / EWGF, TEC, REC and LEC |
| | |
| +-- TEC rising: investigate local transmission / ACK / bit errors |
| +-- REC rising: investigate receive sampling / signal integrity |
| +-- Both rising: investigate timing, interference and topology |
| | |
| +-- LEC 3: no ACK; verify an active receiving peer |
| +-- LEC 6: CRC mismatch; probe physical signals and sample timing |
| +-- LEC 1: stuffing violation; check clocks and noise |
| +-- LEC 4/5: bit mismatch; inspect TXD/RXD and bus wiring |
| |
| Finally verify wiring, bitrate/sample point, transceiver and recovery. |
+--------------------------------------------------------------------------+

Step 1: Check Error Counters Directly

HAL_CAN_GetError() returns a HAL software error-bit mask, not the current numeric TEC and REC. Read both counters and state from the same CAN_ESR sample:

const uint32_t esr = hcan->Instance->ESR;
const uint8_t tec = (uint8_t)((esr >> 16) & 0xFFU);
const uint8_t rec = (uint8_t)((esr >> 24) & 0xFFU);
const bool bus_off = (esr & CAN_ESR_BOFF) != 0U;
const uint32_t hal_errors = HAL_CAN_GetError(hcan);
if (bus_off) {
/* Controller is in bus-off; record evidence before recovery. */
}
(void)tec;
(void)rec;
(void)hal_errors;

Include <stdbool.h> for bool in C translation units. Capture periodic snapshots or log changes; register reads are only a point-in-time view, and TEC/REC do not identify the cause by themselves.

Step 2: Build an Error Histogram

For intermittent faults, accumulate observed error classes, rather than treating the hardware LEC field as a total count. The following sample uses the error flags provided by the STM32F4 HAL callback. The flags can be coalesced, so these counters represent callback observations, not an exact count of CAN protocol error frames.

#include <stdint.h>
typedef struct {
uint32_t stuff, form, ack, bit_recessive, bit_dominant, crc, bus_off;
} can_error_histogram_t;
static volatile can_error_histogram_t g_can_metrics;
/* Called by HAL_CAN_IRQHandler() in interrupt context. */
void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan)
{
const uint32_t err = HAL_CAN_GetError(hcan);
if (err & HAL_CAN_ERROR_STF) { g_can_metrics.stuff++; }
if (err & HAL_CAN_ERROR_FOR) { g_can_metrics.form++; }
if (err & HAL_CAN_ERROR_ACK) { g_can_metrics.ack++; }
if (err & HAL_CAN_ERROR_BR) { g_can_metrics.bit_recessive++; }
if (err & HAL_CAN_ERROR_BD) { g_can_metrics.bit_dominant++; }
if (err & HAL_CAN_ERROR_CRC) { g_can_metrics.crc++; }
if (err & HAL_CAN_ERROR_BOF) { g_can_metrics.bus_off++; }
/* Signal a worker when recovery or logging is needed. Do not
* block, delay or printf inside this callback. */
}

Read/reset the counters from thread context using an appropriate critical section or atomic snapshot, since multi-field reads may race with ISR updates. Some HAL versions reset LEC during IRQ servicing; if exact LEC events are required, capture the raw status before the HAL clears it, or use a dedicated peripheral-level trace.

Step 3: Physical Layer Verification

When ACK errors are excluded as the only fault, inspect topology, timing and the transceiver. These checks assume high-speed ISO 11898-2 CAN; voltage levels, termination and tolerances depend on the transceiver and bus design.

+--------------------------------------------------------------------------+
| CAN PHYSICAL LAYER CHECKLIST |
| |
| [ ] Two end-of-line terminators on a conventional linear bus |
| [ ] ~60 ohms CANH-to-CANL (unpowered, two 120-ohm resistors) |
| [ ] Recessive differential voltage near 0 V (design-dependent) |
| [ ] Dominant differential voltage typically about 2 V |
| [ ] Bitrate, sample point and oscillator tolerance compatible |
| [ ] Short stubs; limit length using rise time and bit rate |
| [ ] Transceiver powered, enabled and not in silent/standby |
| [ ] Shared reference/common-mode voltage within device limits |
| [ ] No excessive ringing, ground shifts or intermittent wiring |
| [ ] Consider EMC measures based on measured emissions/immunity |
+--------------------------------------------------------------------------+
  1. Termination (power off): Two 120-ohm terminators across a conventional linear CANH/CANL bus measure roughly 60 ohms in parallel; 120 ohms suggests one termination. Split terminations can still yield approximately 60 ohms DC. Other topologies and attached circuitry can change this reading.
  2. Differential signalling: With typical high-speed transceivers, recessive CANH and CANL are close together in voltage, often around 2.5 V each; a dominant bit often produces about 2 V differential. Check the actual datasheet rather than treating those nominal voltages as universal pass/fail thresholds.
  3. Topology and EMC: There is no universal 0.1-ohm ground-resistance criterion, compulsory common-mode choke, or single safe stub length for every installation. Assess common-mode range, propagation delay, cable and transceiver characteristics, and measurement results.

Automatic vs. Manual Bus-Off Recovery

When the transmitter’s error counter crosses the bus-off threshold, classical CAN requires the controller to observe 128 occurrences of 11 consecutive recessive bits before resuming normal communication. The observation can occur while the bus is idle or during eligible recessive sequences; it is not a guaranteed fixed delay once bus traffic is considered.

128 x 11 = 1408 nominal bit times (minimum idle-bus observation)
Ideal lower bound on a sufficiently idle bus:
1 Mbit/s : 1.408 ms
500 kbit/s : 2.816 ms
250 kbit/s : 5.632 ms
125 kbit/s : 11.264 ms
Actual recovery can take longer due to bus traffic, faults and
controller/driver policy. These figures are not guaranteed deadlines.

Whether recovery starts automatically or needs a software request is controller-specific. Do not equate a software delay with completion of the protocol-level recovery sequence.

Automatic Recovery (ABOM = 1)

On STM32 bxCAN, CAN_MCR.ABOM enables automatic bus-off management. After bus-off, hardware waits for the required recessive-bit observation before leaving bus-off. It does not require application code to call HAL_CAN_Stop()/HAL_CAN_Start() solely to perform the recovery.

/* Called after the rest of hcan->Init (timing, mode, etc.)
* has been configured for the actual board. */
HAL_StatusTypeDef can_init_with_auto_busoff(CAN_HandleTypeDef *hcan)
{
hcan->Init.AutoBusOff = ENABLE;
return HAL_CAN_Init(hcan);
}
/* Configure the CAN filters, then call HAL_CAN_Start() normally. */

When to use: Systems that tolerate automatic re-entry and have suitable monitoring/back-off at the application level. Automatic hardware recovery does not fix a wiring, termination, transceiver or timing fault, and repeated bus-off/recovery cycles need explicit handling.

Manual Recovery (ABOM = 0)

With ABOM disabled, STM32 bxCAN normally requires software to request re-entry (for example, through initialization mode), followed by the controller’s bus-off recovery observation. Manual recovery is a system-design choice, not a blanket ISO 26262 or IEC 61508 rule.

This sample assumes hcan was already fully initialized, filters configured, and the controller started. Call it from a task/main loop, not from HAL_CAN_ErrorCallback() or another ISR, because the HAL control routines and delay can block.

/* Set AutoBusOff = DISABLE before HAL_CAN_Init() for manual policy. */
HAL_StatusTypeDef can_execute_manual_recovery(CAN_HandleTypeDef *hcan)
{
const uint32_t esr = hcan->Instance->ESR;
if ((esr & CAN_ESR_BOFF) == 0U) {
return HAL_OK;
}
/* Preserve ESR, TEC/REC and HAL errors for later diagnostics.
* The worker may log them here, outside interrupt context. */
const uint8_t tec = (uint8_t)((esr >> 16) & 0xFFU);
const uint8_t rec = (uint8_t)((esr >> 24) & 0xFFU);
const uint8_t lec = (uint8_t)((esr >> 4) & 7U);
(void)tec; (void)rec; (void)lec;
/* Optional policy delay/back-off. Check fault condition before
* attempting restart; HAL_Delay requires a functioning time base. */
HAL_Delay(100U);
if (HAL_CAN_Stop(hcan) != HAL_OK) {
return HAL_ERROR;
}
if (HAL_CAN_Start(hcan) != HAL_OK) {
return HAL_ERROR;
}
/* CAN reception/error notifications may need re-enabling,
* depending on driver state and application initialization. */
return HAL_CAN_ActivateNotification(hcan,
CAN_IT_RX_FIFO0_MSG_PENDING | CAN_IT_ERROR_WARNING |
CAN_IT_ERROR_PASSIVE | CAN_IT_BUSOFF | CAN_IT_LAST_ERROR_CODE);
}

HAL_CAN_ResetError() clears HAL-maintained error flags; it does not substitute for recovering the hardware bus-off state. Recovery success must be confirmed by the resulting controller state, not merely by the return value of HAL_CAN_Start().

+--------------------------------------------------------------------------+
| BUS-OFF RECOVERY PATHS (500 kbit/s nominal) |
| |
| AUTOMATIC (bxCAN ABOM=1) |
| BUS OFF -> 128 x 11 recessive bits -> ERROR ACTIVE |
| 2.816 ms minimum idle-bus time |
| |
| MANUAL (bxCAN ABOM=0) |
| BUS OFF -> application diagnosis/back-off -> request re-entry |
| -> 128 x 11 recessive bits -> ERROR ACTIVE |
| |
| Observe controller state; neither path guarantees wall time. |
+--------------------------------------------------------------------------+

Error Warning Interrupt: Catch Problems Before Bus-Off

STM32 bxCAN exposes early fault-confinement status flags:

  • EWGF: set when TEC >= 96 or REC >= 96.
  • EPVF: set when TEC >= 128 or REC >= 128.
  • BOFF: set after the controller reaches the bus-off condition (TEC threshold exceeded).

Enable the interrupt sources in your normal initialization path. The CAN SCE IRQ must call HAL_CAN_IRQHandler() for the HAL callback to run.

HAL_StatusTypeDef can_enable_diagnostics(CAN_HandleTypeDef *hcan)
{
return HAL_CAN_ActivateNotification(hcan,
CAN_IT_ERROR_WARNING | CAN_IT_ERROR_PASSIVE |
CAN_IT_BUSOFF | CAN_IT_LAST_ERROR_CODE);
}
/* In the HAL_CAN_ErrorCallback() shown earlier, store status flags
* and set a worker signal, for example:
* if (HAL_CAN_GetError(hcan) & HAL_CAN_ERROR_BOF) {
* g_can_recovery_requested = 1U;
* }
* The worker handles logging, diagnosis and any restart later. */

Do not call HAL_Delay(), perform UART printf() that can block, or run HAL_CAN_Stop()/HAL_CAN_Start() directly inside the error ISR. On Cortex-M, share a one-bit recovery request with the main loop or RTOS worker using an appropriate atomic/interrupt-safe mechanism. Avoid clearing HAL error state until the diagnostics have been copied, and remember that some errors may be merged into one interrupt.

Single-Node Development: Loopback Mode

An isolated controller in normal mode has no other active node to acknowledge its messages. This causes repeated ACK errors, but, due to the error-passive ACK exception, does not guarantee bus-off.

For single-board protocol testing, configure internal loopback before initializing and starting bxCAN:

hcan.Init.Mode = CAN_MODE_LOOPBACK; /* Requires normal HAL init sequence. */

Loopback checks the CAN controller and software framing path without depending on an external ACK. It does not validate the transceiver, bus termination, cable propagation, electromagnetic compatibility or real peer acknowledgements. For full physical testing, connect another powered, normal-mode controller at the same nominal bitrate; a listen-only/silent analyzer generally will not ACK transmitted frames.

Zephyr CAN Subsystem: Error Handling

Zephyr’s <zephyr/drivers/can.h> provides controller-state notification and bus-off recovery APIs. Driver support is hardware-dependent, and individual APIs/Kconfig names can evolve across Zephyr versions.

Typical enum can_state values include CAN_STATE_ERROR_ACTIVE, CAN_STATE_ERROR_PASSIVE, CAN_STATE_BUS_OFF, and CAN_STATE_STOPPED. The controller’s error counters may be obtained from the state-change callback or can_get_state().

Implementing Zephyr State Change Callbacks

In current Zephyr releases, use can_init_state_change_callback() and can_add_state_change_callback(). The older can_set_state_change_callback() remains documented but is deprecated. A state-change callback runs in interrupt context, so schedule recovery work rather than blocking there.

#include <errno.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/can.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(can_diag, LOG_LEVEL_INF);
/* Replace can1 with the devicetree node used by your board. */
static const struct device *const can_dev = DEVICE_DT_GET(DT_NODELABEL(can1));
static struct can_state_change_callback can_state_cb;
static struct k_work can_recovery_work;
static void can_recovery_work_handler(struct k_work *work)
{
ARG_UNUSED(work);
int ret = can_recover(can_dev, K_MSEC(100));
if (ret != 0) {
LOG_ERR("CAN recovery failed: %d", ret);
}
}
static void can_state_change_handler(
const struct device *dev,
struct can_state_change_callback *callback,
enum can_state state, struct can_bus_err_cnt err_cnt)
{
ARG_UNUSED(dev);
ARG_UNUSED(callback);
ARG_UNUSED(err_cnt);
if (state == CAN_STATE_BUS_OFF) {
(void)k_work_submit(&can_recovery_work);
}
}
int can_init_monitoring(void)
{
int ret;
if (!device_is_ready(can_dev)) {
return -ENODEV;
}
/* Controller must be stopped before changing its mode.
* Check driver support for CAN_MODE_MANUAL_RECOVERY. */
ret = can_set_mode(can_dev, CAN_MODE_MANUAL_RECOVERY);
if (ret != 0) {
return ret;
}
k_work_init(&can_recovery_work, can_recovery_work_handler);
can_init_state_change_callback(&can_state_cb,
can_state_change_handler);
ret = can_add_state_change_callback(can_dev, &can_state_cb);
if (ret != 0) {
return ret;
}
/* Call can_start(can_dev) separately after remaining setup. */
return 0;
}

For Zephyr builds that support the API, enable manual recovery in prj.conf:

CONFIG_CAN=y
CONFIG_CAN_MANUAL_RECOVERY_MODE=y

can_recover() returns an error if the driver lacks support, the controller is stopped, or a timeout occurs. A 100-ms wait also occupies the workqueue thread; production systems should prefer a dedicated recovery thread/workqueue or appropriately bound recovery task when other system work is latency-sensitive. Zephyr versions that lack the newer callback registration should use the state-change API available in their pinned release.

Embedded Linux: SocketCAN Error Handling and Bus-Off Recovery

On embedded Linux, SocketCAN models CAN controllers as network interfaces. Drivers report controller state through netlink (ip -details link), and optionally emit CAN error frames to interested RAW sockets. Linux automatic restart uses a driver-assisted timer and is separate from STM32 bxCAN’s ABOM register.

Configuring Bus-Off Auto-Restart via iproute2

On a controller and driver that support it, configure a restart delay (milliseconds) using iproute2:

# Run as root, with bitrate appropriate for all nodes on the bus.
ip link set can0 down
ip link set can0 type can bitrate 500000 restart-ms 100
ip link set can0 up

The restart-ms setting schedules a controller restart after the specified delay if bus-off occurs. It is not itself the CAN protocol’s 128-by-11-bit recovery observation interval. A value of zero disables the kernel’s timed auto-restart:

ip link set can0 type can restart-ms 0
# After a confirmed bus-off, request a manual restart:
ip link set can0 type can restart

Controller state, capabilities and restart behavior vary by hardware driver; monitor whether the interface actually returns to ERROR-ACTIVE and whether the original bus fault persists.

Inspecting CAN Error Statistics

Use:

ip -details -statistics link show can0

Typical output (format and available counters vary by driver and iproute2 version):

3: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 state UP
can state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 100
bitrate 500000 sample-point 0.875
re-started bus-errors arbit-lost error-warn error-pass bus-off
0 0 0 0 0 0
RX: bytes packets errors dropped overrun
12840 1605 0 0 0
TX: bytes packets errors dropped carrier
12840 1605 0 0 0

Some CAN drivers cannot report bus-error counters or individual error classes. A zero or missing statistic is not proof that the physical bus is error-free.

Capturing SocketCAN Error Frames in User Space

Set CAN_RAW_ERR_FILTER to request CAN error frames. Check each socket operation, avoid copying an arbitrary interface name with strcpy(), and use the actual Linux error-class constants (CAN_ERR_CRTL, not CAN_ERR_CRIT).

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#include <linux/can/error.h>
int open_monitored_can_socket(const char *ifname)
{
int fd = -1;
struct ifreq ifr = {0};
struct sockaddr_can addr = {0};
can_err_mask_t mask = CAN_ERR_ACK | CAN_ERR_CRTL | CAN_ERR_PROT |
CAN_ERR_BUSOFF | CAN_ERR_RESTARTED;
if (ifname == NULL || strlen(ifname) >= IFNAMSIZ) {
errno = EINVAL;
return -1;
}
fd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (fd < 0) {
return -1;
}
memcpy(ifr.ifr_name, ifname, strlen(ifname) + 1U);
if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0 ||
setsockopt(fd, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
&mask, sizeof(mask)) < 0) {
int saved_errno = errno;
close(fd);
errno = saved_errno;
return -1;
}
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
int saved_errno = errno;
close(fd);
errno = saved_errno;
return -1;
}
return fd;
}
void monitor_bus_health(int fd)
{
struct can_frame frame;
ssize_t n;
while ((n = read(fd, &frame, sizeof(frame))) > 0) {
if (n != (ssize_t)sizeof(frame) ||
(frame.can_id & CAN_ERR_FLAG) == 0U) {
continue;
}
if (frame.can_id & CAN_ERR_BUSOFF) {
puts("CAN controller BUS-OFF");
}
if (frame.can_id & CAN_ERR_ACK) {
puts("CAN ACK error");
}
if (frame.can_id & CAN_ERR_PROT) {
printf("Protocol error: type=0x%02X location=0x%02X\n",
frame.data[2], frame.data[3]);
}
if (frame.can_id & CAN_ERR_CRTL) {
printf("Controller status flags: 0x%02X\n", frame.data[1]);
}
}
if (n < 0) {
perror("CAN read");
}
}

Not every interface emits every error type; errors can be aggregated by the driver. You can inspect error frames from a shell using can-utils:

# Error mask syntax is a can-utils candump filter, not a shell comment.
candump 'can0,#FFFFFFFF'

Common Scenarios and Fixes

SymptomTypical LECCounter behaviorLikely investigationsAppropriate next step
Lone node repeatedly retries and sends no completed frames3 (ACK)TEC may rise to 128 and then stop increasing for ACK-only retriesMissing active peer, silent mode, transceiver standby, bitrate mismatchConnect another normal-mode receiver and inspect ACK slot; do not assume bus-off
Intermittent CRC errors6 (CRC)REC often rises; counter changes follow CAN rulesSignal quality, bit timing, noise, termination, transceiverScope differential waveform and verify sampling point
Stuff errors at higher bitrates1 (Stuff)REC/TEC can rise based on the detecting nodeOscillator tolerance, wrong bit timing, wiring/EMIVerify clocks and bus topology
Dominant bit transmitted but recessive observed5 (Bit dominant)Usually a TX errorTransceiver not driving, wiring/open circuit, standby or faultProbe controller TXD and transceiver outputs
Recessive bit transmitted but dominant observed outside arbitration exceptions4 (Bit recessive)May be a TX errorStuck-dominant bus, wiring and timing faultsInspect bus levels, arbitration and error frames
Form errors in fixed-value fields2 (Form)Often RX errorNoise, incorrect sampling, faulty participantsProbe delimiters and end-of-frame timing

An observed LEC identifies how the CAN controller detected a violation; it rarely proves which physical component caused it. CAN arbitration is intentionally allowed to create recessive-versus-dominant observations without counting them as bit errors.

Practical Debugging Checklist

  1. Capture state first: Record BOFF, EPVF, EWGF, TEC, REC, LEC, and the HAL/OS error flags before initiating recovery.
  2. Distinguish no-ACK from bus-off: On a lone node, expect error-passive ACK retries; do not assume that 32 missing ACKs force bus-off.
  3. Verify conventional termination: With power removed, check for roughly 60 ohms only when the wiring uses two nominal 120-ohm end terminators.
  4. Scope CANH and CANL together: Inspect differential levels, ringing, edge timing, common-mode range and ACK-slot behavior using the actual transceiver specifications.
  5. Validate timing: Ensure all nodes share the nominal bitrate and compatible sample point, oscillator accuracy, propagation delay and synchronization jump width.
  6. Log early warning and passive transitions: Enable state/error interrupts, but defer formatting, printing and recovery to a worker/task.
  7. Set recovery policy to system needs: Use bxCAN ABOM or controlled initialization-mode re-entry; in Zephyr use the supported driver mode and can_recover(); on Linux use SocketCAN restart policy.

Summary

CAN fault confinement prevents a failing node from repeatedly corrupting bus traffic, but accurate diagnosis requires respecting the protocol’s exceptions and the specific controller implementation. In particular, ACK errors alone on an isolated, error-passive transmitter do not necessarily cause bus-off.

  1. Error counters: Transmission errors often add 8 to TEC and successful transmissions subtract 1; reception errors generally follow different rules and there are important special cases.
  2. State transitions: Error-passive begins at TEC >= 128 or REC >= 128; bus-off requires TEC to cross 255. Inspect the hardware BOFF status, not a presumed visible TEC value of 256.
  3. STM32 bxCAN diagnostics: LEC 3 = ACK, 6 = CRC, 1 = stuff, 4 = bit recessive and 5 = bit dominant. A single LEC sample is not an exhaustive event history.
  4. Recovery: The protocol calls for observing 128 sequences of 11 consecutive recessive bits. At 500 kbit/s, 2.816 ms is an idle-bus minimum, not a guaranteed recovery latency.
  5. Platform-specific operation: Use bxCAN ABOM/manual initialization-mode policy, supported Zephyr state-change and recovery APIs, or Linux SocketCAN error frames and restart-ms. Never run blocking restart logic inside an ISR.

References

  1. ISO 11898-1:2015 — Road vehicles — Controller Area Network (CAN) — Part 1: Data link layer and physical signaling. International Organization for Standardization. https://www.iso.org/standard/63648.html
  2. STMicroelectronics AN2857 — CAN bus error handling and recovery strategies for STM32 MCUs. Application Note. https://www.st.com/resource/en/application_note/an2857-can-bus-error-handling-and-recovery-strategies-for-stm32-mcus-stmicroelectronics.pdf
  3. STMicroelectronics RM0090 — STM32F405/415, STM32F407/417, STM32F427/437 and STM32F429/439 advanced Arm-based 32-bit MCUs Reference Manual (Section 28: bxCAN). https://www.st.com/resource/en/reference_manual/rm0090-stm32f405415-stm32f407417-stm32f427437-and-stm32f429439-advanced-armbased-32bit-mcus-stmicroelectronics.pdf
  4. Zephyr Project Documentation — CAN Controller API Reference (can_get_state, can_recover, can_set_state_change_callback). https://docs.zephyrproject.org/latest/hardware/peripherals/can/controller.html
  5. Linux Kernel Documentation — Linux SocketCAN Subsystem and Network Driver Architecture. The Linux Kernel Archives. https://www.kernel.org/doc/html/latest/networking/can.html
  6. Kvaser AB — The CAN Protocol: Error Handling and Fault Confinement. https://www.kvaser.com/about-can/the-can-protocol/can-error-handling/
  7. Grid Connect — CAN Bus Diagnostics: Step-by-Step Guide for Physical and Logical Troubleshooting. https://www.gridconnect.com/blogs/news/how-to-diagnose-a-controller-area-network-can

Frequently Asked Questions

What causes a CAN node to enter bus-off state?

Bus-off occurs when a CAN controller's Transmit Error Counter (TEC) exceeds 255. Many transmission errors add 8 to TEC, but the ISO 11898 fault-confinement rules have exceptions. In particular, a lone error-passive transmitter seeing only ACK errors, with no dominant bits detected during its passive error flag, does not continue increasing TEC for those ACK errors. A single unacknowledged node may therefore remain error-passive instead of reaching bus-off. Other repeated bit, form, or stuffing errors can cause bus-off.

How does automatic bus-off recovery (ABOM) work?

For STM32 bxCAN, enabling ABOM allows hardware-controlled recovery after bus-off when the controller has observed 128 occurrences of 11 consecutive recessive bits. This is at least 1408 nominal bit times of recessive observation; at 500 kbit/s, 2.816 ms is the ideal lower bound, not a guaranteed wall-clock delay on an active or faulty bus. Once recovery completes, the controller resumes error-active operation without software restarting it.

When should I use manual bus-off recovery instead of automatic?

Choose manual recovery when system requirements call for inspecting faults, applying a restart policy, or obtaining higher-level permission before rejoining. It is not universally mandated by ISO 26262 or IEC 61508. On STM32 bxCAN with ABOM disabled, software can control re-entry through initialization-mode exit, typically with HAL_CAN_Stop()/HAL_CAN_Start() from thread or main-loop context, while still respecting the controller's bus-idle recovery requirements.

Why does my CAN node show CRC errors on an otherwise working bus?

On STM32 bxCAN, LEC = 6 indicates a CRC sequence mismatch on a received frame, not a fault in the CRC delimiter. Possible causes include noise, reflections, wiring and termination problems, oscillator or bit-timing mismatch, or a failing transceiver. The common 60-ohm power-off resistance check applies to a conventional bus with exactly two 120-ohm terminators, not every CAN topology.

How do I read TEC and REC registers on STM32 bxCAN?

On STM32 bxCAN, read a single CAN_ESR snapshot: TEC is bits 23:16, REC bits 31:24, and LEC bits 6:4. For example, use (esr >> 16) & 0xFFU and (esr >> 24) & 0xFFU. HAL_CAN_GetError() returns accumulated HAL error flags rather than those two numeric counters. The visible 8-bit TEC field is not a readable value of 256 once bus-off occurs; use the BOFF flag to determine state.

Tags

canbus-offerror-handlingstm32zephyrembedded-linux

Share


Previous Article
Fixing FreeRTOS Timer Task Stall When Command Queue Is Full
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Fixing PWM Dead-Time Errors Causing MOSFET Shoot-Through
Fixing PWM Dead-Time Errors Causing MOSFET Shoot-Through
October 26, 2026
7 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media