In-Depth Understanding of CAN Bus

CAN Bus (Part 1)

Original Source: http://www.cnblogs.com/jacklu/p/4729638.html

Blog Garden, Author: lulujianjie

Engineers in embedded systems generally know that the CAN bus is widely used in cars; in fact, marine electronic device communication also extensively uses CAN. With the increasing emphasis on national maritime defense, the demand for CAN will also grow. This summer, by participating in social practice in Suzhou, I interned at a ship electrical company for a few weeks and took this opportunity to learn about the CAN bus.

Overview

CAN (Controller Area Network) is a serial communication network that can achieve distributed real-time control.

When thinking of CAN, one must think of the German company Bosch, as it was developed by this company (along with Intel).

CAN has many excellent characteristics that enable its widespread application. For example: the transmission speed can reach up to 1Mbps, the communication distance can be as far as 10km, it has a lossless arbitration mechanism, and a multi-master structure.

In recent years, the price of CAN controllers has decreased significantly, and many MCUs have integrated CAN controllers. Now, every car is equipped with a CAN bus.

A typical application scenario of CAN:

In-Depth Understanding of CAN Bus

CAN Bus Standards

The CAN bus standards only specify the physical layer and data link layer, requiring user-defined application layers. Different CAN standards only differ in the physical layer.

In-Depth Understanding of CAN Bus

CAN transceivers are responsible for the conversion between logical levels and physical signals.

In-Depth Understanding of CAN Bus

They convert logical signals into physical signals (differential levels) or convert physical signals into logical levels.

There are two CAN standards, namely IOS11898 and IOS11519, which have different differential voltage characteristics.

In-Depth Understanding of CAN Bus

Low voltage amplitude corresponds to a fast transmission speed;

In-Depth Understanding of CAN Bus

In-Depth Understanding of CAN Bus

* Twisted pairs eliminate common mode interference because the levels change simultaneously while the voltage difference remains unchanged.

Physical Layer

There are three types of interface devices for CAN.

In-Depth Understanding of CAN Bus

In-Depth Understanding of CAN Bus

When multiple nodes are connected, if one is at a low level, the bus is at a low level; only when all nodes output a high level, is it considered high level.

The CAN bus inserts an opposite bit after five consecutive same bits to create a transition edge for synchronization, thus eliminating cumulative errors.

Similar to RS-485 and RS-232, the transmission speed of CAN is inversely proportional to the distance.

In-Depth Understanding of CAN Bus

The connection method of the terminal resistor for the CAN bus:

In-Depth Understanding of CAN Bus

Why is it 120Ω? Because the characteristic impedance of the cable is 120Ω, to simulate an infinitely long transmission line.

Data Link Layer

The CAN bus transmits CAN frames, which are divided into five types: data frames, remote frames, error frames, overload frames, and frame intervals.

Data frames are used for data transmission between nodes and are the most commonly used frame type; remote frames are used for receiving nodes to request data from sending nodes; error frames are used to notify other nodes of frame errors when a node detects an error; overload frames are used by receiving nodes to inform sending nodes of their receiving capacity; frames are used to isolate data frames, remote frames, and previous frames.

Data frames are divided into standard frames (2.0A) and extended frames (2.0B) based on the length of the arbitration segment.

Frame Start

In-Depth Understanding of CAN Bus

The frame start consists of one dominant bit (low level), and the sending node sends the frame start, while other nodes synchronize to the frame start.

The frame end consists of seven recessive bits (high level).

Arbitration Segment

How does the CAN bus solve the problem of multi-point competition?

The arbitration segment provides the answer.

The CAN bus controller monitors the bus level while sending data. If the levels differ, it stops sending and takes other actions. If the bit is in the arbitration segment, it exits the bus competition; if it is in other segments, it generates an error event.

In-Depth Understanding of CAN Bus

The smaller the frame ID, the higher the priority. Since the RTR bit of the data frame is a dominant level and the remote frame is a recessive level, under the same frame format and frame ID, data frames take priority over remote frames; since the IDE bit of the standard frame is a dominant level and the IDE bit of the extended frame is a recessive level, for the first 11 bits of ID that are the same, standard frames have higher priority than extended frames.

Control Segment

Consisting of 6 bits, the control segment of the standard frame includes the extended frame flag IDE, reserved bit r0, and data length code DLC; the control segment of the extended frame includes IDE, r1, r0, and DLC.

