Timeline
Timeline
2026-01-09
init
This article introduces the core features, application areas, and development history of the CAN bus, and discusses in detail the architecture principles and key component roles of two hardware connection methods: the CPU's built-in CAN controller and the SPI-to-CAN module.
Linux Driver Notes
| Table of Contents | Links |
|---|---|
| 1. Linux Driver Framework | |
| 2. Linux Driver Loading Logic | |
| 3. Character Device Basics | |
| 4. Concurrency and Competition | |
| 5. Advanced Character Device Progression | |
| 6. Interrupts | |
| 7. Platform Bus | |
| 8. Device Tree | |
| 9. Device Model | |
| 10. Hot Plug | |
| 11. pinctrl Subsystem | |
| 12. gpio Subsystem | |
| 13. Input Subsystem | |
| 14. Single Bus | |
| 15. I2C | |
| 16. SPI | |
| 17. UART | |
| 18. PWM | |
| 19. RTC | |
| 20. Watchdog | |
| 21. CAN | |
| 22. Network Device | |
| 23. ADC | |
| 24. IIO | |
| 25. USB | |
| 26. LCD |
Introduction to CAN Bus
CAN(Controller Area Network) is a serial communication protocol introduced by Bosch in 1986, designed specifically for automotive electronic systems to reduce the number of wiring harnesses in vehicles and enable efficient communication among multiple electronic control units (ECUs).
Core Features
- The CAN bus supports multi-master communication, where all nodes (ECUs) can actively send data without relying on a central controller.
- It uses a non-destructive arbitration mechanism to resolve bus conflicts via ID priority, ensuring that high-priority data is transmitted first.
- The bus has high reliability, with built-in CRC checks, error detection and recovery mechanisms, and uses differential signals to enhance resistance to electromagnetic interference.
- The CAN bus achieves low cost by simplifying wiring and reducing system complexity.
Application Areas
- Automotive Electronics: Engine control, body modules (lights/windows), diagnostic systems (OBD-II), etc.
- Industrial Automation: PLC, sensor networks, robot control.
- Other Fields: Medical devices, aerospace, smart buildings.
Development History
- 1983: Bosch initiates research on automotive network technology.
- 1986: Official release of the CAN protocol.
- 1987: Intel and Philips launch the first CAN controller chip.
- 1991: CAN 2.0 specification released, first applied in Mercedes-Benz S-Class.
- 1993: Becomes an international standard (ISO 11898).
- 2015: CAN FD (Flexible Data Rate) standardized (supports higher data rates and 64-byte data).
- 2020: Next-generation CAN XL released, with further bandwidth improvement.
CAN Hardware Connection
In CAN hardware connection, there are two cases: the CPU has an integrated CAN controller, or the CPU lacks a CAN controller and requires an external adapter (e.g., SPI to CAN).
CPU with Integrated CAN Controller
The connection diagram for a CPU with an integrated CAN controller is shown below. The CPU communicates directly with the CAN transceiver via the integrated CAN controller, and the CAN transceiver converts digital signals into differential signals suitable for CAN bus transmission (CAN_H and CAN_L)。The CPU can communicate directly with the CAN bus

| Component | Description |
|---|---|
| CPU and CAN Controller | Each CPU communicates with the CAN bus via a CAN controller. The CPU is responsible for handling control logic and data processing tasks, while the CAN controller manages the communication details of the CAN protocol. |
| CAN Tx | Signal line for transmitting data. The CPU sends data to the CAN bus through the CAN controller, and this signal line is used to transmit the sent data. |
| CAN Rx | Signal line for receiving data. The CPU receives data from the CAN bus through the CAN controller, and this signal line is used to receive data from the bus. |
| CAN Transceiver | The CAN transceiver is connected between the CPU’s CAN controller and the CAN bus, and its main functions are: Converting the digital signals output by the CPU into differential level signals suitable for transmission on the CAN bus (level conversion); At the same time, converting the differential signals on the bus back into digital signals recognizable by the CPU. |
| CAN H and CAN L | These are the two main physical signal lines of the CAN bus: CAN H: Used to transmit high-level signals; CAN L: Used to transmit low-level signals. Data transmission is achieved through the voltage difference between these two lines (differential signal), improving anti-interference capability. |
| 120Ω resistor | A 120Ω termination resistor is connected at each end of the CAN bus to: • Prevent signal reflection at the bus ends (impedance matching); • Ensure signal integrity and improve communication stability. These termination resistors are especially important in long-distance or multi-device connections. |
CPU without CAN controller
The connection diagram for a CPU without a CAN controller is shown below,The CPU communicates with the SPI-to-CAN module via the SPI controller, which converts SPI data into the format required by the CAN bus.
With this structure, the CPU can communicate with the CAN bus via the SPI protocol, suitable for application scenarios where connection to a CAN network is needed without a direct CAN controller. The termination resistors at both ends of the bus ensure the stability of CAN communication.

| Component | Description |
|---|---|
| CPU and SPI controller | The CPU communicates with SPI interface peripherals via the SPI controller. SPI (Serial Peripheral Interface) is a synchronous serial communication protocol commonly used for high-speed data exchange between microcontrollers and peripherals such as sensors and memory. |
| SPI to CAN Converter | This is a critical bridge module connected between the SPI controller and the CAN bus. Its function is to convert the data format of the SPI protocol into the CAN protocol format, enabling devices that originally could only communicate via SPI to communicate with other nodes through the CAN bus. |
| CAN Tx | The signal line for transmitting data, used to send data received from the SPI-to-CAN module onto the CAN bus. |
| CAN Rx | The signal line for receiving data, used to receive data from the CAN bus and transmit it to the SPI-to-CAN module for processing. |
| CAN Transceiver | Connected between the CAN bus and the SPI-to-CAN module, responsible for: Converting logic level signals (from the converter) into differential signals suitable for CAN bus transmission; Simultaneously converting the differential signals on the bus back into logic level signals and sending them back to the module. |
| CAN H and CAN L | The two differential signal lines of the CAN bus: CAN H: High-level signal line; CAN L: Low-level signal line. Data is transmitted through the voltage difference between the two, providing strong anti-interference capability. |
| 120Ω Resistor | A 120Ω termination resistor is connected at each end of the CAN bus, with the purpose of: Impedance matching to prevent signal reflection; Improve communication stability, especially in long-distance or multi-node connections. |
CAN Electrical Characteristics
The CAN bus uses differential signals for data transmission.
- CAN Signal Levels
The CAN bus uses two signal lines for data transmission: CAN_H (high level) and CAN_L (low level).
CAN_H and CAN_The voltage difference between L determines the state of the logic signal. This gives the CAN bus better anti-interference capability, making it especially suitable for operation in noisy environments.
- CAN_H: High-level signal line, typically with a voltage range of 2.5V to 3.5V.
- CAN_L: Low-level signal line, typically with a voltage range of 1.5V to 2.5V.
- Differential Signals and Anti-Interference
The CAN bus transmits data via differential signals, meaning information transfer relies on the voltage difference between CAN_H and CAN_L, rather than individual voltage values. The characteristic of differential signals gives the CAN bus extremely strong anti-interference capability in noisy environments.
Advantages of differential signals:
- Noise typically affects both CAN_H and CAN_L, but since differential signals rely on the voltage difference between the two,the effects of noise on both cancel each other out, thereby maintaining signal integrity.
- This characteristic makes the CAN bus perform excellently in noisy environments such as automotive and industrial control.
Electrical properties and operating states
The electrical properties of the CAN bus determine its operating states, specifically manifested as recessive and dominant states.
- Recessive state (logic “1”):When CAN_H and CAN_L have equal voltages(typically 2.5V), indicating**The bus is in an idle state.**At this time, there is no data transmission on the bus, and all devices are waiting for communication. The recessive state is also called “idle level” or “logic 1”.
- Dominant state (logic “0”):When CAN_H and CAN_L the voltage difference is 2V ,it indicatesdata is being transmitted. Specifically, CAN_H is 3.5V, CAN_L is 1.5V, representing logic “0”. The dominant state indicates that the bus is transmitting data, andit has a higher priority。

iTOP-RK3568 development board CAN interface
The RK3568 SoC can use up to 3 CAN interfaces

