STM32 Advanced Learning (6)-Detailed Explanation of CAN Communication Protocol


1. Background of CAN communication

The background of CAN communication dates back to the early 1980s, when car manufacturers faced a common challenge: how to efficiently transmit and share large amounts of sensor data and control information . Traditional cabling methods are complex and error-prone, and cannot meet the growing demands for data transmission.

In order to solve this problem, the German car manufacturer Mercedes-Benz and the German telecommunications company Bosch cooperated to develop a new communication protocol, namely CAN (Controller Area Network) controller area network communication. CAN communication was originally designed to meet the data transmission needs of automotive electronic systems, but has subsequently been widely used in other fields.

The design goals of CAN communication are to achieve high reliability, real-time performance and flexibility. It adopts a differential signal transmission method, has strong anti-interference ability, and can perform reliable data transmission over a long distance. The CAN bus supports concurrent transmission of multiple frames, has fast data transmission speed, and can meet the requirements of real-time control systems. In addition, the CAN bus supports the connection of multiple hosts and multiple nodes, making it easy to expand and change the system structure.

The successful application of CAN communication has been widely recognized in the automotive field and has become the core technology in modern automotive electronic systems. With the development of technology, CAN communication has gradually evolved into higher-speed versions, such as CAN-FD (CAN with Flexible Data-Rate), to meet higher bandwidth data transmission needs. CAN communication is also used in other fields, such as industrial automation, aerospace, etc., becoming a highly reliable and real-time communication method.
insert image description here

2. Basic introduction to CAN communication

CAN communication is a communication protocol based on CAN (Controller Area Network) bus. CAN bus is a high-speed, reliable serial bus mainly used for data transmission in real-time control systems.

Features of CAN communication include:

High reliability: The CAN bus uses differential signal transmission, has strong anti-interference ability, and can perform reliable data transmission over long distances.
Real-time: CAN bus supports concurrent transmission of multiple frames, has fast data transmission speed, and can meet the requirements of real-time control systems.
Flexibility: CAN bus supports the connection of multiple hosts and nodes, and can easily expand and change the system structure.
Low cost: The hardware cost of the CAN bus is relatively low and easy to implement and maintain.
In CAN communication, each node has a unique identifier that is used to distinguish different nodes. Data communication is carried out between nodes through the CAN bus, and data frames are sent and received. Data frames are divided into two types: data frames and remote frames. Data frames are used to transmit actual data, and remote frames are used to request data. Communication between nodes is based on priority, and nodes with higher priority have higher sending priority.

3. Intuitive hardware connection diagram of CAN communication

insert image description here
Looking at this picture, it is mainly divided into three parts: CPU controller part, vehicle sensor monitoring part, and data bus part. Next, we will introduce them one by one:

(1) CPU controller part

Normally, the central processing unit (CPU) does not directly integrate the CAN (Controller Area Network) transceiver. The CAN transceiver is a hardware device specifically used for CAN bus communication. It is responsible for converting the CAN data generated by the CPU into electrical signals on the CAN bus, and converting the electrical signals on the CAN bus into a data format that the CPU can process.

In a typical automotive electronics system, the CAN transceiver is usually connected to the CPU as an external component. The CPU communicates with the CAN transceiver through the bus interface (such as SPI, UART, etc.), transmits the CAN data to be sent to the CAN transceiver, and receives the data on the CAN bus from the CAN transceiver.
Although the CPU itself does not integrate a CAN transceiver, some advanced processors of modern automotive electronic systems (such as automotive-grade MCUs or SoCs) may integrate a CAN controller that can communicate with an external CAN transceiver . Such an integrated design can simplify system layout and connections and improve system integration.

(2) Vehicle-mounted sensor part

As the name suggests, it is deployed in various locations in the car to detect various data and feed it back to the CPU. Take this picture for example:

ABS: ABS is the anti-lock braking system (Anti-lock Braking System) in cars. It is a safety system that dynamically adjusts the braking force during braking to prevent wheel locking and provide vehicle stability and controllability during braking.

SAS: SAS is the steering angle sensor (Steering Angle Sensor) in cars. It is a sensor device used to detect the angle and speed at which the driver turns the steering wheel in order to provide it to the vehicle's stability control system and driver assistance systems.

ETM: ETM is the electronic throttle module (Electronic Throttle Module) in the car. It is an electronic device that controls the opening and closing of the engine throttle. It is used to adjust the engine's air intake and the response of the accelerator pedal to provide better power performance and fuel economy.

ECM: ECM is the engine control module (Engine Control Module) in the car. It is an electronic control unit that monitors and controls engine operation. The ECM receives data from various sensors and controls parameters such as ignition timing and fuel injection amount according to preset algorithms to ensure normal operation and optimal performance of the engine.

DDM: DDM is the abbreviation of Distributed Drive Module. It is a distributed electronic control system that connects the drives and sensors in the vehicle to the control unit. The DDM system distributes electronic control units in various locations of the vehicle and performs data exchange and control through network connections. Each DDM unit is responsible for controlling a specific functional module, such as the electric drive system, braking system or chassis control system.

PDM: PDM is the abbreviation of Power Distribution Module. It is a power management system used to control the transmission and distribution of electrical power in vehicles. The PDM system transmits power from the battery to the vehicle's various electronic devices and systems through a centralized power management module. PDM is responsible for controlling and protecting circuits, while also providing circuit monitoring and diagnostic functions. It can effectively manage the power in the vehicle and ensure the normal operation of various electronic devices and systems.

(3) Communication bus part