In-Depth Understanding of CAN Bus

Data Segment

Ranging from 0 to 8 bytes, it has a short frame structure with good real-time performance, suitable for automotive and industrial control fields;

In-Depth Understanding of CAN Bus

CRC Segment

The CRC check segment consists of a 15-bit CRC value and a CRC delimiter.

In-Depth Understanding of CAN Bus

ACK Segment

When the receiving node receives the frame start to the CRC segment without errors, it will send a dominant level in the ACK segment, while the sending node sends a recessive level, resulting in a dominant level as the line AND result.

Remote Frame

Remote frames are divided into 6 segments and are also classified into standard frames and extended frames, with the RTR bit set to 1 (recessive level).

In-Depth Understanding of CAN Bus

CAN is a highly reliable bus, but it also has five types of errors.

CRC Error: This error occurs when the CRC values sent and received differ;

Format Error: This error occurs when the frame format is invalid;

Acknowledgment Error: This error occurs when the sending node does not receive acknowledgment information during the ACK phase;

Bit Sending Error: This error occurs when the sending node finds that the bus level does not match the sending level while sending information;

Bit Stuffing Error: This error occurs when communication rules are violated on the communication line.

When any of these five errors occur, the sending node or receiving node will send an error frame.

To prevent some nodes from continuously sending error frames due to their own errors, interfering with communication with other nodes, the CAN protocol specifies three states and behaviors for nodes

In-Depth Understanding of CAN Bus

Overload Frame

When a node is not ready to receive, it will send an overload frame to notify the sending node.

In-Depth Understanding of CAN Bus

Frame Interval

Used to isolate data frames, remote frames, and their preceding frames; error frames and overload frames do not have frame intervals before them.

In-Depth Understanding of CAN Bus

// Understand the last slide of 1.6 well

Building CAN Node

Constructing nodes to achieve corresponding control, divided into four parts from bottom to top: CAN node circuit, CAN controller driver, CAN application layer protocol, and CAN node application program.

Although the functions completed by different nodes differ, they all have the same hardware and software structure.

In-Depth Understanding of CAN Bus

The CAN transceiver and controller correspond to the physical layer and data link layer of CAN, completing the sending and receiving of CAN messages; functional circuits complete specific functions, such as signal acquisition or controlling peripherals; the main controller and application software parse the message according to the CAN message format to achieve corresponding control.

The CAN hardware driver is a program running on the main controller (such as P89V51), which mainly completes the following tasks: register-based operations, initializing the CAN controller, sending CAN messages, and receiving CAN messages;

If the CAN hardware driver is used directly, when changing the controller, the upper application program needs to be modified, resulting in poor portability. By adding a virtual driver layer between the application layer and hardware driver layer, the differences between different CAN controllers can be masked.

A CAN node not only completes communication functions but also includes some specific hardware functional circuits. The functional circuit driver directly controls the functional circuit downwards and provides control function circuit function interfaces upwards. Specific functions include signal acquisition, human-machine display, etc.

In-Depth Understanding of CAN Bus

CAN transceivers realize the interchange between the logic levels of the CAN controller and the differential levels on the CAN bus. There are two schemes for implementing the CAN transceiver: one is to use a CAN transceiver IC (which requires power isolation and electrical isolation), and the other is to use a CAN isolation transceiver module. The second option is recommended.

The CAN controller is the core component of CAN, implementing all functions of the data link layer in the CAN protocol and automatically completing the parsing of CAN protocol. There are generally two types of CAN controllers: one is the controller IC (SJA1000), and the other is the MCU with integrated CAN controller (LPC11C00).

The MCU is responsible for controlling the functional circuit and CAN controller: at node startup, initialize the parameters of the CAN controller; read and send CAN frames through the CAN controller; handle interrupt exceptions of the CAN controller when interrupts occur; output control signals based on the received data;

In-Depth Understanding of CAN Bus

Interface management logic: interprets MCU instructions, addresses the register units of each functional module in the CAN controller, and provides interrupt information and status information to the main controller.

The send buffer and receive buffer can store complete information on the CAN bus network.

Acceptance filtering compares the stored verification code with the CAN message identification code, and only the CAN frames that match the verification code will be stored in the receive buffer.

The CAN kernel implements all protocols of the data link.

Overview of CAN Protocol Application Layer