Among them,TJA1040Tis a high-speed CAN transceiver chip produced by NXP. It is responsible for converting the CPU’s digital signals into signals suitable for CAN bus transmission and receiving data from the bus. According to the net label, the development board uses CAN1
| CAN interface | pinctrl function | Net label | Corresponding GPIO | Function |
|---|---|---|---|---|
| CAN0 | CAN0_TX_M0 | I2C1_SCL_TP | GPIO0_B3_u | MIPI screen touch I2C |
| CAN0_RX_M0 | I2C1_SDA_TP | GPIO0_B4_u | MIPI screen touch I2C | |
| CAN0_TX_M1 | SDMMC0_CMD | GPIO2_A1 | TF card CMD pin | |
| CAN0_RX_M1 | SDMMC0_CLK | GPIO2_A2 | TF card clock pin | |
| CAN1 | CAN1_TX_M0 | I2C3_SCL_M0 | GPIO1_A1_u | Backplane back 20-pin GPIO |
| CAN1_RX_M0 | I2C3_SDA_M0 | GPIO1_A0_u | Backplane back 20-pin GPIO | |
| CAN1_TX_M1 | HDMI_RX_INT_L_GPIO4_C3 | GPIO4_C3_d | CAN TX | |
| CAN1_RX_M1 | 4G_DISABLE_GPIO4_C2 | GPIO4_C2_d | CAN RX | |
| CAN2 | CAN2_TX_M0 | I2C2_SCL_M1 | GPIO4_B5_d | MIPI screen touch I2C |
| CAN2_RX_M0 | I2C2_SDA_M1 | GPIO4_B4_d | MIPI screen touch I2C | |
| CAN2_TX_M1 | WIFI_WAKE_HOST_H_GPIO2_B2 | GPIO2_B2_u | Base plate lead unused | |
| CAN2_RX_M1 | WIFI_REG_ON_H_GPIO2_B1 | GPIO2_B1_u | Base plate lead unused |
CAN protocol frame structure
Frame types
A frame is the basic unit of data transmission in CAN communication. Five different types of frames are used in CAN communication to achieve different functions. Below is a brief description of each frame type and its purpose:
- Data Frame: The data frame is the most commonly used frame type in CAN communication, used by the transmitting unit to transfer data to the receiving unit. Data frames have two formats:
- Standard format (11-bit identifier) suitable for simpler networks
- Extended format (29-bit identifier) suitable for more complex networks.
- Remote Frame: The remote frame is used by the receiving unit to request data from the transmitting unit. It does not contain a data field, but instead tells the transmitting unit via the identifier (ID) “I need the data corresponding to this ID.” Remote frames also have standard and extended formats, with a structure similar to data frames but lacking the data field.
- Error Frame: The error frame is used when a node detects an error to notify other nodes of the error occurrence. It is a special frame used to interrupt the current communication and restart. The error frame consists of an error flag (6 consecutive dominant or recessive bits) and an error delimiter, and is triggered by conditions such as bit errors, stuffing errors, CRC errors, etc.
- Overload Frame: The overload frame is used by the receiving unit to notify the transmitting unit that it is not yet ready to receive. It typically occurs when the receiving node needs more time to process the previous frame. Overload frames can only be sent during the interframe space, and their structure is similar to error frames, consisting of an overload flag and an overload delimiter.
- Interframe Space: The interframe space is used to separate data frames or remote frames from the preceding frame. It is a time interval that ensures nodes in the network can correctly identify the start of the next frame. For data frames and remote frames, the interframe space is typically 3 bit times; for error frames and overload frames, the interframe space may differ.
| Frame Type | Purpose |
|---|---|
| Data Frame | A frame that transmits data from the sending unit to the receiving unit. |
| Remote Frame | A frame that requests data from the sending unit with the same ID by the receiving unit. |
| Error Frame | A frame that notifies other units of an error when an error is detected. |
| Overload Frame | A frame that notifies that the receiving unit is not yet ready to receive. |
| Interframe Space | A frame that separates data frames and remote frames from the preceding frame. |
Data Frame
The data frame is the most core frame type, responsible for carrying actual data content and enabling efficient information transmission between the sending unit and the receiving unit.
In early CAN communication,the standard data frame uses an 11-bit identifier, which could meet the relatively simple network architecture requirements at that time. However, as vehicle functions became more complex (such as advanced driver assistance systems, powertrain control, body electronics, etc.), the address space of the 11-bit identifier gradually proved insufficient, making it difficult to support larger-scale nodes and more refined communication needs. For this reason, the CAN protocol introducedthe extended data frame, which uses a29-bit identifierto provide a larger address space, significantly improving the flexibility and scalability of the network.
Standard Data Frame
The standard data frame is the basic structure used for data transmission in the CAN communication protocol. It contains multiple fields, each with a different function, ensuring efficient and secure data transmission. The composition block diagram of the data frame is shown below.

From the above diagram, it can be seen that the standard data frame consists of the following 7 main fields:
Start of Frame
- The start of frame consists of a fixed dominant bit(logic 0)Composition,Used to identify the start of a data frame。
It not only notifies the receiving device to prepare for data reception but also synchronizes the clocks of the transmitter and receiver, ensuring correct parsing of subsequent data.
Arbitration field(Arbitration Field)
- ID(11-bit identifier) is mainly used to distinguish message types, priorities, and determine transmission order. The smaller the identifier value, the higher the priority;
- RTR bit(1 bit, Remote Transmission Request) is used to distinguish between data frames (dominant 0) and remote frames (recessive 1). Additionally, the high 7 bits in the arbitration field are prohibited from being all recessive to avoid arbitration errors.
Control field(Control Field)
- IDE bit(1 bit) is used to distinguish between standard frames (dominant 0) and extended format
- RO bit(1 reserved bit), the reserved bit is fixed to dominant 0 for future expansion
- DLC bit(4 bits) indicates the number of bytes contained in the data field (range from 0 to 8 bytes).
Data field(Data Field)
- Data FieldContains up to 8 bytes (64 bits), which is the core part of the data frame, used to carry the actual communication data content.
- Itslength is specified by the DLC bits in the control field, ranging from 0 bytes (no data) to 8 bytes (maximum data amount). The content of this field is the actual information of the communication, which may include sensor data, control commands, etc.
CRC Check Field(CRC Field)
- CRC check code (15 bits)
- CRC delimiter (1 bit), fixed as recessive 1, used to clearly mark the end of the CRC field.
- The receiving device verifies data integrity by recalculating the CRC and comparing it with the received CRC check code.
ACK Field(Acknowledgment Field)
- ACK slot (1 bit), when the receiving device successfully receives the data frame, it returns a dominant bit in the ACK slot as an acknowledgment signal, indicating that the data frame has been correctly received
- ACK delimiter (1 bit), the ACK delimiter is fixed as recessive 1, used to mark the end of the ACK field.
End of Frame(End of Frame)
- Consists of 7 consecutive recessive bits (logic 1), used to clearly mark the end of the data frame.
- It not only tells the receiving device that the data frame has been transmitted completely, but also provides extra time for signal synchronization to ensure correct reception of the next frame.
| Field Name | Composition | Function |
|---|---|---|
| Start of Frame | 1 dominant bit (0) | Marks the start of the data frame and is used to synchronize the clocks of the transmitter and receiver, ensuring correct parsing of subsequent data. |
| Arbitration Field | 11-bit identifier + 1-bit RTR bit | Distinguishes message type (data frame or remote frame), priority, and transmission order; the smaller the identifier value, the higher the priority; the RTR bit distinguishes data frames (dominant 0) from remote frames (recessive 1); the high 7 bits are prohibited from being all recessive. |
| Control Field | 1 IDE bit + 1 RO reserved bit + 4 DLC bits | The IDE bit distinguishes standard frames (dominant 0) from extended frames (recessive 1); the reserved bit is fixed to dominant 0 for future expansion; the DLC bits indicate the data field length (0-8 bytes). |
| Data Field | Up to 8 bytes (64 bits) | Carries the actual communication data content, with length specified by the DLC bits; the data field is the core part of communication, potentially containing sensor data, control commands, and other actual information. |
| CRC Check Field | 15-bit CRC check code + 1 CRC delimiter | Detects errors during data transmission; the receiving device verifies data integrity by recalculating the CRC and comparing it with the received CRC check code; the CRC delimiter is fixed to recessive 1, marking the end of the CRC field. |
| ACK Field | 1 ACK slot + 1 ACK delimiter | The receiving device returns a dominant bit in the ACK slot to confirm successful reception of the data frame; the ACK delimiter is fixed to recessive 1, marking the end of the ACK field. |
| End of Frame | 7 recessive 1 bits | Clearly marks the end of the data frame, notifying the receiving device that the data frame transmission is complete, and provides additional time for signal synchronization to ensure correct reception of the next frame. |

SRR bit function
The SRR bit in the CAN protocol replaces the RTR bit of standard frames and is located at the original RTR bit position in the arbitration field of extended frames.
Its function is to be forced to a recessive level (1) to ensure that when a standard frame and an extended frame compete for the bus simultaneously, the standard frame has higher priority due to its dominant RTR bit (0). When both frames are sent at the same time, the bus arbitration logic detects the dominant level (0), allowing the standard frame to win.
IDE bit
The IDE bit is the identifier extension flag used to distinguish frame types:Dominant (0) indicates the current frame is a standard frame, recessive (1) indicates an extended frame。
In extended frames, the IDE bit exists not only in the arbitration field to identify the frame type but also appears in the control field, further clarifying the frame structure and enabling differentiation between extended and standard frames.
Remote frame
Remote Frameis a special frame type in the CAN protocolused to actively request data。
When a node needs to obtain data from other nodes, it can send a remote frame to initiate a request on the bus, and the target node returns the corresponding data frame upon receiving the request.
A remote frame is a data frame with the data field removed, and like remote frames, remote frames are also divided into standard remote frames and extended remote frames, with their respective structures as follows:

- Start of Frame
- The start of frame consists of 1 dominant bit (0), identical to that of a data frame, used to mark the beginning of a remote frame.
- It not only notifies the receiving device to prepare for data reception but also synchronizes the clocks of the transmitter and receiver, ensuring the accuracy of subsequent data parsing.
- Arbitration Field:
- 11-bit Identifier (ID)
- Consists of 1 RTR bit (recessive 1),
- Used to specify the type of data frame being requested, and distinguishes from data frames (dominant 0) via the recessive RTR bit (1), ensuring lower priority than data frames with the same ID. In extended remote frames, the arbitration field expands to a 29-bit identifier (ID), SRR bit (recessive 1), IDE bit (recessive 1), and RTR bit (recessive 1). The SRR bit replaces the RTR bit of standard frames, ensuring extended frames have lower priority than standard data frames during arbitration; the recessive IDE bit (1) identifies the frame as an extended frame.
- Control Field: Same as the control field in standard data frames and extended data frames.
- Data Field: Remote framehas no data field, which is the core difference from data frames. By omitting the data field, it clearly indicates that the frame is a request rather than data transmission, thereby triggering the target node to send a data frame with the corresponding ID.
- CRC Field:
- 15-bit CRC checksum
- 1 recessive CRC delimiter
- Used to verify whether errors occur during the transmission of the remote frame. The receiving device recalculates the CRC and compares it with the received CRC check code to ensure the reliability of the request.
- **ACK field (Acknowledgment Field)**The ACK field consists of 1 ACK slot bit and 1 recessive ACK delimiter bit. After the receiving node successfully receives the remote frame, it returns a dominant bit in the ACK slot as an acknowledgment signal, indicating that the remote frame has been correctly received, while the ACK delimiter is fixed as recessive 1 to mark the end of the ACK field.
- End of Frame
- The end of frame consists of 7 consecutive recessive 1 bits, same as the data frame, used to clearly mark the end of the remote frame. It not only tells the receiving device that the remote frame transmission is complete but also provides additional time for signal synchronization, ensuring correct reception of the next frame.
| Field Name | Composition | Function |
|---|---|---|
| Start of Frame | 1 dominant 0 bit | Marks the start of the remote frame, synchronizes the clocks of the transmitter and receiver, and ensures the accuracy of subsequent data parsing. |
| Arbitration Field | Standard frame: 11-bit ID + RTR (recessive 1) Extended frame: 29-bit ID + SRR (recessive 1) + IDE (recessive 1) + RTR (recessive 1) | Specifies the type of data frame requested; RTR recessive 1 distinguishes it from data frames; the extended frame is compatible with standard frames via SRR and IDE bits, with lower priority than data frames with the same ID. |
| Control Field | Standard Frame: IDE + R0 + 4-bit DLC bits; Extended Frame: R1 + R0 + 4-bit DLC bits | The DLC bits indicate the number of bytes in the target data frame (0-8 bytes), but the remote frame itself carries no data; the IDE bit distinguishes between extended and standard frames. |
| Data Field | None | Clearly indicates that the remote frame is a request frame and does not perform data transmission. |
| CRC Check Field | 15-bit CRC check code + 1 recessive CRC delimiter | Verifies the correctness of the remote frame transmission process, ensuring the reliability of the request. |
| ACK Field | 1-bit ACK slot (filled with dominant bit by receiving node) + 1 recessive ACK delimiter | The receiving node confirms correct reception of the remote frame via the ACK slot, and the ACK delimiter marks the end of this field. |
| End of Frame | 7 recessive bits (1) | Marks the end of the remote frame, providing signal synchronization time to ensure correct reception of the next frame. |
Error Frame
An error frame is a special frame in the CAN bus used to indicate that an error has occurred during communication. Its structure differs from other frames (such as data frames or remote frames) and is primarily used to notify all nodes in the network that the current transmission has an error.

- Error Flag
- 6 consecutive dominant bits (logic 0) or recessive bits (logic 1), divided into active error flag and passive error flag.
- Active Error FlagSent by the node that detects the error, it forcibly interrupts the transmission of the current frame and notifies all nodes in the network of the error occurrence;
- Passive Error FlagIt is sent by a node in the passive error state to avoid interfering with the normal communication of other nodes.
- Error Delimiter
- Composed of 8 consecutive recessive bits (logic 1), it is used to mark the end of the error frame. It ensures that all nodes can clearly identify the boundary of the error frame and resume normal communication flow after error handling is complete.
| Field Name | Composition | Function |
|---|---|---|
| Error Flag | Active Error Flag: 6 dominant bits; Passive Error Flag: 6 recessive bits | The active error flag forcibly interrupts the current frame transmission to notify network nodes of an error; the passive error flag avoids interfering with other nodes’ communication. |
| Error Delimiter | 8 recessive bits | Marks the end of an error frame, helping all nodes identify the error frame boundary and resume normal communication. |
Overload Frame
An overload frame is a special frame in the CAN bus used to notify other nodes on the network that the receiving device needs more time to process data. It is typically sent when the receiving node cannot process the received data in time, requesting the transmitting node to delay the next frame. The composition of an overload frame is as follows:

- Overload Flag
- Consists of 6 consecutive dominant bits (logic 0), sent by the receiving node to notify other nodes on the network that the receiving device needs more time to process data, thereby requesting a delay in the next frame’s transmission.
- Multiple nodes can send overload flags simultaneously, and these flags will superimpose to form a longer sequence of dominant bits.
- Overload Delimiter
- Consists of 8 consecutive recessive bits (logic 1), used to mark the end of an overload frame.
- It ensures that all nodes can clearly identify the boundaries of the overload frame and resume normal communication flow after overload handling is complete.
| Field Name | Composition | Function |
|---|---|---|
| Overload Flag | 6 consecutive dominant bits | Sent by the receiving node to inform other nodes on the network that it needs more time to process data, requesting a delay in the next frame transmission. |
| Overload Delimiter | 8 consecutive recessive bits | Marks the end of the overload frame, helping all nodes identify its boundaries, thereby restoring normal communication flow. |
The overload frame consists ofan overload flagandan overload delimiterTwo fields implement the identification and handling of insufficient processing capability at the receiving node.
When the receiving node cannot process data in time, it sends an overload flag (6 dominant bits) to notify other nodes in the network to delay the transmission of the next frame; then, an overload delimiter (8 recessive bits) clearly marks the end of the overload frame.
The design of the overload frame ensures that nodes in the network can coordinate communication under high load conditions, avoiding data loss or errors.
Bit Stuffing
Bit stuffing is an important mechanism in the CAN protocol used to ensure signal synchronization during data transmission.
Bit stuffing ensures that there is always a level change on the bus by inserting a stuffing bit of opposite polarity after five consecutive bits of the same polarity, thereby maintaining synchronization between the transmitter and receiver.
Stuffing is only performed from the start of frame to the CRC field to avoid interference with other parts. After detecting the stuffing bit, the receiver automatically removes it to restore the original data. This mechanism is crucial for preventing signal synchronization issues and improving the reliability of CAN bus communication.
Core Purpose
By inserting a stuffing bit of opposite polarity after five consecutive bits of the same polarity, it avoids bus synchronization issues caused by prolonged ‘0’ or ‘1’ levels, thereby improving communication reliability.
Bit Stuffing Rules
When five consecutive bits of the same polarity appear in the data, a stuffing bit with opposite polarity is inserted at the sixth bit.
This mechanism ensures that there is always a level change on the bus by breaking up potentially long strings of the same level, thereby maintaining synchronization between the transmitter and receiver.
Stuffing Range
Performed from the start of frame to the CRC field,
- Example 1:
- Original data: 110000011
- Analysis: No 5 consecutive identical polarity bits appear, so no padding is needed.
- Actual transmitted data: 1100000111
- The receiver directly recovers the original data: 110000011
- Example 2:
- Original data: 0111111
- Analysis: 5 consecutive '1’s appear, so a ‘0’ is inserted at the 6th bit.
- Actual transmitted data: 01111101
- The receiver detects and removes the padding bit, recovering the original data: 0111111
- Example 3:
- Original data: 1000001111
- Analysis: Five consecutive '0’s appear, so a ‘1’ is inserted at the 6th bit. After inserting the ‘1’, five consecutive '1’s appear, so a ‘0’ needs to be added at the last bit.
- Actual transmitted data: 100000111110
- The receiver detects and removes the stuffing bits, restoring the original data: 1000001111
CAN waveform example analysis
Standard data frame

CAN communication is determined by a pair of differential signal lines, but the CAN waveform above shows only one signal. This is because the waveform was captured by a logic analyzer, which automatically converts the differential signal into a logic signal. Then the waveform is analyzed.
Start of frame
First is the start of frame, which consists of a fixed dominant bit (logic 0) used to mark the beginning of a data frame.

