Is the CAN bus difficult? It is impossible to not understand the CAN bus!

CAN (Controller Area Network) is a controller area network, which is a serial communication network that can realize distributed real-time control.

When thinking of CAN, one must think of the German company Bosch, because CAN is developed by this company (and Intel). CAN has many excellent features that make it widely used. For example: the transmission speed is up to 1Mbps, the communication distance is up to 10km, lossless bit arbitration mechanism, multi-master structure.

In recent years, CAN controller prices have become lower and lower, and many MCUs have also integrated CAN controllers. Now every car is equipped with CAN bus.

A typical CAN application scenario:

CAN bus standard

The CAN bus standard only specifies the physical layer and the data link layer, and the user-defined application layer is required. Different CAN standards differ only in the physical layer.

The CAN transceiver is responsible for the conversion between logic levels and physical signals.

Convert a logical signal to a physical signal (differential level), or convert a physical signal to a logical level.

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

The high and low level amplitude is low, and the corresponding transmission speed is fast;

*Twisted pair common mode eliminates interference because the level changes at the same time and the voltage difference remains unchanged.

Physical layer

CAN has three interface devices

When multiple nodes are connected, as long as one of them is low, the bus is low, and only when all nodes output high, it is high. The so-called "line and".

After the CAN bus has 5 consecutive identical bits, insert an opposite bit to generate a transition edge for synchronization. Thereby eliminating accumulated errors.

Like 485 and 232, the transmission speed of CAN is inversely proportional to distance.

CAN bus, terminal resistance connection:

Why is it 120Ω, because the characteristic impedance of the cable is 120Ω, in order to simulate an infinite transmission line

data link layer

CAN bus transmission is CAN frame, CAN communication frame is divided into five kinds, namely data frame, remote frame, error frame, overload frame and frame interval.

Data frames are used to send and receive data between nodes, and are the most used frame type; remote frames are used to receive data from a receiving node to a sending node; error frames are frames used to notify other nodes when a node finds a frame error; overload frames are A frame used by the receiving node to inform the sending node of its receiving capability; a frame used to isolate data frames and remote frames from previous frames.

Data frame is divided into standard frame (2.0A) and extended frame (2.0B) according to the length of the arbitration section

Start of frame


The frame start is composed of a dominant bit (low level), the sending node sends the frame start, and other nodes are synchronized with the frame start;

The end of the frame consists of 7 invisible bits (high level).

Arbitration section

How does CAN bus solve the problem of multipoint competition?

The answer is given by the arbitration section.

The CAN bus controller monitors the bus level while sending data. If the levels are different, it stops sending and performs other processing. If the bit is in the arbitration section, it will exit the bus competition; if it is in other sections, an error event will be generated.

The smaller the frame ID, the higher the priority. Since the RTR bit of the data frame is at the dominant level and the remote frame is at the recessive level, if the frame format and frame ID are the same, the data frame has priority over the remote frame; since the IDE bit of the standard frame is at the dominant level, The IDE bit of the extended frame is invisible. For standard frames and extended frames with the same ID in the first 11 bits, the priority of the standard frame is higher than that of the extended frame.

Control section

There are 6 bits in total. The control section of the standard frame is composed of extended frame flag bit IDE, reserved bit r0 and data length code DLC; the extended frame control section is composed of IDE, r1, r0 and DLC.

Data segment

0-8 bytes, short frame structure, good real-time performance, suitable for automotive and industrial control fields;

CRC stage

The CRC check segment is composed of 15-bit CRC value and CRC delimiter.

ACK stage

When there is no error from the beginning of the frame received by the receiving node to the CRC segment, it will send a dominant level in the ACK segment, the sending node will send a recessive level, and the line and result will be a dominant level.

Remote frame

The remote frame is divided into 6 segments, which are also divided into standard frames and extended frames, and the RTR bit is 1 (recessive level)

CAN is a very reliable bus, but it also has five errors.

CRC error: This error occurs when the sent and received CRC values ​​are different;

Format error: The error occurs when the frame format is illegal;

Response error: This error occurs when the sending node does not receive the response message in the ACK phase;

Bit sending error: The sending node finds that the bus level does not match the sending level when sending information, and this error occurs;

Bit stuffing error: This error occurs when the communication rules are violated on the communication cable.

When one of these five errors occurs, the sending node or the receiving node will send an error frame