Treat each deployed sensor as a node, and all nodes are connected by two lines. The two lines are called CAN_H and CAN_L.
The CAN bus adopts a two-wire system, namely CAN_H (CAN High) and CAN_L (CAN Low). These two wires are connected together through terminating resistors, forming a loop or linear topology, with all nodes connected to this bus.

On the CAN bus, each node sends and receives data through the CAN transceiver. Each node determines whether the data bit is 0 or 1 by identifying the potential difference on the CAN bus . The CAN bus uses differential signaling, that is, the potential difference on the CAN_H and CAN_L lines represents the status of the data bits . When the potential of the CAN_H line is higher than the CAN_L line, it means the data bit is 1; when the potential of the CAN_L line is higher than the CAN_H line, it means the data bit is 0.

There must be 120Ω termination resistors at both ends of the network. Therefore, when designing the circuit board, there must be a 120 ohm resistor. Select whether to use this resistor through a jumper or DIP switch. Why is it 120Ω? Because the characteristic impedance of the cable is 120Ω, in order to simulate an infinite transmission line.

4. Detailed analysis of the level signal of the loop double line

insert image description here
node is each node, CAN_H, CAN_L and the 120 ohm resistor form a loop structure.

1.What is a differential signal?

The bus levels on CANBUS are called recessive levels and dominant levels:

nature logic CAN_H CAN_L The voltage difference between the two lines
implicit Logic 1 2.5V 2.5V 0V
explicit logic 0 3.5V 1.5V 2V

If the CAN controller sends logic 1, the CAN transceiver makes both CAN_H and CAN_L 2.5V. At this time, the voltage difference on the two lines is 0V. It is called the recessive level on the bus.
If the CAN controller sends logic 0, the CAN transceiver makes CAN_H 3.5V and CAN_L 1.5V. At this time, the voltage difference on the two lines is 2V. It is called the dominant level on the bus.

In the same way, if one of my nodes wants to send data 1, make both CAN_H and CAN_L output 2.5V voltage so that the differential voltage is 0. Note that the levels of 3.5V and 2.5V here are not necessarily certain, and different international standards have different regulations.
When multiple nodes start sending at the same time, bus arbitration will be involved (that is, who can continue to send). This involves a priority issue.

2. Priority of arbitration

The priority of arbitration of each node on the CAN bus is determined by the identifier (Identifier) . Nodes sending information on the CAN bus will include a priority field in the identifier, which determines the node's sending priority.

On the CAN bus, an identifier consists of 11 or 29 bits and contains a priority field. The smaller the value of the priority field, the higher the priority of the node. When multiple nodes try to send information at the same time, the lower priority node will give up the bus to allow the higher priority node to send first.

The CAN bus uses a non-destructive arbitration mechanism, that is, when multiple nodes try to send information at the same time, only one node can successfully send it. Other nodes will detect that the differential signal on the bus is inconsistent with the signal they sent, and thus realize that something has happened. A conflict occurs and transmission is stopped.

During the arbitration process, nodes on the CAN bus are compared based on the priority field of the identifier. The node will compare the priority field of the identifier bit by bit, and the higher bit comparison result will determine the priority first. If the comparison result is consistent, the next bit will continue to be compared until the final priority result is obtained.

3.CAN transceiver

The CAN transceiver is an interface circuit used to connect the CAN controller and the CAN bus. It is responsible for converting the differential signal generated by the CAN controller into an electrical signal on the CAN bus, and converting the electrical signal on the CAN bus into a CAN controller. Identify differential signals. (two-way effect)

CAN transceivers usually consist of a transmitting part and a receiving part.

The sending part is responsible for converting the differential signals output by the CAN controller into electrical signals on the CAN bus. It will drive the CAN_H and CAN_L lines on the CAN bus based on the data and control signals sent by the CAN controller to generate a corresponding voltage difference.

The receiving part is responsible for converting the electrical signals on the CAN bus into differential signals that can be recognized by the CAN controller. It measures the voltage difference between the CAN_H and CAN_L lines and converts it into a differential signal that the CAN controller can process for interpretation by the CAN controller.

CAN transceivers are also typically anti-interference capable and can withstand noise and interference from the external environment. It can ensure the signal quality and reliability on the CAN bus through filtering and voltage adjustment.

4. Advantages of differential signals

Compared with single signal line transmission, using differential signal transmission has the following advantages:

Strong anti-interference ability, when there is noise interference from the outside world, it will be coupled to two signal lines almost at the same time, and the receiving end only cares about the difference between the two signals, so the external common mode noise can be completely offset.

To give an example, the normal single-line assumes that logic 1 is 3.3V, and logic 0 is assumed to be 0V, but if there is noise, 3.3V is changed to 0V (extreme), and 0V is changed to -3.3V, and the logic is wrong at this time , but Can high/Can low generally acts on two lines, so although both are affected by noise, the difference remains the same.

• It can effectively suppress its external electromagnetic interference. In the same way, because the polarities of the two signals are opposite, the electromagnetic fields radiated from them can cancel each other out. The tighter the coupling, the less electromagnetic energy will be released to the outside world.

To give an example, suppose one is 10V and the other is -10V, a single heel will cause electromagnetic interference to the outside, but CAN can twist the wires together, just like weaving twists, which can cancel each other's electronic interference

• Accurate timing positioning, because the switching change of the differential signal is located at the intersection of the two signals, unlike ordinary single-ended signals that rely on high and low threshold voltages to judge, so it is less affected by the process and temperature, and can reduce timing errors. It is also more suitable for circuits with low amplitude signals.

Due to these advantages of differential signal lines, differential signal transmission is used in the physical layers of USB protocol, 485 protocol, Ethernet protocol and CAN protocol.

5. Frame structure used in CAN communication