Arbitration field
Next is the 12-bit arbitration field, where the first 11 bits are the identifier (ID) and the last bit is the remote transmission request (RTR) bit. The identification diagram is shown below, where bits marked with a red ‘×’ indicate stuffing bits, so they should be ignored during actual analysis. The last RTR bit is dominant (logic 0), so the currently transmitted frame is a data frame.

Control field
After the arbitration field comes a 6-bit control field, including 1 IDE bit, 1 reserved bit (R0), and 4 data length code (DLC) bits. As shown in the identification diagram, the IDE bit is dominant (logic 0), so the current frame is a standard frame. The reserved bit R0 defaults to dominant (logic 0), and the last four DLC bits are 0001, indicating that 8 bits of data will be sent next.

Data Field
Next is the 8-bit data field, which is used to carry the actual communication data content. As shown in the identification diagram, the data to be sent is 00000001, and then the analysis continues.

CRC Check Field

ACK Field
The next two bits are the ACK field (Acknowledgment Field). The ACK field consists of 2 bits, including 1 ACK slot and 1 ACK delimiter. When the receiving device successfully receives the data frame, it returns a dominant bit in the ACK slot as an acknowledgment signal, indicating that the data frame has been correctly received. The ACK delimiter is fixed as recessive 1, used to mark the end of the ACK field. The identification diagram is as follows:

Finally, the end of frame consists of 7 consecutive recessive bits (logic 1), used to clearly mark the end of the data frame.
Extended Remote Frame

Start of Frame
First is the start of frame. The start of frame consists of a fixed dominant bit (logic 0), used to mark the beginning of the data frame, as indicated in the diagram below.

Arbitration Field
Next is the 12-bit arbitration field, where the first 11 bits are the identifier (ID) and the last bit is the Remote Transmission Request (RTR) bit. The identification diagram is shown below, where bits marked with a red X indicate stuff bits, so they should be ignored during actual analysis. The last RTR bit is recessive (logic 1), and it can be observed that there are no data bits to be transmitted afterward, so the currently transmitted frame is a remote frame.

Control Field
Following the arbitration field is the 6-bit control field, which includes 1 IDE bit, 1 reserved bit (R0), and 4 data length code (DLC) bits. The identification diagram is shown below. The IDE bit is recessive (logic 1), so the current frame is an extended remote frame. The reserved bit R0 defaults to dominant (logic 0), and the last four DLC bits are 0001. However, since the current frame is a remote frame, no data is transmitted.

CRC Check Field
The CRC check field consists of 15 bits of CRC check code and 1 CRC delimiter, used to detect errors during data transmission. The identification diagram is shown below. The last CRC delimiter is fixed as recessive 1 to mark the end of the CRC field.

ACK Field
The next two bits are the ACK field (Acknowledgment Field), which consists of 2 bits: 1 ACK slot and 1 ACK delimiter. When a receiving device successfully receives a data frame, it returns a dominant bit in the ACK slot as an acknowledgment signal, indicating that the data frame has been correctly received. The ACK delimiter is fixed as recessive 1 to mark the end of the ACK field. The identification diagram is shown below:

Finally, the end of frame consists of 7 consecutive recessive bits (logic 1).
Extended Data Frame

Start of Frame
First is the start of frame, which consists of a fixed dominant bit (logic 0) used to mark the beginning of the data frame, as indicated in the diagram below.

Extended Frame
Based on the waveform length and the yellow marker above, this frame is an extended frame. Therefore, in the next 12 bits, the first 11 bits are the identifier (ID), and the last bit is the SRR bit. The identification diagram is shown below, where bits marked with a red × indicate stuff bits, so they should be ignored during actual analysis. The SRR bit is a recessive bit (logic 1).

Next is the IDE bit, which is a recessive bit (logic 1), so the current frame is an extended frame. However, whether it is an extended remote frame or an extended data frame requires further analysis.

In the next 19 bits, the first 18 bits are also ID bits, and the last bit is the RTR bit. The identification diagram is shown below. The RTR bit is a dominant bit (logic 0), so the currently transmitted frame is an extended data frame. Continue with further analysis:

Control Field
The next six bits are the control field, which includes 2 reserved bits (R1 and R0) and 4 data length code (DLC) bits. The identification diagram is shown below. The last four DLC bits are 0001, indicating that 8 bits of data will be sent next.

Data Field
Next is the 8-bit data field, which carries the actual communication data content. The identification diagram is shown below. The data to be sent is 00000001.

CRC Check Field
The CRC check field consists of a 15-bit CRC check code and a 1-bit CRC delimiter, used to detect errors during data transmission. The identification diagram is shown below. The last bit, the CRC delimiter, is fixed as a recessive 1 to clearly mark the end of the CRC field.

ACK Field
The next two bits are the ACK field (Acknowledgment Field). The ACK field consists of 2 bits, including a 1-bit ACK slot and a 1-bit ACK delimiter. After a receiving device successfully receives a data frame, it returns a dominant bit in the ACK slot as an acknowledgment signal, indicating that the data frame has been correctly received. The ACK delimiter is fixed as a recessive 1 to mark the end of the ACK field. The identification diagram is shown below.

Finally, the end of frame consists of 7 consecutive recessive bits (logic 1), used to clearly mark the end of the data frame.
Core Mechanisms and Communication Principles of CAN Bus
Bit Time
In CAN bus communication,**bit time refers to the time required to transmit one logical bit,**which is one of the core concepts for achieving reliable data transmission in the CAN protocol, directly affecting the communication baud rate and signal synchronization accuracy. As the basis of asynchronous communication, all nodes maintain synchronization through an agreed-upon bit time.
The CAN protocol divides the bit time into multiple time segments, which together determine the signal sampling and synchronization mechanism. Specifically, it includes the following parts:

- Sync Segment
The sync segment is the first part of the bit time,fixed to 1 time quantum(TQ (Time Quantum) is the basic unit of bit time, and all time segments are divided based on the time quantum), mainly used to detect signal edges and achieve hard synchronization.
During the Start of Frame (SOF) phase, the receiving node forcibly adjusts its own clock based on the falling edge of the bus signal to align with the bus signal, thereby ensuring that all nodes remain synchronized at the initial stage of communication.
- Propagation Segment
The propagation segment is used to compensate for the signal propagation delay on the bus and the response time of the input comparator. Its length is typically 1 to 8 time quanta (TQ), with the specific value determined by configuration. This
time segment allows the signal to propagate on the physical medium and ensures that all nodes can receive a stable signal, thereby avoiding sampling errors caused by propagation delays.
- Phase Segment 1
Phase Segment 1 is a configurable part of the bit time, typically 1 to 8 time quanta (TQ),mainly used to adjust the position of the sampling point, ensuring it is located in a stable signal region。
If a signal edge is detected to arrive early,,it can be achieved by shortening the phase buffer segment 1 to achieve resynchronization,Thus dynamically compensating for the effects of clock deviation or signal jitter.。- Phase Segment 2
Phase Segment 2 is similar to Phase Segment 1, also a configurable part of the bit time, typically ranging from 1 to 8 Time Quanta (TQ).
It is mainly used to handle cases where the signal edge arrives late.。If the signal edge is delayed,,it can be compensated by extending the phase buffer segment, 2 achieving resynchronization.,Thus ensuring that the receiving node can sample the signal at the correct time,,improving the reliability of data transmission.。Role of Bit Time
- Ensuring synchronization: By dividing time segments, CAN nodes can dynamically adjust the sampling point when a signal edge occurs, compensating for clock deviation and signal delay, thereby achieving synchronization among multiple nodes.
- Improving anti-interference capability: Setting the sampling point in a stable signal region (e.g., at 87.5% of the bit time) to avoid misjudgment caused by signal edge jitter or interference.
- Supporting flexible configuration: By adjusting the lengths of various time segments (such as the propagation segment, phase buffer segments, etc.), it can adapt to different baud rates and network environments.
Hard Synchronization and Resynchronization
In CAN communication, due to the use of asynchronous communication and the absence of an independent clock line, each node relies on its local crystal oscillator for data transmission. However, clock drift of the crystal oscillator can cause gradual timing offset between nodes, ultimately leading to sampling errors. To address this issue, the CAN protocol implements dynamic timing adjustment through two major mechanisms: hard synchronization and resynchronization:
- Hard synchronization forcibly aligns the clocks of all nodes during the frame start phase, eliminating initial phase deviation.;
- Resynchronization dynamically adjusts the length of the phase buffer segment based on real-time detection of signal edges during data transmission to compensate for clock drift.。
These two mechanisms work together, combined with the bit time division (synchronization segment, propagation segment, phase segments I/II) and the quantitative management of time quanta (Tq), to ensure that all nodes accurately read the bus level at the sampling point, thereby achieving highly reliable data transmission in asynchronous communication without a separate clock line. This subsection will provide a detailed explanation of hard synchronization and resynchronization.
Hard Synchronization
In CAN communication, hard synchronization is an important mechanism to ensure consistent initial timing among all nodes. Its core function isto forcibly align the timing of each node during the start-of-frame (SOF) phase, thereby eliminating the initial phase difference caused by local crystal oscillator variations.。
The trigger condition for hard synchronization isWhen the bus detects a falling edge of a dominant level (logic 0) from the idle state (i.e., the edge of the SOF bit), the node immediately adjusts its own timing to align the synchronization segment of the current bit to that edge.。
This process can be divided into the following steps:
- The nodecontinuously monitors level changes during bus idle periods.;
- Whena falling edge of SOF is detected and this edge falls within the synchronization segment, hard synchronization is triggered.;
- The node forcibly adjusts its timing, aligning the start of the synchronization segment of the current bit to that edge, and restarts the counting of subsequent bit times.。