In order to prevent some nodes from making mistakes and sending error frames all the time, interfering with the communication of other nodes, the CAN protocol stipulates 3 states and behaviors of nodes

Overload frame

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

Frame interval

It is used to isolate data frames, remote frames and frames before them, and no frame interval is added before error frames and overload frames.

Build CAN node

Construct a node to realize corresponding control. It is divided into four parts from bottom to top: CAN node circuit, CAN controller driver, CAN application layer protocol, CAN node application program.

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

 

The CAN transceiver and the controller correspond to the physical layer and data link layer of CAN respectively to complete the sending and receiving of CAN messages; the functional circuit completes specific functions, such as signal acquisition or control peripherals; the main controller and application software follow the CAN The message format parses the message and completes the corresponding control.

CAN hardware driver is a program running on the main controller (such as P89V51). It mainly completes the following tasks: register-based operations, initialize the CAN controller, send CAN messages, and receive CAN messages;

If you use the CAN hardware driver directly, you need to modify the upper application program when you change the controller, which is poor in portability. Adding a virtual drive layer to the application layer and hardware drive layer can shield the differences between different CAN controllers.

In addition to completing the communication function, a CAN node also includes some specific hardware function circuits. The function circuit drives the downward direct control function circuit, and the upward provides the control function circuit function interface for the application layer. Specific functions include signal acquisition, man-machine display, etc.

The CAN transceiver realizes the interchange of the logic level of the CAN controller and the differential level on the CAN bus. There are two schemes for implementing CAN transceivers, one is to use CAN transceiver IC (need to add power supply isolation and electrical isolation), and the other is to use CAN isolation transceiver module. The second type is recommended.

The CAN controller is the core component of CAN. It implements all the functions of the data link layer in the CAN protocol and can automatically complete the analysis of the CAN protocol. There are generally two types of CAN controllers, one is the controller IC (SJA1000), and the other is the MCU (LPC11C00) integrated with the CAN controller.

The MCU is responsible for the control of the functional circuit and the CAN controller: when the node is started, it initializes the CAN controller parameters; reads and sends CAN frames through the CAN controller; when the CAN controller is interrupted, handles the interrupt exception of the CAN controller ; Output control signals according to the received data;

 

Interface management logic: Interpret MCU instructions, address the register unit of each functional module in the CAN controller, and provide interrupt information and status information to the main controller.

The sending buffer and receiving buffer can store the complete information on the CAN bus network.

Acceptance filtering is to compare the stored verification code with the CAN message identification code, and only the CAN frame that matches the verification code will be stored in the receiving buffer.

The CAN core implements all the 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 meaning of the data represents. Common CAN application layer protocols are: CANOpen, DeviceNet, J1939, iCAN, etc.

The CAN application layer protocol driver is a program running on the main controller (such as P89V51). It defines the CAN message according to the application layer protocol and completes the analysis and assembly of the CAN message. For example, we use the frame ID to indicate the node address. When the received frame ID does not pass the own node ID, it is directly discarded, otherwise it is passed to the upper layer for processing; when sending, the frame ID is set to the address of the receiving node.

CAN transceiver

There are many output modes of SJA1000, the most used is the normal output mode, the input mode usually does not select the comparator mode, which can increase the communication distance and reduce the current in sleep.

According to the communication speed, the transceiver is divided into high-speed CAN transceiver and fault-tolerant CAN transceiver.

The same CAN transceiver should be used in the same network.

There will be many interference signals on the CAN connection line, and it is necessary to add filters and anti-interference circuits to the hardware

 

CAN isolation transceiver (integrated filter and anti-interference circuit) can also be used.

Connection mode of CAN controller and MCU


SJA1000 can be regarded as an external RAM, the address width is 8 bits, and it supports up to 256 registers

#define REG_BASE_ADDR 0xA000 // 寄存器基址
unsigned char *SJA_CS_Point = (unsigned char *) REG_BASE_ADDR ;

// 写SJA1000寄存器
void WriteSJAReg(unsigned char RegAddr, unsigned char Value) {
*(SJA_CS_Point + RegAddr) = Value;
return;
}

// 读SJA1000寄存器
unsigned char ReadSJAReg(unsigned char RegAddr) {
 return (*(SJA_CS_Point + RegAddr));
}

 

 

 

Write the data in the buffer to the register continuously

…… 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]);   }……

 

 

The header file contains the scheme:

  1. Each program contains the header files used

  2. Each program contains a common header file, which includes all other header files