Each node can actively send frames. (Frame is the unit of sending or receiving specified by CAN protocol). Frames are made up of segments, which are made up of binary bits.

serial number name Frame usage
1 Data Frame A frame used by the sending unit to transfer data to the receiving unit.
2 remote control frame A frame used by a receiving unit to request data from a sending unit with the same ID.
3 error frame Frame used to notify other units of an error when an error is detected. (Automatically done by hardware)
4 overload frame When a node is busy processing received information, it can notify other nodes to suspend sending new messages. (Automatically done by hardware)
5 interval frame Frame used to separate data frames and remote control frames from previous frames (automatically done by hardware)

There are many types of frames, among which error frames, overload frames, and frame intervals are all completed by hardware and cannot be controlled by software . For ordinary users, they only need to master the data frame and remote control frame. Data frames and remote control frames have standard formats and extended formats . The standard format has an 11-bit identifier, and the extended format has a 29-bit identifier.

1. Data frame

This thing has been exposed in the serial port, IIC, and SPI. It is a data segment with data.
Recall:
the frame structure of the serial port, including start bit-data segment-check bit-stop bit.
IIC frame structure: includes a start bit, 7-bit or 10-bit device address, read/write bits, data bytes and a stop bit.
SPI frame structure: consists of a start bit, one or more data bytes and a stop bit.
The CAN data frame structure is as follows:
insert image description here

Take the standard format as an example

(1) The start bit of the frame
The start bit of the frame is a low-level bit, called "SOF" (Start of Frame). The start bit is used to identify the beginning of the frame, and its presence helps the receiver synchronize the clock of the data bits.
(2) Arbitration Segment
Complex explanation:
The Arbitration Segment is an important part of the CAN frame. The arbitration segment is used to determine that nodes with higher priority can successfully send their data frames, while nodes with lower priority will actively give up sending.
The length of the arbitration segment depends on the bit timing parameters of the CAN bus and is determined by the configuration of the CAN controller and communication system. Generally, the length of the arbitration segment is 1 to 8 time periods (Time Quanta).
In the arbitration segment, all nodes on the CAN bus send their identifiers (Identifier) ​​and remote frame flags (RTR) in parallel. The identifier is a unique identification code used to distinguish data frames sent by different nodes.
In the arbitration segment, each node sends its identifier and RTR as bits on the CAN bus. All nodes on the CAN bus simultaneously detect the bit values ​​on the bus and determine whether to continue sending data based on the comparison results of the identifiers.
In the arbitration section, identifier comparison is based on the principle of "Non-Destructive Bit Timing". That is, each node is receiving bits as it sends them, and compares them with the bits it sent. If the received bits are inconsistent with the sent bits, the node will realize that a higher priority node is sending data and actively give up sending.
Through the mechanism of the arbitration segment, the CAN bus can realize conflict detection and conflict resolution among multiple nodes to ensure reliable data transmission and correctness of priority. The arbitration segment is a key link in CAN bus communication, providing an effective scheduling and control mechanism for multi-node communication.

My understanding:
data is equivalent to a letter, and the arbitration section is equivalent to the ID number of the envelope of the letter. There are many sensors in the car that send data to the CPU. Different types of data correspond to letters with different numbers. The different numbers of the arbitration sections are directly related to It determines the different types of data (different nodes), and indirectly determines the priority of sending and receiving data.

(3) Control section
As shown in the figure, the control section has several bits:
reserved bits (r0, r1) must all be sent at dominant level. But the receiver can receive explicit, recessive and any combination of levels

RTR (Remote Transmission Request): RTR is a bit of the CAN frame used to indicate whether the frame sent is a data frame or a remote frame. When the RTR bit is 0, it means that a data frame is sent; when the RTR bit is 1, it means that a remote frame is sent. Data frames contain actual data information, while remote frames are used to request other nodes to send data frames.

IDE (Identifier Extension): IDE is a bit of the CAN frame used to indicate the type of identifier (Identifier). When the IDE bit is 0, it means that the identifier is an 11-bit identifier in the standard format; when the IDE bit is 1, it means that the identifier is a 29-bit identifier in the extended format. The identifier is used to distinguish data frames sent by different nodes.

DLC (Data Length Code): DLC is a field of the CAN frame, which is used to indicate the length of the data in the data frame. The value range of DLC is 0 to 8. The different DLC values ​​represent the number of data bytes contained in the data frame. For example, if the DLC is 2, it means that the data frame contains 2 bytes of data information.

(4) Data segment
It is used to carry actual data information. The data segment contains the valid data in the transmitted or received data frame.

The length of the data segment (Data Length) is specified by the DLC field, and the value range of the DLC field is 0 to 8, indicating the number of data bytes contained in the data segment. For example, if the DLC is 2, it means that the data segment contains 2 bytes of data information.

The specific content of the data segment is determined by the sending node and transmitted in the CAN frame. The receiving node parses and processes the received data based on the data segments in the CAN frame.

In the data segment, each data byte is transmitted as an 8-bit byte, which can be any valid 8-bit data. The content of the data segment can be sensor data, control instructions, status information, etc., depending on the application area and communication requirements.

(5) CRC segment, ACK segment and end frame (not important, hardware completion)
CRC segment: CRC (Cyclic Redundancy Check) segment is part of the CAN frame and is used to verify the integrity of the data. CRC is a check code generated by calculating and generating the data in the data frame, which is used to detect whether errors occur during data transmission. The sending node will calculate the CRC value when sending the data frame and place it in the CRC segment. The receiving node will recalculate the CRC value when receiving the data frame, and compare it with the value in the received CRC segment to determine whether the data is complete and correct. If the CRC values ​​match, it means that the data transmission is correct; if the CRC values ​​do not match, it means that there may be errors in the data, and the receiving node can choose to discard the data or request to resend it.