However,The scope of hard synchronization is limited; it only takes effect at the start of a message frame and can only resolve initial phase offset issues.。
Resynchronization
In CAN communication,resynchronization is a key mechanism for resolving dynamic phase errors caused by clock drift or signal interference during communication.。
Unlike hard synchronization, resynchronization is not limited to the start of a frame, butcontinuously functions throughout the entire data transmission process.。Its core function is to dynamically adjust the position of the sampling point,,ensuring that the receiving node can read the bus level at the correct time,,thereby maintaining communication reliability.。
Specifically,the trigger condition for resynchronization is when a deviation is detected between the signal edge (such as a change from dominant to recessive level) and its expected position.。
- If the signal edge arrives early, it indicates that the sending node’s clock is faster than the receiving node’s clock. In this case, the receiving node advances the sampling point by shortening Phase Buffer Segment 1.
- Conversely, if the signal edge arrives late, it indicates that the sending node’s clock is slower than the receiving node’s clock. The receiving node then delays the sampling point by extending Phase Buffer Segment 2.
This dynamic adjustment process relies on theSynchronization Jump Width (SJW), which defines the


The advantage of resynchronization lies in its flexibility and real-time capability, effectively addressing challenges caused by clock drift or signal propagation delays during communication.
However,the adjustment range of resynchronization is limited by the configuration of SJW configuration,If the phase error exceeds the limit of SJW limitation,This may lead to sampling errors,thereby affecting the reliability of communication。
Therefore, resynchronization and hard synchronization work together to form the complete synchronization mechanism in the CAN protocol: hard synchronization provides initial alignment for communication, while resynchronization dynamically compensates for errors during subsequent transmission, ensuring the accuracy and stability of data transmission.
Arbitration Rules
In CAN bus communication, since multiple nodes share the same bus and only one data frame can be transmitted at a time, an efficient arbitration mechanism is required to ensure orderly data transmission.
The CAN protocol achieves efficient, collision-free communication among multiple nodes through the collaboration of carrier sensing, non-destructive arbitration, and read-back mechanisms.
Carrier Sensing
Beforesending data, each node first listens to the bus status, and only when the bus is idle (i.e., no other node is transmitting data) is the node allowed to start sending data.
This mechanism is similar to ‘Carrier Sense Multiple Access (CSMA)’ in Ethernet, effectively preventing multiple nodes from seizing the bus simultaneously.
If two or more nodes detect the bus idle and start sending data almost simultaneously,they enter the non-destructive arbitration phase。Non-destructive Arbitration
Non-destructive arbitration is the core of the CAN bus arbitration mechanism, and its core principle isBased on the wired-AND mechanism
- When all nodes send recessive level (logic 1), the bus appears recessive;
- As long as one node sends a dominant level (logic 0), the bus appears dominant.
This mechanism ensures that even if multiple nodes send data simultaneously, the signal on the bus is not corrupted but is dominated by the dominant level. The arbitration process is as follows:
- The identifier (ID) field of each data frame is used for arbitration priority,The smaller the ID, the higher the priority。
- When multiple nodes send data simultaneously, they compare their own transmitted ID bit by bit with the actual level on the bus,
- If a node sends a recessive level (1) but detects a dominant level (0) on the bus, it indicates that a higher-priority node is sending data. This node immediately stops transmitting and enters listening mode, waiting for the next bus idle time to retry sending.
- If a node sends a dominant level (0) and the bus also shows a dominant level (0), the node continues transmitting, indicating it currently has the highest priority.
Read-back mechanism
To ensure the correctness of arbitration and the reliability of data transmission, CAN nodescontinuously read back the signal on the bus while sending data,and compare it with the data they are sending
This mechanism ensures that low-priority nodes can withdraw from transmission in time, avoiding interference with the communication of high-priority nodes
Error State
In the CAN protocol, the error state of a node is dynamically adjusted based on the**Transmit Error Counter (TEC)andReceive Error Counter (REC)**values.
Through three different error states: active error state, passive error state, and bus-off state,
the CAN protocol achieves effective management and isolation of faulty nodes, while ensuring the reliability and stability of communication.
Active Error State
When both the Transmit Error Counter (TEC) and Receive Error Counter (REC) of a node are less than or equal to 127, the node is in the active error state.
In this state, the node can normally participate in bus communication and actively sends an active error flag (dominant bit) when an error is detected. This dominant flag forcibly overrides the bus signal, notifying other nodes of the current error.
Since the dominant bit has higher priority, this mechanism can quickly propagate error information, thereby ensuring that errors are handled in a timely manner and maintaining the reliability of bus communication.
Passive Error State
If a node’s Transmit Error Counter (TEC) or Receive Error Counter (REC) exceeds 127 (typically triggered by TEC), the node enters the passive error state.
In this state, the node can still participate in communication, but its behavior is restricted: it cannot actively send dominant error flags; instead, it sends passive error flags (recessive bits) to avoid disturbing the bus. Additionally, after each transmission, a delay of 8 recessive bits must be inserted before attempting communication again.
It is worth noting that if only a node in the passive error state detects an error while other active nodes do not, the bus is considered error-free, and communication continues.
This design both limits the impact of low-reliability nodes on the bus and ensures the communication efficiency of high-reliability nodes.
Bus-Off State
When a node’s Transmit Error Counter (TEC) exceeds 255, the node enters the bus-off state.
In this state, the node is completely prohibited from communicating; it can neither send nor receive data, to prevent further disturbance to the bus.
To resume communication, the node must detect 128 consecutive occurrences of 11 recessive bits (i.e., the bus being idle for a sufficient period), then reset TEC and REC to 0, thereby returning to the active error state and rejoining bus communication.
This mechanism is designed to isolate severely faulty nodes while providing them with an opportunity to rejoin the bus.