#ifndef __CONFIG_H__ // 防止头文件被重复包含
#define __CONFIG_H__
#include <8051.h>         // 包含80C51寄存器定义头文件
#include "SJA1000REG.h"         // 包含SJA1000寄存器定义头文件

// 定义取字节运算
#define LOW_BYTE(x)  (unsigned char)(x)
#define HIGH_BYTE(x)  (unsigned char)((unsigned int)(x) >> 8)

// 定义振荡器时钟和处理器时钟频率(用户可以根据实际情况作出调整)
#define OSCCLK 11059200UL
// 宏定义MCU的时钟频率
#define CPUCLK (OSCCLK / 12)
#endif // __CONFIG_H__

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

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

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

(3) Set acceptance filter, set verification code and shield code;

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

(5) Set the output mode;

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

Mode register


 

Detect only mode: SJA1000 does not check the response bit when sending CAN frames;

Listen only mode: In this mode, SJA1000 will not send error frames, which is used to automatically detect the baud rate; SJA1000 receives CAN frames at different baud rates. When CAN frames are received, it indicates the current baud rate and bus baud rate the same.

Baud rate setting

The CAN bus has no clock and uses asynchronous serial transmission; the baud rate is the data bits sent in 1 second;

 

CAN frame transmission:

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

2. Fill the message to the sending buffer;

3. Start sending.

 

SJA1000 has a 12-byte buffer, the message to be sent can be written in through register 16-28, or written or read through register 96-108

 

 

 

Set sending mode

char SetSJASendCmd(unsigned char cmd) {
unsigned char ret;
switch (cmd) {
default:
case 0:
        ret = SetBitMask(REG_CAN_CMR, TR_BIT); //正常发送
break;
case 1:
        ret = SetBitMask(REG_CAN_CMR, TR_BIT|AT_BIT); //单次发送
break;
case 2:
        ret = SetBitMask(REG_CAN_CMR, TR_BIT|SRR_BIT);//自收自发
break;
case 0xff:
        ret = SetBitMask(REG_CAN_CMR, AT_BIT);//终止发送
break;
    }
return ret;
}

 Send function

unsigned char SJA_CAN_Filter[8] = {    // 定义验收滤波器的参数,接收所有帧       
0x00, 0x00, 0x00, 0x00,                                                
// ACR0~ACR3       
0xff, 0xff, 0xff, 0xff                                                         
// AMR0~AMR3
};
unsigned char STD_SEND_BUFFER[11] = {   // CAN 发送报文缓冲区       
0x08,   // 帧信息,标准数据帧,数据长度 = 8       
0xEA, 0x60, // 帧ID = 0x753
0x55, 0x55, 0x55, 0x55, 0xaa, 0xaa, 0xaa, 0xaa  // 帧数据
};
void main(void) // 主函数,程序入口{       
    timerInit();// 初始化
    D1 = 0;       
    SJA1000_RST = 1; // 硬件复位SJA1000       
    timerDelay(50); // 延时500ms       
    SJA1000_RST = 0;       
    SJA1000_Init(0x00, 0x14, SJA_CAN_Filter);   // 初始化SJA1000,设置波特率为1Mbps       
    // 无限循环,main()函数不允许返回      
    for(;;) {           
        SJASendData(STD_SEND_BUFFER, 0x0);           
        timerDelay(100);         // 延时1000ms      
    }    
}

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

 

 

The terminal resistance is very important. When the baud rate is high and the terminal resistance is not added, the signal overshoot is very serious.

 

SJA1000 has a 64-byte receive buffer (FIFO), which can reduce the MCU requirements. MCU can confirm that SJA1000 reads the message after receiving the message by query or interruption.

1. The domestically-made alternatives are intangible? Come back to the Zhaoyi Innovation Live Class!

2. Can the open source RISC-V be the antidote to China's "core shortage"?

3. Raspberry Pi Pico: MCU for only $4

4. There are many reasons why MCU supports AI function~

5. In 2020, 20 software engineering principles I learned~

6. The application of state machine ideas in embedded development~

Disclaimer: This article is reproduced online, and the copyright belongs to the original author. If you are involved in copyright issues, please contact us, we will confirm the copyright based on the copyright certification materials you provide and pay the author's remuneration or delete the content.

Guess you like

Origin blog.csdn.net/DP29syM41zyGndVF/article/details/113749928