ACK segment: The ACK (Acknowledgment) segment is a bit in the CAN frame and is used to indicate the reception status of data. In the CAN bus, each node has an ACK bit for sending and receiving. When a sending node sends a data frame, it detects the ACK bit on the CAN bus. If the receiving node receives the data frame correctly and verifies it is correct, it will send an ACK frame with the ACK bit set to 0 as a response. After receiving the ACK frame, the sending node confirms that the data frame has been received correctly and continues to send the next frame. If the receiving node fails to receive the data frame correctly or fails to check, it will not send the ACK frame. The sending node will detect the lack of ACK and may perform error processing or resend the data frame.

To sum it up:

serial number name describe
1 start of frame Indicates the beginning of the frame and generates a dominant level of one bit.
2 arbitration section Indicates the priority of the frame, consisting of an identifier (ID) and a transmission frame type (RTR).
3 Control terminal Represents the number of bytes of data, consisting of 6 bits
4 data segment For the specific content of the data, 0 to 8 bytes of data can be sent.
5 CRC segment Used to verify whether the transmission is correct.
6 ACK segment Indicates confirmation of normal reception.
7 end of frame Indicates the end of this frame.

2. Remote frame (remote frame)

Remote frames are used to request other nodes to send data, rather than transmitting the actual data content. It acts as a request mechanism during communication, allowing one node to send a request to other nodes to obtain specific data.

The format of a remote frame is similar to an ordinary data frame, but the data segment is empty. It contains the following important fields:

Frame ID: The frame ID field of the remote frame is used to specify the target node of the request. The frame ID represents the message identifier to which the data frame or remote frame belongs.

RTR (Remote Transmission Request): The RTR bit is a bit in a remote frame that indicates that the frame is a remote frame. The RTR bit is 1, indicating that the frame is a remote frame, used to request other nodes to send data.

DLC (Data Length Code): The DLC field specifies the length of the data segment in the remote frame. Because remote frames do not contain actual data content, the DLC field is usually set to 0.

When a node sends a remote frame, it sets the frame ID and RTR bits to the specified values ​​and sets the DLC field to 0. After receiving the remote frame, other nodes determine the target of the request based on the frame ID and RTR bits, and prepare corresponding data to respond.

The node that receives the remote frame can prepare a response data frame based on the requested frame ID and other information, and then send it back to the requesting node. This mechanism allows flexible data exchange and communication between nodes.

6. CAN Arbitration Mechanism

The arbitration mechanism of CAN (Controller Area Network) is used to deal with conflicts when multiple nodes send data at the same time, ensuring the reliability and sequence of data transmission. The arbitration mechanism on the CAN bus is based on the "non-destructive bit timing" and "priority" principles.

The following are the main steps of CAN’s arbitration mechanism:

Bit Timing: Each node on the CAN bus has an internal clock that determines when to send data. Before data transmission begins, the sending node monitors the level on the bus until it detects that the bus level changes from high level (logic 1) to low level (logic 0). This point in time is called "bit timing".
Preemption priority: Each node on the CAN bus has a unique identifier (ID) to determine its priority. Nodes with lower IDs have higher priority. When multiple nodes start sending data at the same time, the priority will be judged based on the ID of the node.
Bitwise comparison: When sending data, the sending node will compare the value of each bit one by one. If in a certain bit comparison, the value of the sending node does not match the value on the bus, the sending node will stop sending data and wait for other nodes to continue sending.
Non-destructive bit timing: After a conflict occurs, the sending node stops sending data and waits for the conflict to end. At this time, the node will continue to monitor the level on the bus. Each node on the bus performs non-destructive bit timing based on its own clock until the conflict is over.
Transmission completed: Once other nodes complete the transmission of data, the sending node will restart sending data according to priority. The highest priority node will be able to successfully send its data, and the other nodes will retry sending in the next time window.
insert image description here
In this figure, three nodes send data at the same time, and the lowest bit of node3 in the arbitration segment is dominant low and has a higher priority, so the data of node3 will be sent first.

  1. When the bus is idle, the node that starts sending first gets the right to send. Once it starts sending, it will not be preempted by other nodes.
  2. When multiple nodes start sending at the same time, each sending node starts arbitration from the first position in the arbitration segment. The node that continuously outputs the most dominant levels can continue to send. (Dominant: dominant priority)
  3. When data frames and remote control frames with the same ID compete on the bus, the data frame whose last bit (RTR) of the arbitration segment is a dominant bit has priority and can continue to be sent.
  4. ​When the standard format ID competes with the remote control frame or extended format data frame with the same ID on the bus, the one with the dominant RTR bit in the standard format has priority and can continue to send.

7. STM32 deploys CAN communication

1.CAN controller

The STM32 chip has a bxCAN controller (Basic Extended CAN), which supports CAN protocol 2.0A and 2.0B standards. The CAN controller supports the highest communication rate of 1Mb/s; it can automatically receive and send CAN messages, and supports messages using standard IDs and extended IDs; there are 3 sending mailboxes in the peripheral, and the priority of sending messages It can be controlled by software, and can also record the sending time; it has 2 receiving FIFOs with 3 levels of depth, and can use the filtering function to only receive or not receive messages with certain ID numbers; it can be configured as automatic retransmission; DMA is not supported Send and receive data. The frame diagram is as follows:
insert image description here
STM32 has two sets of CAN controllers, of which CAN1 is the master device. The "storage access controller" in the block diagram is controlled by CAN1. CAN2 cannot directly access the storage area, so CAN1 must be enabled when using CAN2 Peripheral clock. The block diagram mainly includes the CAN control core, sending mailbox, receiving FIFO and acceptance filter.