The CAN bus only provides reliable transmission services, so when a node receives a message, it must use the application layer protocol to determine who sent the data and what the data represents. Common CAN application layer protocols include: CANOpen, DeviceNet, J1939, iCAN, etc.

The CAN application layer protocol driver is a program running on the main controller (such as P89V51) that defines the CAN messages according to the application layer protocol, completing parsing and assembling of CAN messages. For example, we use the frame ID to represent the node address; when the received frame ID does not match the node ID, it is discarded directly; otherwise, it is handed over to the upper layer for processing; when sending, the frame ID is set to the address of the receiving node.

CAN Transceiver

The output modes of SJA1000 are numerous, with the most commonly used being the normal output mode. The input mode usually does not select the comparator mode, which can increase communication distance and reduce current during sleep.

In-Depth Understanding of CAN Bus

Transceivers are divided into high-speed CAN transceivers and fault-tolerant CAN transceivers based on communication speed.

All CAN transceivers in the same network must be the same.

There will be many interference signals on the CAN connection line, so hardware filters and anti-interference circuits need to be added.

In-Depth Understanding of CAN Bus

Alternatively, a CAN isolation transceiver (integrating filters and anti-interference circuits) can be used.

In-Depth Understanding of CAN Bus

In-Depth Understanding of CAN Bus

Connection method between CAN controller and MCU

In-Depth Understanding of CAN Bus

SJA1000 can be regarded as an external RAM, with an address width of 8 bits, supporting up to 256 registers

In-Depth Understanding of CAN Bus

In-Depth Understanding of CAN Bus

1

2

3

4

5

6

7

8

9

10

11

12

13

#define REG_BASE_ADDR 0xA000 // Register Base Address

unsigned char *SJA_CS_Point = (unsigned char *) REG_BASE_ADDR ;

// Write SJA1000 Register

void WriteSJAReg(unsigned char RegAddr, unsigned char Value) {

*(SJA_CS_Point + RegAddr) = Value;

return;

}

// Read SJA1000 Register

unsigned char ReadSJAReg(unsigned char RegAddr) {

return (*(SJA_CS_Point + RegAddr));

}

In-Depth Understanding of CAN Bus

In-Depth Understanding of CAN Bus

Continuously write data from the buffer to the register

…… for (i=0;i<len;i++) { WriteSJAReg(RegAdr+i,ValueBuf[i]); } ……

Continuously read multiple registers into the buffer

…… for (i=0;i<len;i++) { ReadSJAReg(RegAdr+i,ValueBuf[i]); } ……

In-Depth Understanding of CAN Bus

Header file inclusion scheme:

  1. Each program includes the necessary header files

  2. Each program includes a common header file that contains all other headers

1

2

3

4

5

6

7

8

9

10

11

12

13

14

#ifndef __CONFIG_H__ // Prevent header file from being included multiple times

#define __CONFIG_H__

#include <8051.h> // Include 80C51 Register Definition Header File

#include "SJA1000REG.h" // Include SJA1000 Register Definition Header File

// Define byte operations

#define LOW_BYTE(x) (unsigned char)(x)

#define HIGH_BYTE(x) (unsigned char)((unsigned int)(x) >> 8)

// Define oscillator clock and processor clock frequency (users can adjust according to actual situation)

#define OSCCLK 11059200UL

// Macro definition of MCU clock frequency

#define CPUCLK (OSCCLK / 12)

#endif // __CONFIG_H__

The SJA1000 is in a reset state after power-on and must be initialized before it can work.

(1) Set the mode register Bit0 to enter reset mode;

(2) Set the clock division register to select clock frequency and CAN mode;

(3) Set acceptance filtering, defining verification and masking codes;

(4) Set the bus timer registers 0 and 1 to set the CAN baud rate;

(5) Set output mode;

(6) Clear the mode register Bit0 to exit reset mode;

Mode Register

In-Depth Understanding of CAN Bus

Listen-only mode: The SJA1000 does not check the acknowledgment bit when sending CAN frames;

Listen mode: In this mode, the SJA1000 will not send error frames, used for automatic baud rate detection; the SJA1000 receives CAN frames at different baud rates, and when a CAN frame is received, it indicates that the current baud rate matches the bus baud rate.

Baud Rate Settings

The CAN bus has no clock and uses asynchronous serial transmission; the baud rate is the number of bits sent per second;