The more specific conditions for changes in the Receive Error Counter (REC) and Transmit Error Counter (TEC) are shown in the following table:
| Serial Number | Conditions for Changes in Receive and Transmit Error Counters | Transmit Error Counter (TEC) | Receive Error Count (REC) |
|---|---|---|---|
| 1 | When the receiving unit detects an error. Exception: When the receiving unit detects a ‘bit error’ while sending an error flag or overload flag, the receive error count does not increase. | — | +1 |
| 2 | When the first bit detected by the receiving unit after sending the error flag is dominant. | — | +8 |
| 3 | When the transmitting unit outputs an error flag. | +8 | — |
| 4 | When the transmitting unit detects a bit error while sending an active error flag or overload flag. | +8 | — |
| 5 | When the receiving unit detects a bit error while sending an active error flag or overload flag. | — | +8 |
| 6 | When each unit detects 14 consecutive dominant bits from the start of an active error flag or overload flag. Thereafter, each time 8 consecutive dominant bits are detected. | +8 when transmitting | +8 when receiving |
| 7 | When 8 consecutive dominant bits are detected after a passive error flag. | +8 when transmitting | +8 when receiving |
| 8 | When the transmitting unit successfully completes data transmission (when ACK is returned and no error is detected up to the end of frame). | ±0 when TEC=0, otherwise -1 | — |
| 9 | When the receiving unit successfully completes data reception (when no error is detected up to CRC and ACK is returned normally). | — | When 1≤REC≤127: -1; when REC=0: ±0; when REC>127: set REC=127 |
| 10 | A unit in bus-off state detects 128 consecutive occurrences of 11 recessive bits. | TEC=0 | REC=0 |
Error Detection Mechanism
The CAN (Controller Area Network) protocol effectively improves communication reliability through various error detection methods.
The error detection mechanism can be divided into the following five types: bit error, stuff error, CRC error, form error, and ACK error.
Bit Error
Bit error refers toan error detected when the transmitting unit compares its own output level with the bus level (excluding stuff bits) during communication and finds them inconsistent.。
This error usually indicates a conflict or interference between the transmitting node and the signal on the bus.
Bit errors can occur in the data frame,、remote frame,、error frame, and any segment of the overload frame.(From SOF to EOF)。Since bit errors are detected by the transmitting unit itself, the detecting unit is the transmitting unit.
Stuff Error
A stuff error refers toan error triggered when the receiving unit detects six consecutive identical bits within a segment requiring bit stuffing.。
The CAN protocol stipulates that in a bit stuffing segment, a stuffing bit of opposite polarity must be inserted after every five consecutive identical bits to ensure DC balance of the signal.
If the receiving unit detects six consecutive identical bits, it considers a stuff error to have occurred.
Stuff errors mainly occur in any segment of data frames and remote frames.(From SOF to EOF),Its detection unit is the receiving unit.。CRC Error
A CRC error refers to**an inconsistency between the CRC check value calculated by the receiving unit based on the received data and the actual CRC sequence received in the frame,**which is detected as an error.
CRC check is a key mechanism in the CAN protocol for verifying data integrity; if the check fails, it indicates that the data may have been corrupted or lost during transmission.
CRC Errors usually occur in the CRC Within the segment,Its detection unit is the receiving unit。Format error
A format error refers toAn error triggered when the receiving unit detects a format contrary to the fixed-format bit field while parsing a frame. For example, illegal values in the CRC delimiter, ACK delimiter, or EOF can cause a format error.
This error usually indicates that the frame structure does not comply with the CAN protocol specification.
Format errors can occur in the CRC delimiter、ACK delimiter、EOF segment,as well as in the error delimiter and overload delimiter,Its detection unit is the receiving unit。ACK error
An ACK error refers toError triggered when the transmitting unit detects a recessive level in the ACK slot。
In the CAN protocol,After the transmitting unit completes sending a data frame or remote frame, it waits for an acknowledgment signal (dominant level) from other nodes in the ACK slot。
If the transmitting unit does not detect a dominant level, it considers that no acknowledgment signal was received, thereby triggering an ACK error.
ACK The error mainly occurs in the ACK ACK slot segment,Its detection unit is the transmitting unit。CAN bus protocol and standard specifications
In modern communication systems, the ISO seven-layer network model is a classic framework for describing and standardizing network communication processes. It divides network communication into seven layers, from the underlying physical signal transmission to the high-level application services, each with specific functions and roles.
Although the design of the CAN protocol does not fully adhere to the ISO seven-layer network model, its functions can be mapped to some layers of the model.
The CAN protocol mainly focuses on thephysical layer、data link layerandtransport layersome of the functions.
ISO Seven-Layer Network Model
Physical Layer
The Physical Layer is responsible for the transmission of physical signals between devices, defining the electrical signals, hardware specifications, and communication media required for communication. It covers communication modes (e.g., simplex, half-duplex, full-duplex), signal levels (e.g., high and low levels representing logic 0 and 1), hardware specifications (e.g., cables, connectors, transceivers), and bit timing conditions (e.g., bit synchronization, sampling points), thereby ensuring reliable data transmission over the physical medium.Data Link Layer
The Data Link Layer organizes the bit sequence received from the Physical Layer into meaningful data frames and provides error detection and control functions. Its specific items include the format of data frames (e.g., frame start, identifier, data field, CRC check), access control methods (e.g., CSMA/CD, CSMA/CA), and error detection and correction mechanisms (e.g., CRC check, ACK response), to ensure the accuracy and integrity of data transmission over the link.Network Layer
The Network Layer is responsible for routing and relaying data packets, ensuring that data can be efficiently transmitted from the source device to the destination device. It achieves cross-network data transmission through functions such as routing (e.g., static routing, dynamic routing), address management (e.g., IP address allocation), and packet segmentation and reassembly, providing support for communication in complex network environments.Transport Layer
The Transport Layer ensures the reliability of data transmission, controlling data sequencing, error recovery, and flow control. It guarantees the consistency, integrity, and efficiency of data during end-to-end transmission through mechanisms such as data transmission sequence control (e.g., sequence numbers, acknowledgment mechanisms), error recovery (e.g., retransmission mechanisms), and flow control (e.g., sliding window protocol).Session Layer
The Session Layer manages the establishment, maintenance, and termination of communication sessions, ensuring that data can be correctly transmitted during the session. It coordinates interactions between applications through functions such as session establishment and termination (e.g., handshake protocols), session synchronization (e.g., checkpoint mechanisms), and session recovery (e.g., resumable transfers), improving the stability and efficiency of communication.Presentation Layer
The Presentation Layer is responsible for converting data representation formats, ensuring data compatibility between different systems. It enables seamless exchange and processing of data across different platforms and applications through functions such as data format conversion (e.g., text encoding, image formats), data encryption and decryption, and data compression and decompression.Application Layer
The application layer provides network service interfaces for applications, implementing specific application functions. It directly serves end users through application protocols (such as HTTP, FTP, SMTP), user interfaces (such as browsers, email clients), and data services (such as file transfer, email), meeting diverse network application needs.
CAN protocol physical layer and data link layer
The CAN protocol mainly focuses on the physical layer and data link layer
- Physical layer in the CAN protocol
The physical layer is responsible for defining the actual transmission method of signals, using NRZ (Non-Return-to-Zero) encoding and inserting stuffing bits after every 6 bits.
It also specifies bit timing and the number of samples, which users can choose according to their needs.
Synchronization is achieved through the synchronization segment (SS) and has resynchronization capability. However, specific details such as signal levels, communication speed, sampling points, electrical characteristics of drivers and buses, and connector types are not defined in the protocol and need to be determined by the user based on system requirements.
- Data link layer in the CAN protocol
- **MAC sublayer (Medium Access Control sublayer)**It is responsible for organizing data into frames, including data frames, remote frames, error frames, and overload frames. It also handles arbitration during data conflicts, deciding which message continues based on priority, and responds with ACK (acknowledgment) and NACK (negative acknowledgment). Additionally, the MAC sublayer detects and reports CRC errors, stuffing bit errors, bit errors, ACK errors, and format errors, while also having fault confinement capability to automatically distinguish between temporary and persistent errors and isolate faulty nodes.
- **LLC sublayer (Logical Link Control sublayer)**It is responsible for message reception selection, supporting point-to-point connections, broadcasting, and multicasting. It also provides error recovery functions, controlling retransmission when errors are detected to ensure reliable data transmission.

After ISO standardization, the CAN protocol is divided into two standards: ISO11898 and ISO11519-2.
These two standards have the same definition at the data link layer but differ at the physical layer:
- ISO11898 is a CAN high-speed communication standard with a communication speed of 125kbps-1Mbps
- ISO11519-2 is the CAN low-speed communication standard with a communication speed below 125kbps.