①What is FIFO?

FIFO (First In, First Out) is a data structure that can be used to store and manage data. It is similar to a queue, and data is processed in first-in, first-out order.

In communications, FIFO is often used to cache data. Here are some reasons for using FIFO:
(1) Data transfer rate mismatch: The sending and receiving devices may have different data transfer rates. FIFO can be used to buffer sent and received data to facilitate temporary storage and adjustment of data in the event of rate mismatch.
(2) Data processing delay: During the communication process, data processing may take a certain amount of time. Using FIFO can cache the received data while processing the data to ensure that the data will not be lost.
(3) Data burstiness: In some cases, data may be transmitted in bursts, that is, a large amount of data is continuously transmitted in a short period of time. FIFO can be used to temporarily store these burst data for subsequent processing one by one.
(4) Data priority: When multiple data arrive at the same time, they may need to be processed according to priority. Using FIFO can sort and process data according to its priority.
(5) Data flow control: When the data flow between the sending and receiving devices is unbalanced, FIFO can be used to achieve data flow control and avoid data loss or overflow.

②What are the sending email address and receiving email address?

In CAN communication, the transmit mailbox (Transmit Mailbox) and the receive mailbox (Receive Mailbox) are buffers in the CAN controller, used to store sent and received CAN frames .

Transmit Mailbox: The transmit mailbox is used to temporarily store the CAN frames to be sent in the CAN controller, waiting to be sent . Usually, the CAN controller will provide multiple sending mailboxes, which can store multiple CAN frames to be sent at the same time . Each sending mailbox has its own identifier, data and control bits used to configure and identify the sent CAN frames. After the CAN frame in the sending mailbox is sent, the sending mailbox can be used to store new CAN frames to be sent.

Receive Mailbox: The receiving mailbox is used to store received CAN frames. CAN controllers usually provide multiple receiving mailboxes for storing different CAN frames . Each receiving mailbox has its own identifier, data and control bits for storing information about received CAN frames. When the CAN controller receives a CAN frame, it stores the frame into an available receive mailbox for the host to process and read.

The number and configuration of sending and receiving mailboxes depends on the model and function of the CAN controller used. Different CAN controllers may provide different numbers and characteristics of sending and receiving mailboxes. The use of these mailboxes can be configured and managed through corresponding registers to control the sending and receiving of CAN frames.

③What is the acceptance filter?

Receive Filters are a mechanism used to filter received CAN frames. In CAN communication, receive filters are used to filter and select interested CAN frames so that only the required data is received.

The reception filter determines which CAN frames to receive by configuring some parameters and ignores other unnecessary CAN frames. These parameters can include the following:

Identifier: The reception filter can be configured with one or more identifiers to identify the CAN frames that need to be received. Only CAN frames matching these identifiers will be received and processed.

Mask: **Mask is used to perform a logical AND operation with the identifier of the CAN frame to filter out CAN frames that meet the conditions. **Each bit of the mask is compared with the corresponding bit of the identifier, and if there is a match, subsequent filtering and processing continues.

Filter Mode: Acceptance filters can be configured in different modes such as Mask Mode and List Mode . In mask bit mode, one or more mask bits and an identifier are used for filtering. In list mode, use multiple filters for matching and filtering.

By properly configuring the reception filter, flexible filtering and selection of CAN frames can be achieved, and only the required data can be received and processed . This is very important to improve the efficiency and reliability of CAN communication, especially in complex systems where there may be multiple CAN nodes and a large number of CAN frames. When using an STM32 microcontroller for CAN communication, the corresponding registers can be used to configure and manage the reception filter.

2.What registers are needed for STM32 to use CAN?

In the STM32 microcontroller, using the CAN controller for CAN communication requires configuring and operating some of the following common CAN-related registers:

Register name effect
CAN controller configuration register (CAN_CRx) Used to configure the working mode of the CAN controller, enable the CAN controller, set the CAN clock source, etc.
CAN Receive Filter Configuration Register (CAN_FMR Parameters used to configure the CAN receive filter, including filter mode, number of filters, etc.
CAN receive filter group X identifier register (CAN_FxR1) and CAN receive filter group X mask register (CAN_FxR2) Identifier and mask used to configure acceptance filter group X.
CAN interrupt enable register (CAN_IER) It is used to configure the enable and mask of CAN interrupt.
CAN Status Register (CAN_SR) Used to read the status information of the CAN controller, such as whether a new CAN frame is received, whether the transmission is completed, etc.
CAN send mailbox X identifier register (CAN_TXxR) and CAN send mailbox X data length register (CAN_TXxDLC) Used to configure the identifier and data length of sending mailbox X.
CAN transmit mailbox X data register (CAN_TXxDTx) Used to configure and send data for sending mailbox X.
CAN receive mailbox X identifier register (CAN_RXxR) and CAN receive mailbox X data length register (CAN_RXxDLC) Used to read the identifier and data length of the CAN frame in the receiving mailbox X.
CAN Receive Mailbox X Data Register (CAN_RXxDTx) Used to read the data of the CAN frame in the receiving mailbox X.
CAN Error Status Register (CAN_ESR) Used to read the error status information of the CAN controller, such as error counter, error type, etc.
CAN Error Management Register (CAN_MSR) Used to clear and manage the error status of the CAN controller.

8. Analyze CAN communication with punctual atomic routines

1. Initialization program

CAN_Mode_Init(CAN_SJW_1tq,CAN_BS2_8tq,CAN_BS1_9tq,4,CAN_Mode_LoopBack);
//CAN初始化环回模式,波特率500Kbps   

What do these parameters mean? How to initialize it? Enter the specific function definition:

//tsjw:重新同步跳跃时间单元.范围:CAN_SJW_1tq~ CAN_SJW_4tq
//tbs2:时间段2的时间单元.   范围:CAN_BS2_1tq~CAN_BS2_8tq;
//tbs1:时间段1的时间单元.   范围:CAN_BS1_1tq ~CAN_BS1_16tq
//brp :波特率分频器.范围:1~1024;  tq=(brp)*tpclk1
//波特率=Fpclk1/((tbs1+1+tbs2+1+1)*brp);
//mode:CAN_Mode_Normal,普通模式;CAN_Mode_LoopBack,回环模式;
//Fpclk1的时钟在初始化的时候设置为36M,如果设置CAN_Mode_Init(CAN_SJW_1tq,CAN_BS2_8tq,CAN_BS1_9tq,4,CAN_Mode_LoopBack);
//则波特率为:36M/((8+9+1)*4)=500Kbps
//返回值:0,初始化OK;
//    其他,初始化失败;
u8 CAN_Mode_Init(u8 tsjw,u8 tbs2,u8 tbs1,u16 brp,u8 mode)
{
    
    

	  GPIO_InitTypeDef GPIO_InitStructure; 
	  CAN_InitTypeDef        CAN_InitStructure;
 	  CAN_FilterInitTypeDef  CAN_FilterInitStructure;
#if CAN_RX0_INT_ENABLE 
   	NVIC_InitTypeDef  NVIC_InitStructure;
#endif
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//使能PORTA时钟	                   											 
  	RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1, ENABLE);//使能CAN1时钟	

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;	//复用推挽
    GPIO_Init(GPIOA, &GPIO_InitStructure);		//初始化IO
   
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//上拉输入
    GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化IO
	  
 	//CAN单元设置
 	  CAN_InitStructure.CAN_TTCM=DISABLE;						 //非时间触发通信模式  //
 	  CAN_InitStructure.CAN_ABOM=DISABLE;						 //软件自动离线管理	 //
  	CAN_InitStructure.CAN_AWUM=DISABLE;						 //睡眠模式通过软件唤醒(清除CAN->MCR的SLEEP位)//
  	CAN_InitStructure.CAN_NART=ENABLE;						 	//禁止报文自动传送 //
  	CAN_InitStructure.CAN_RFLM=DISABLE;						 //报文不锁定,新的覆盖旧的 // 
  	CAN_InitStructure.CAN_TXFP=DISABLE;						 //优先级由报文标识符决定 //
  	CAN_InitStructure.CAN_Mode= mode;	         //模式设置: mode:0,普通模式;1,回环模式; //
  	//设置波特率
  	CAN_InitStructure.CAN_SJW=tsjw;				//重新同步跳跃宽度(Tsjw)为tsjw+1个时间单位  CAN_SJW_1tq	 CAN_SJW_2tq CAN_SJW_3tq CAN_SJW_4tq
  	CAN_InitStructure.CAN_BS1=tbs1; //Tbs1=tbs1+1个时间单位CAN_BS1_1tq ~CAN_BS1_16tq
  	CAN_InitStructure.CAN_BS2=tbs2;//Tbs2=tbs2+1个时间单位CAN_BS2_1tq ~	CAN_BS2_8tq
  	CAN_InitStructure.CAN_Prescaler=brp;            //分频系数(Fdiv)为brp+1	//
  	CAN_Init(CAN1, &CAN_InitStructure);            // 初始化CAN1 
  	
 	CAN_FilterInitStructure.CAN_FilterNumber=0;	  //过滤器0
   	CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask; 
  	CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit; //32位 
  	CAN_FilterInitStructure.CAN_FilterIdHigh=0x0000;32位ID
  	CAN_FilterInitStructure.CAN_FilterIdLow=0x0000;
  	CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x0000;//32位MASK
  	CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000;
  	CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_Filter_FIFO0;//过滤器0关联到FIFO0
 	CAN_FilterInitStructure.CAN_FilterActivation=ENABLE; //激活过滤器0

  	CAN_FilterInit(&CAN_FilterInitStructure);//滤波器初始化
#if CAN_RX0_INT_ENABLE
	
	  CAN_ITConfig(CAN1,CAN_IT_FMP0,ENABLE);//FIFO0消息挂号中断允许.		    
  
  	NVIC_InitStructure.NVIC_IRQChannel = USB_LP_CAN1_RX0_IRQn;
  	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;     // 主优先级为1
  	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;            // 次优先级为0
  	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  	NVIC_Init(&NVIC_InitStructure);
#endif
	return 0;
}   

(1) First, the PA11 and PA12 pins are the transceiver pins of CAN1. Initialize GPIO normally.
insert image description here
(2) Notice here that CAN has two structures,
CAN_InitTypeDef and CAN_FilterInitTypeDef. Look at the concrete structure members of the first one:

typedef struct
{
    
    
 uint16_t CAN_Prescaler; 
 uint8_t CAN_Mode; 
 uint8_t CAN_SJW; 
 uint8_t CAN_BS1; 
 uint8_t CAN_BS2; 
 FunctionalState CAN_TTCM; 
 FunctionalState CAN_ABOM; 
 FunctionalState CAN_AWUM; 
 FunctionalState CAN_NART; 
 FunctionalState CAN_RFLM; 
 FunctionalState CAN_TXFP; 
} CAN_InitTypeDef;
} CAN_InitTypeDef;