In-Depth Understanding of CAN Bus

Sending CAN Frames:

Steps to send a CAN frame: 1. Check the status register, wait for the send buffer to be available;

2. Fill the message into the send buffer;

3. Start sending.

In-Depth Understanding of CAN Bus

The SJA1000 has a 12-byte buffer, and the messages to be sent can be written through registers 16-28, or written or read through registers 96-108.

In-Depth Understanding of CAN Bus

In-Depth Understanding of CAN Bus

Set sending mode

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

char SetSJASendCmd(unsigned char cmd) {

unsigned char ret;

switch (cmd) {

default:

case 0:

ret = SetBitMask(REG_CAN_CMR, TR_BIT); // Normal Send

break;

case 1:

ret = SetBitMask(REG_CAN_CMR, TR_BIT|AT_BIT); // Single Send

break;

case 2:

ret = SetBitMask(REG_CAN_CMR, TR_BIT|SRR_BIT);// Self-send

break;

case 0xff:

ret = SetBitMask(REG_CAN_CMR, AT_BIT);// Terminate Sending

break;

}

return ret;

}

Sending function

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

unsigned char SJA_CAN_Filter[8] = { // Define acceptance filter parameters, receive all frames

0x00, 0x00, 0x00, 0x00,

// ACR0~ACR3

0xff, 0xff, 0xff, 0xff

// AMR0~AMR3

};

unsigned char STD_SEND_BUFFER[11] = { // CAN Sending Message Buffer

0x08, // Frame Info, Standard Data Frame, Data Length = 8

0xEA, 0x60, // Frame ID = 0x753

0x55, 0x55, 0x55, 0x55, 0xaa, 0xaa, 0xaa, 0xaa // Frame Data

};

void main(void) // Main Function, Program Entry

{

timerInit();// Initialize

D1 = 0;

SJA1000_RST = 1; // Hardware Reset SJA1000

timerDelay(50); // Delay 500ms

SJA1000_RST = 0;

SJA1000_Init(0x00, 0x14, SJA_CAN_Filter); // Initialize SJA1000, set baud rate to 1Mbps

// Infinite loop, main() function should not return

for(;;) {

SJASendData(STD_SEND_BUFFER, 0x0);

timerDelay(100); // Delay 1000ms

}

}

Why is the frame ID 0x753? This is related to the storage format of CAN frames in the buffer.

In-Depth Understanding of CAN Bus

In-Depth Understanding of CAN Bus

The terminal resistor is very important; when the baud rate is high and no terminal resistor is added, signal overshoot can be very severe.

In-Depth Understanding of CAN Bus

Source: Hardware Ten Thousand Why. (End)

More Exciting:

Yan Ten │ Thoughts and Suggestions on the “Predicament” of Young Teachers in Higher Education

Academician Zheng Weimin: Why Computer Majors Have Become Popular Choices for Examinees

【Directory】 “Computer Education” 2022 Issue 6

【Directory】 “Computer Education” 2022 Issue 5

【Directory】 “Computer Education” 2022 Issue 4

【Directory】 “Computer Education” 2022 Issue 3

【Directory】 “Computer Education” 2022 Issue 2

【Directory】 “Computer Education” 2022 Issue 1

【Editorial Message】 Professor Li Xiaoming of Peking University: Reflections on the “Year of Improvement in Classroom Teaching”…

Professor Chen Daoxu of Nanjing University: Which is more important, teaching students to ask questions or teaching students to answer questions?

【Yan Ten Series】: Trends in Computer Discipline Development and Their Impact on Computer Education

Professor Li Xiaoming of Peking University: From Interesting Mathematics to Interesting Algorithms to Interesting Programming – A Path for Non-Professional Learners to Experience Computational Thinking?

Reflections on Several Issues in Building a First-Class Computer Discipline

Professor Zhan Dechen of Harbin Institute of Technology: A New Model to Ensure Teaching Quality in Higher Education – Synchronous-Asynchronous Hybrid Teaching

[Principal Interview] Accelerating the Advancement of Computer Science Education and Becoming a Pathfinder in Data Science Education – Interview with Professor Zhou Aoying, Vice President of East China Normal University

New Engineering and Big Data Major Construction

Other Stones Can Attack Jade – Compilation of Research Articles on Computer Education at Home and Abroad

Leave a Comment