Enable CAN
Device tree
1 | can0: can@fe570000 { |
Although there are 3 CAN device nodes here, on the Xunwei baseboard, due to pin multiplexing issues, there is only one CAN interface. The corresponding schematic section is as follows:

It can be seen that CAN1 is used on the development board, while in therk3568.dtsidevice tree, the status of the can1 node is set to disabled, indicating it is not enabled, so there must be an addition to this node in another device tree:
1 | //CAN interface |
In addition to enabling the device tree, the corresponding driver must also be enabled in the kernel configuration file. The specific path is as follows:
1 | > Networking support |
Porting and Usage of CAN Tools
iproute2andcan-utilsare two indispensable tools. They provide basic management and advanced operation functions for the CAN interface respectively, helping us easily configure, test, and debug the CAN bus.
Porting iproute2 Tools
iproute2 is a toolset for network management, including commands such as ip, ss, and tc. The corresponding source code archive can be downloaded from the official website.
Compilation:
1 | ./configure |
After compilation, the corresponding executable file will be generated in the ip directory. Copy this file to the development board.
Porting can-utils Tools
canutils is a commonly used CAN communication test toolkit, containing 5 independent programs: canconfig, candump, canecho, cansend, and cansequence. The introduction of each tool is as follows:
| Tool Name | Function Description | Main Configuration Items / Additional Features / Usage |
|---|---|---|
| canconfig | Used to configure parameters of the CAN bus interface. | Bitrate Working mode (Mode), such as Loopback mode or Normal mode. |
| candump | Receive data from the CAN bus interface and print it to standard output in hexadecimal format. | The received data can be saved to a specified file. |
| canecho | Resend all data received from the CAN bus interface back to the CAN bus interface. | Used to test the loopback function of the CAN bus. |
| cansend | Send specified data to the specified CAN bus interface. | Data is sent in CAN frame format, including frame ID and frame data. |
| cansequence | Automatically send an incrementing number sequence to the specified CAN bus interface; supports receive mode to verify whether the received incrementing numbers are correct. | Used to test the data transmission integrity and stability of the CAN bus. |
Since canutils depends on the libsocketcan library, libsocketcan must be compiled first, followed by canutils. The source code link for libsocketcan is:
Compile:
1 | $ export ARCH=arm64 |
The canutils source code download address is:
After decompression, enter the corresponding directory and modify theconfig/autoconf/config.subfile by adding the following content to support aarch64. The modified file is as follows:
1 | | aarch64 | aarch64_be \ |
Then modify the configure configuration file, changing the compiler on line 2604 to aarch64-linux-gnu-gcc. The modification is completed as shown below:
1 | at_ct_CC=aarch64-linux-gnu-gcc |
Compile:
1 | $ export ARCH=arm64 |
Using CAN Tools
Set the Baud Rate of the CAN Interface
The baud rate of the CAN interface can be set using the ip command. For example, the following command sets the baud rate of the CAN0 interface to 250 k:
1 | ip link set can0 type can bitrate 250000 |
Starting and Stopping the CAN Interface
After configuring the baud rate of the CAN interface, you need to start the CAN interface to use it.
- Method 1: Using the ifconfig Command
ifconfig is a traditional network interface configuration tool. You can start the CAN interface with the following command:
1 | ifconfig can0 up |
Stop the CAN interface:
1 | ifconfig can0 down |
- Method 2: Using the ip Command
Start the CAN Interface
1 | ip link set can0 up |
Stop the CAN Interface
1 | ip link set can0 down |
Check the CAN Interface Status
After starting the CAN interface, you can use the ifconfig command and the ip command to check its status.
- Check using ifconfig
1 | ifconfig can0 |
- Check using the ip command
1 | ip -details link show can0 |
Test communication using CAN tools
Receive data using candump
candump is used to receive data from a CAN bus interface and print it to standard output in hexadecimal format.
Command format:candump <接口> [选项]
1 | candump can0 -L & |
Set filter rules
Basic filter formulas are divided into two types:
<can id>:<can mask>Match specific CAN frames- Indicates that when the received CAN ID meets the condition
<received can id> & mask == can id & maskit matches. - The mask determines which bits need to participate in the match; only the parts where the corresponding bit is 1 will be checked
- The can id is the target ID expected to match. This rule is typically used to filter frames that meet a specific ID and format, such as only receiving certain standard frames or extended frames.
- Indicates that when the received CAN ID meets the condition
<can id>~<can mask>Exclude specific CAN frames, opposite to<can id>:<can mask>which ignores those that meet
frames that meet the condition, while receiving all other frames.- Indicates that when the received CAN ID meets the condition
<received can id> & mask != can id & maskit matches.
- Indicates that when the received CAN ID meets the condition
The CAN ID length of a standard frame is 11 bits, ranging from 0x000 to 0x7FF. In the filter rule, the upper 18 bits of the mask are usually set to 0, indicating that the
extended frame part is not concerned;The CAN ID length of an extended frame is 29 bits, ranging from 0x00000000 to 0x1FFFFFFF. In its filter rule, the lower 11 bits of the mask can be flexibly set to 0 or 1 to decide whether to also match standard frames
Example
Match a specific extended frame
1 | candump can0,12345678:1FFFFFFF |
- Meaning: Only receive extended frames, and the CAN ID exactly matches 0x12345678.
- Analysis:
- can id = 0x12345678。
- mask = 0x1FFFFFFF (matches all 29 bits, and requires it to be an extended frame)
Match a specific standard frame
1 | candump can0,123:C00007FF |
- Meaning: Only receive standard frames, and the CAN ID exactly matches 0x123.
- Analysis:
- can id = 0x123。
- mask = 0xC00007FF: The upper 18 bits are 0xC0000 (ignoring the extended frame part), and the lower 11 bits are 0x7FF (exactly matching the standard frame ID).
Match standard frames and remote frames
1 | candump can0,123:800007FF |
- Meaning: Only receive standard frames or remote frames, with CAN ID exactly matching 0x123.
- Analysis:
- can id = 0x123
- mask = 0x800007FF: The high 18 bits are 0x80000 (allowing remote frames), and the low 11 bits are 0x7FF (exact match for standard frame ID).
Exclude specific extended frames
1 | candump can0,12345678~1FFFFFFF |
- Meaning: Exclude extended frames, with CAN ID exactly matching 0x12345678.
- Analysis:
- can id = 0x12345678。
- mask = 0x1FFFFFFF (matches all 29 bits, and requires it to be an extended frame). Use ~ to indicate exclusion matching
Multiple matching rules
If you want to apply multiple matching rules, simply append them with commas. For example, only receive standard frames with CAN IDs exactly matching 0x123 and 0x456
1 | candump can0,123:C00007FF,456:C00007FF |
Use cansend to send data
cansend is used to send different frames to the CAN bus interface. Examples of sending different frames are as follows
- Send standard data frame
- Command format:
cansend <接口> <帧 ID>#<数据><接口>: CAN interface name (e.g., can0).
<帧 ID>: CAN frame ID (11 bits, hexadecimal).<数据>: CAN frame data (hexadecimal).
- Example: can0 sends a standard data frame with ID 0x123 and data DE AD BE EF.
1 | cansend can0 123#DEADBEE |
- Send Remote Frame
- Command format:
cansend <接口> <帧 ID>#R R: Indicates a remote frame.- Example: Send a standard remote frame to can0 with ID 0x123.
- Command format:
1 | cansend can0 123#R |
- Send Extended Data Frame
- Command format:
cansend <接口> <帧 ID>#<数据> <帧 ID>: CAN frame ID (29 bits, hexadecimal).- Example: Send an extended data frame to can0 with ID 0x00000123 and data 12 34 56 78.
- Command format:
1 | cansend can0 00000123#12345678 |
- Send Extended Remote Frame
- Command format:
cansend <接口> <帧 ID>#R - R: Indicates a remote frame.
- Example: Send an extended remote frame to can0 with ID 0x00000123
- Command format:
1 | cansend can0 00000123#R |
CAN Application Programming
Create a Socket
The socket function is one of the most fundamental functions in network programming, used to create a socket.
A socket is the basic unit of network communication, providing a mechanism for inter-process communication. Through sockets, applications can send and receive data packets, thereby enabling network communication.
socket()Used to create a socket, it is thefirst stepof network communication. The socket descriptor returned upon successful creation is used for subsequentbind、listen、connect、send、recvand other operations.
Header File
1 |
Function Prototype
1 | int socket(int domain, int type, int protocol); |
Return Value
- Success: Returns a non-negative integer representing the socket file descriptor (socket fd)
- Failure: Return
-1, and seterrno
Parameter Description
domainProtocol Family (Address Family)
Specifies the protocol family used for communication, determiningthe address format and communication scope. Common values:
| Protocol Family | Description |
|---|---|
| AF_UNIX | Used for local communication (inter-process communication on the same machine), also known as AF_LOCAL. |
| AF_INET | IPv4 Internet protocol family, used for IPv4-based network communication. |
| AF_INET6 | IPv6 Internet protocol family, used for IPv6-based network communication. |
| AF_IPX | Novell’s IPX/SPX protocol family, used for Novell networks. |
| AF_NETLINK | Communication between kernel and user space, used for receiving kernel event notifications. |
| AF_X25 | ITU-T X.25/ISO-8208 protocol family, used for packet-switched networks. |
| AF_AX25 | Amateur radio AX.25 protocol family, used for amateur radio communication. |
| AF_ATMPVC | Used to access raw ATM PVCs (Permanent Virtual Circuits), ATM is a high-speed network communication technology. |
| AF_APPLETALK | AppleTalk protocol family, used to connect Mac computers and other devices. |
| AF_PACKET | Low-level packet interface, allowing applications to directly access network devices to send and receive raw packets. |
| AF_ALG | Interface to the kernel cryptographic API, allowing applications to use encryption services provided by the kernel. |
| PF_CAN | Protocol family for CAN (Controller Area Network) communication. |
typeSocket type
Specifies the data transmission method. Common values:
| Type | Description |
|---|---|
| SOCK_STREAM | Stream socket, providing connection-oriented, reliable, bidirectional byte stream communication (e.g., TCP). |
| SOCK_DGRAM | Datagram socket, providing connectionless, unreliable, fixed-length datagram communication (e.g., UDP). |
| SOCK_RAW | Raw socket, allowing direct access to underlying protocols (e.g., IP, ICMP). |
| SOCK_SEQPACKET | Provides connection-oriented, reliable, fixed-length datagram communication. |
protocolProtocol type
Specify the specific protocol to use, usually set to0, which is automatically selected by the system based ondomainandtype. Common values:
| Protocol | Description | Corresponding domain and type |
|---|---|---|
| IPPROTO_TCP | TCP protocol, used for SOCK_STREAM type | AF_INET or AF_INET6, SOCK_STREAM |
| IPPROTO_UDP | UDP protocol, used for SOCK_DGRAM type | AF_INET or AF_INET6, SOCK_DGRAM |
| IPPROTO_RAW | Raw protocol, used for SOCK_RAW type | AF_INET or AF_INET6, SOCK_RAW |
| CAN_RAW | Raw CAN protocol, used for CAN bus communication | PF_CAN, SOCK_RAW |
| CAN_BCM | Broadcast management protocol, used for more complex CAN communication | PF_CAN, SOCK_DGRAM |
Common combination examples
1 | // TCP IPv4 socket |
Examples
1 |
|
Bind socket
Function introduction
bind()Used to bind a socket toa specified local address。
In network programming, it is commonly used to bindIP addresses and port numbers; inCAN communication,bind()its main function is to bind a socket to aspecified CAN interface(such ascan0), thereby determining which CAN controller transmits and receives data.
bind()It is abasic configuration stepin CAN socket communication and must be called before data transmission and reception.
Header file
1 |
Function prototype
1 | int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); |
Return value
- Success: Returns
0 - Failure: Returns
-1, and setserrno
Parameter Description
sockfdSocket Descriptor
Created bysocket()The socket file descriptor created by the function, indicating the socket to be bound.
addrAddress Structure Pointer: A pointer to the structure containing the address information to bind. The actual structure used varies in different communication scenarios:IPv4:
struct sockaddr_inIPv6:
struct sockaddr_in6CAN:
struct sockaddr_can
When callingbind(), it needs to be cast tostruct sockaddr *type.
addrlenAddress Structure Length: Indicates the size of theaddraddress structure pointed to, typically usingsizeof()Calculate:IPv4:
sizeof(struct sockaddr_in)IPv6:
sizeof(struct sockaddr_in6)CAN:
sizeof(struct sockaddr_can)
Bind Example in CAN Communication
1 | struct sockaddr_can addr; |
Description:
can_family: Must be set toAF_CANcan_ifindex: Specify the CAN interface index (e.g.,can0)- After binding, the socket will only communicate on the specified CAN interface
Example
1 |
|
The above code uses the ioctl system call via theSIOCGIFINDEXmacro to obtain the CAN interface index number. In addition to theSIOCGIFINDEXmacro, there are other macros with different functions in network devices, as shown in the table below:
| Command | Function Description |
|---|---|
| SIOCGIFADDR | Get the IP address of the network interface |
| SIOCSIFADDR | Set the IP address of the network interface |
| SIOCGIFNETMASK | Get the subnet mask of the network interface |
| SIOCSIFNETMASK | Set the subnet mask of the network interface |
| SIOCGIFBRDADDR | Get the broadcast address of the network interface |
| SIOCSIFBRDADDR | Set the broadcast address of the network interface |
| SIOCGIFDSTADDR | Get the destination address of the network interface (peer address of a point-to-point interface) |
| SIOCSIFDSTADDR | Set the destination address of the network interface |
| SIOCGIFHWADDR | Get the hardware address of the network interface (e.g., MAC address) |
| SIOCSIFHWADDR | Set the hardware address of the network interface (usually uncommon as hardware addresses are mostly fixed) |
| SIOCGIFINDEX | Get the index number of the network interface (system-assigned unique identifier) |
| SIOCSIFMTU | Set the Maximum Transmission Unit (MTU) of the network interface |
| SIOCGIFFLAGS | Get the flags of the network interface (e.g., whether it is enabled, whether it is a broadcast interface, etc.) |
| SIOCSIFFLAGS | Set the flags of the network interface |
Send/Receive data
CAN data cannot be sent directly; a packetization operation is required before sending
struct can_frame
CAN data frames are typically represented using thestruct can_framestructure. This structure is defined in the<linux/can.h>header file, used to encapsulate the CAN data to be sent. The content of this structure is as follows:
1 | struct can_frame { |
can_id: can_id is a 32-bit unsigned integer field used to represent the CAN identifier (ID).- For standard frames, the lower 11 bits of can_id represent the identifier;
- for extended frames, the lower 29 bits represent the identifier.
- Bit 30 is used to identify whether it is a remote frame (via the CAN_RTR_FLAG flag).
- The most significant bit (bit 31) is used to identify whether it is an extended frame (via the CAN_EFF_FLAG flag),
can_dlc: can_dlc is an 8-bit unsigned integer field that indicates the length of the data field in a CAN data frame. Its value ranges from 0 to 8, corresponding to the maximum supported data length of 8 bytes in the classic CAN protocol.- For CAN FD (Flexible Data-rate CAN), can_dlc can support larger data lengths (e.g., 64 bytes). This field determines the actual number of data bytes sent or received, and unused portions are ignored.
data: data is an 8-byte array field used to store the actual data content to be sent or received.- The actual length of the data is determined by the can_dlc field, with a maximum of 8 bytes (classic CAN) or more (CAN FD).
- Unused portions of the array are not transmitted, so only valid bytes need to be filled when encapsulating data.
Example:
1 | struct can_frame frame[3]; // CAN frame array |
Example
Send Data
1 |
|
Receive Data
1 |
|
Filter rule configuration
Filter rule configuration in CAN applications requires the use ofsetsockoptfunction,setsockoptThe main function of is to configure the filter rules or other specific options of the CAN socket.
By setting these options, users can control the behavior of the socket, such as filtering specific CAN data frames or adjusting the communication mode. This is one of the important steps to achieve efficient data processing in CAN communication.
setsockopt()
setsockopt()is used to set variousprotocol-related options. InCAN Socket communication, it is mainly used for:
- SettingsCAN frame filtering rules
- Control whether to receive error frames
- Configure behaviors such as local loopback
One of the most commonly used and core configurations of CAN communication is CAN_RAW_FILTER, used to specify which CAN frames the socketreceives.
Header file
1 |
Function prototype
1 | int setsockopt(int sockfd, |
Return value
- Success: returns
0 - Failure: returns
-1, and setserrno
Parameter Description
sockfdSocket descriptor, created bysocket()The CAN socket file descriptor, representing the socket to be configured.levelOption level, specifying the protocol layer to which the option belongs. In CAN communication, it is fixed to useSOL_CAN_RAWindicating that the setting is foroptions related to the raw CAN protocol (CAN_RAW)。optnameSpecific option name, specifying the CAN socket option to be set. Common options include:CAN_RAW_FILTER, setting the CAN data frame’sfilter rules(focus of this chapter)CAN_RAW_ERR_FILTER, setting whether to receive error framesCAN_RAW_LOOPBACK, setting whether to enable local loopback mode
optvalOption value pointer, pointing to the buffer of option data.- For
CAN_RAW_FILTER, the type isstruct can_filter *- Can bea single filter rule
- or can bean array of filter rules
- For
optlenOption value length: indicatesoptvalbuffer size (in bytes):Single filter rule:
sizeof(struct can_filter)Multiple filter rules:
sizeof(struct can_filter) * 规则数量
Example:
Only receive standard frames with ID 0x123
1 | struct can_filter filter; |
Set multiple filter rules
1 | struct can_filter filters[2] = { |
Receive all CAN frames (disable filtering)
1 | setsockopt(fd, SOL_CAN_RAW, |
struct can_filter
CAN filter rule structure
1 | struct can_filter { |
can_idIndicates the expected CAN ID to match
Can include:
- Standard frame ID (11 bits)
- Extended frame ID (29 bits)
- Flag bits (e.g.,
CAN_EFF_FLAG、CAN_RTR_FLAG)
can_maskUsed to specifywhich bits need to participate in matching
A certain bit is:
1: This bit must match0: This bit is ignored
Common CAN mask macros
| Mask value | Meaning | Example code and usage |
|---|---|---|
| CAN_SFF_MASK | Match the lower 11 bits (0x7FF) of standard frames, ignore extended frame part | can_id=0x123, can_mask=CAN_SFF_MASKOnly receive standard frames with ID exactly matching 0x123 |
| CAN_EFF_MASK | Match all 29 bits of extended frames (0x1FFFFFFF) | can_id=0x12345678, can_mask=CAN_EFF_MASKOnly receive extended frames with ID exactly matching 0x12345678 |
| CAN_EFF_FLAG | Match extended frame flag (bit 30) | can_mask=CAN_EFF_FLAGDistinguish standard/extended frames, only focus on whether it is an extended frame |
| CAN_RTR_FLAG | Match remote frame flag (bit 31) | can_mask=CAN_RTR_FLAGDistinguish data/remote frames, only focus on whether it is a remote frame |
| CAN_SFF_MASK | CAN_EFF_FLAG | Match lower 11 bits of standard frames, distinguish whether it is an extended frame | `can_id=0x123, can_mask=CAN_SFF_MASK |
| CAN_EFF_MASK | CAN_RTR_FLAG | Match 29 bits of extended frames, distinguish whether it is a remote frame | `can_id=0x12345678, can_mask=CAN_EFF_MASK |
| CAN_SFF_MASK | CAN_RTR_FLAG | Match lower 11 bits of standard frames, distinguish whether it is a remote frame | `can_id=0x123, can_mask=CAN_SFF_MASK |
| CAN_SFF_MASK | CAN_EFF_FLAG | CAN_RTR_FLAG | Match lower 11 bits of standard frames, distinguish whether it is an extended frame and remote frame | `can_id=0x123, can_mask=CAN_SFF_MASK |
| 0xFFFFFFFF | Match all 32 bits (including standard frame, extended frame, and remote frame flags) | can_id=0x123, can_mask=0xFFFFFFFFExact match of a specific complete CAN ID and frame type |
| 0x0 | Ignore all bits, match all frames (no filter rules) | can_mask=0x0Receive all frames, no filtering |
Example
1 |
|