This structure seems to have many member variables, but in fact the parameters can be divided into two categories.
The first five parameters are used to set the register CAN_BTR, which is used to set the mode and baud rate related parameters. This has been explained before. The parameter to set the mode is CAN_Mode. In our experiment, we used the loopback mode CAN_Mode_LoopBack and the normal mode CAN_Mode_Normal. You can also choose silent mode and silent loopback mode testing.
Other parameters related to setting the baud rate: CAN_Prescaler, CAN_SJW, CAN_BS1 and CAN_BS2 are used to set the baud rate divider, resynchronization jump width and the number of time units occupied by time period 1 and time period 2 respectively. The next six member variables are used to set the register CAN_MCR, that is, to set the control bits related to CAN communication. The specific comments are:

CAN_InitStructure.CAN_TTCM=DISABLE; //非时间触发通信模式
CAN_InitStructure.CAN_ABOM=DISABLE; //软件自动离线管理
CAN_InitStructure.CAN_AWUM=DISABLE; //睡眠模式通过软件唤醒
CAN_InitStructure.CAN_NART=ENABLE; //禁止报文自动传送
CAN_InitStructure.CAN_RFLM=DISABLE; //报文不锁定,新的覆盖旧的
CAN_InitStructure.CAN_TXFP=DISABLE; //优先级由报文标识符决定
CAN_InitStructure.CAN_Mode= CAN_Mode_LoopBack; //模式设置: 1,回环模式;
//设置波特率
CAN_InitStructure.CAN_SJW=CAN_SJW_1tq;//重新同步跳跃宽度为个时间单位 
CAN_InitStructure.CAN_BS1=CAN_BS1_8tq; //时间段 1 占用 8 个时间单位
CAN_InitStructure.CAN_BS2=CAN_BS2_7tq;//时间段 2 占用 7 个时间单位
CAN_InitStructure.CAN_Prescaler=5; //分频系数(Fdiv)
CAN_Init(CAN1, &CAN_InitStructure); // 初始化 CAN1

And the filter settings:

typedef struct
{
    
    
 uint16_t CAN_FilterIdHigh; 
 uint16_t CAN_FilterIdLow; 
 uint16_t CAN_FilterMaskIdHigh; 
 uint16_t CAN_FilterMaskIdLow; 
 uint16_t CAN_FilterFIFOAssignment; 
 uint8_t CAN_FilterNumber; 
 uint8_t CAN_FilterMode; 
 uint8_t CAN_FilterScale; 
 FunctionalState CAN_FilterActivation; 
} CAN_FilterInitTypeDef;

CAN_FilterIdHigh: The high bits of the filter identifier are used to specify the high 16 bits of the filter identifier.

CAN_FilterIdLow: The low bits of the filter identifier are used to specify the lower 16 bits of the filter's identifier.

CAN_FilterMaskIdHigh: The high bits of the filter mask identifier are used to specify the high 16 bits of the filter's mask identifier.

CAN_FilterMaskIdLow: The low bits of the filter mask identifier are used to specify the lower 16 bits of the filter's mask identifier.

CAN_FilterFIFOAssignment: Filter FIFO assignment, which is used to specify in which FIFO the CAN frames matched by the filter should be stored.

CAN_FilterNumber: Filter number, used to specify the number of the filter.

CAN_FilterMode: Filter mode, used to specify the working mode of the filter, which can be one of the following values: single filter mode, double filter mode, list mode.

CAN_FilterScale: Filter scale, used to specify the scale of the filter, which can be one of the following values: 16-bit scale, 32-bit scale.

CAN_FilterActivation: Filter activation status, used to enable or disable the filter.

2.CAN sends and receives messages

1. Sending and receiving structures

typedef struct
{
    
    
  uint32_t StdId; 
  uint32_t ExtId; 
  uint8_t IDE;    
  uint8_t RTR;    
  uint8_t DLC;    
  uint8_t Data[8]; 
} CanTxMsg;

In fact, as mentioned before, this code defines the structure type CanTxMsg of the CAN message, which is used to represent each field of the CAN message. The specific fields are as follows:

StdId: Standard identifier, used to specify the standard identifier (11 bits) of CAN messages.
ExtId: Extended identifier, used to specify the extended identifier (29 bits) of the CAN message.
IDE: Identifier extension bit, used to specify the identifier type of the CAN message. 0 represents a standard identifier and 1 represents an extended identifier.
RTR: Remote transmission request bit, used to specify the transmission type of CAN message. 0 means data frame, 1 means remote frame.
DLC: Data Length Code, used to specify the data length (0-8 bytes) of the CAN message.
Data: the data of the CAN message, used to store the data content of the CAN message. The data length is specified by the DLC field, and the maximum length is 8 bytes.

//can发送一组数据(固定格式:ID为0X12,标准帧,数据帧)	
//len:数据长度(最大为8)				     
//msg:数据指针,最大为8个字节.
//返回值:0,成功;
//		 其他,失败;
u8 Can_Send_Msg(u8* msg,u8 len)
{
    
    	
  u8 mbox;
  u16 i=0;
  CanTxMsg TxMessage;
  TxMessage.StdId=0x12;					 // 标准标识符 
  TxMessage.ExtId=0x12;				   // 设置扩展标示符 
  TxMessage.IDE=CAN_Id_Standard; // 标准帧
  TxMessage.RTR=CAN_RTR_Data;		 // 数据帧
  TxMessage.DLC=len;						// 要发送的数据长度
  for(i=0;i<len;i++)
  TxMessage.Data[i]=msg[i];			          
  mbox= CAN_Transmit(CAN1, &TxMessage);   
  i=0;
  while((CAN_TransmitStatus(CAN1, mbox)==CAN_TxStatus_Failed)&&(i<0XFFF))i++;	//等待发送结束
  if(i>=0XFFF)return 1;
  return 0;		

}
//can口接收数据查询
//buf:数据缓存区;	 
//返回值:0,无数据被收到;
//		 其他,接收的数据长度;
u8 Can_Receive_Msg(u8 *buf)
{
    
    		   		   
 	u32 i;
	CanRxMsg RxMessage;
    if( CAN_MessagePending(CAN1,CAN_FIFO0)==0)return 0;		//没有接收到数据,直接退出 
    CAN_Receive(CAN1, CAN_FIFO0, &RxMessage);//读取数据	
    for(i=0;i<8;i++)
    buf[i]=RxMessage.Data[i];  
	return RxMessage.DLC;	
}

The core of the sending function is
to use a loop statement to copy the data in the msg array to the Data field of TxMessage one by one .
Call the CAN_Transmit function to send the TxMessage to the CAN1 controller, and save the returned sending mailbox index into the mbox variable .
Initialize i to 0.
Use a loop statement to determine whether the sending is completed. If the sending fails and the number of loops is less than 0XFFF, continue to wait for the sending to end.
If the number of cycles reaches 0XFFF and the transmission is still not successful, 1 will be returned to indicate that the transmission failed.
If sent successfully, return 0 to indicate successful sending.

The core of the receiving function is
to declare a variable RxMessage of type CanRxMsg, which is used to receive CAN messages.
Use the CAN_MessagePending function to determine whether there are pending messages in FIFO0 of the CAN1 controller. If there is no message, 0 is returned directly to indicate that no data has been received.
Use the CAN_Receive function to read data from FIFO0 of the CAN1 controller and save the read data to the RxMessage variable.
Use a loop statement to copy the RxMessage data into the buf buffer one by one.
Returns the DLC field of RxMessage, indicating the received message data length.

3. Main function part

	while(1)
	{
    
    
		key=KEY_Scan(0);
		if(key==KEY0_PRES)//KEY0按下,发送一次数据
		{
    
    
			for(i=0;i<8;i++)
			{
    
    
				canbuf[i]=cnt+i;//填充发送缓冲区
				if(i<4)   printf("canbuf[%d]=%d",i,canbuf[i]);	//显示数据
				else printf("canbuf[%d]=%d",i,canbuf[i]);	//显示数据
 			}
			res=Can_Send_Msg(canbuf,8);//发送8个字节 
			if(res)LCD_ShowString(60+80,190,200,16,16,"Failed");		//提示发送失败
			else LCD_ShowString(60+80,190,200,16,16,"OK    ");	 		//提示发送成功								   
		}else if(key==WKUP_PRES)//WK_UP按下,改变CAN的工作模式
		{
    
    	   
			mode=!mode;
  			CAN_Mode_Init(CAN_SJW_1tq,CAN_BS2_8tq,CAN_BS1_9tq,4,mode);//CAN普通模式初始化, 波特率500Kbps 
			POINT_COLOR=RED;//设置字体为红色 
			if(mode==0)//普通模式,需要2个开发板
			{
    
    
				LCD_ShowString(60,130,200,16,16,"Nnormal Mode ");	    
			}else //回环模式,一个开发板就可以测试了.
			{
    
    
 				LCD_ShowString(60,130,200,16,16,"LoopBack Mode");
			}
 			POINT_COLOR=BLUE;//设置字体为蓝色 
		}		 
		key=Can_Receive_Msg(canbuf);
		if(key)//接收到有数据
		{
    
    			
			LCD_Fill(60,270,130,310,WHITE);//清除之前的显示
 			for(i=0;i<key;i++)
			{
    
    									    
				if(i<4)printf("canbuf[%d]=%d",i,canbuf[i]);	//显示数据
				else printf("canbuf[%d]=%d",i,canbuf[i]);	//显示数据
 			}
		}
		t++; 
		delay_ms(10);
		if(t==20)
		{
    
    
			LED0=!LED0;//提示系统正在运行	
			t=0;
			cnt++;
			printf("cnt=%d",cnt);
			//LCD_ShowxNum(60+48,170,cnt,3,16,0X80);	//显示数据
		}		   
	}
}

It is relatively simple, just create an 8-byte array, store the cnt value into the array using a for loop, press the button, and send it to the node through the CAN sending function.

Summarize

The key points of STM32 driving CAN communication are as follows:

Configure CAN controller: Use registers or library functions to configure the parameters of the CAN controller, including baud rate, operating mode, filters, interrupts, etc. You can choose whether to use standard frames or extended frames.

Initialize the CAN controller: Use library functions to initialize the CAN controller and enable the CAN bus.

Send CAN message: Construct the structure of the CAN message and fill in the corresponding fields, such as identifier, data length, data content, etc. CAN messages are sent to the CAN bus through library functions.

Receive CAN messages: Use the library function to determine whether there is a message to be processed on the CAN bus, and use the library function to read the data of the received CAN message.

Handling CAN interrupts: According to actual needs, configure the interrupts of the CAN controller and write the corresponding interrupt processing function. Process CAN communication-related operations in the interrupt handling function.

Handling CAN errors: Detect the error status of the CAN controller through library functions and perform corresponding error handling.

Configure GPIO pins: Configure the GPIO pins used by the CAN controller to connect them to the CAN bus.

Configure clock: Configure the system clock and the clock used by the CAN controller to ensure the stability of CAN communication.

Debugging and verification: Use appropriate debugging tools and methods to verify the correctness and stability of CAN communication. Can be verified using a CAN analyzer or other equipment.

Guess you like

Origin blog.csdn.net/qq_53092944/article/details/132437193