Engineers in embedded systems generally know that the CAN bus is widely used in automobiles. In fact, ship electronic devices also widely use CAN. As the country pays more and more attention to maritime defense, the demand for CAN will also increase.
CAN (Controller Area Network) is a serial communication network that can achieve distributed real-time control.
When thinking of CAN, one must think of Bosch, a German company, because CAN was developed by this company (and Intel).
CAN has many excellent features that allow it to be widely used. For example: a maximum transmission speed of 1Mbps, a maximum communication distance of 10km, 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 for CAN:
The CAN bus standard only specifies the physical and data link layers, requiring users to define the application layer. Different CAN standards only differ in the physical layer.
The CAN transceiver is responsible for converting between logical levels and physical signals.
It converts logical signals into physical signals (differential levels) or converts physical signals into logical levels.
There are two CAN standards, namely IOS11898 and IOS11519, which differ in their differential voltage characteristics.
Low amplitude of high and low levels corresponds to fast transmission speed;
* Twisted pair common-mode interference elimination is because the levels change simultaneously while the voltage difference remains unchanged.
Physical Layer
There are three types of interface devices for CAN:
Multiple nodes are connected; as long as one is low, the bus is low. It will only be high when all nodes output high. This is called “wired AND”.
The CAN bus inserts an opposite bit after five consecutive identical bits to produce a transition edge for synchronization, thus eliminating cumulative errors.
Like 485 and 232, the transmission speed of CAN is inversely proportional to the distance.
CAN bus, terminal resistance connection:
Why is it 120Ω? Because the characteristic impedance of the cable is 120Ω, simulating an infinitely long transmission line.
The CAN bus transmits CAN frames, which are divided into five types: data frame, remote frame, error frame, overload frame, and frame interval.
The data frame is used for nodes to send and receive data; it is the most commonly used frame type. The remote frame is used for receiving nodes to request data from sending nodes; the error frame is used to notify other nodes of frame errors when a node detects an error; the overload frame is used by the receiving node to inform the sending node of its receiving capacity; and the frame interval is used to isolate the data frame, remote frame, 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.
The frame start consists of a dominant bit (low level), sent by the sending node, while other nodes synchronize to the frame start;
The frame end consists of seven recessive bits (high level).
How does the CAN bus solve the problem of multiple-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.
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 ID, the data frame has a higher priority than the remote frame; 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 standard and extended frames with the same first 11 bits ID, the standard frame has a higher priority than the extended frame.
It consists of six 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 consists of IDE, r1, r0, and DLC.
It ranges from 0 to 8 bytes, short frame structure, good real-time performance, suitable for automotive and industrial control fields;
The CRC check segment consists of a 15-bit CRC value and a CRC delimiter.
When the receiving node receives a 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 wired AND.
The remote frame consists of six segments and is divided into standard frames and extended frames, with the RTR bit being 1 (recessive level).
CAN is a highly reliable bus, but it also has five types of errors:
CRC Error: This error occurs when the sent and received CRC values 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 during the ACK phase;
Bit Sending Error: This error occurs when the sending node detects that the bus level does not match the sending level during transmission;
Bit Stuffing Error: This error occurs when the communication line violates communication rules.
When one of these five errors occurs, the sending 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.
When a node is not ready to receive, it will send an overload frame to notify the sending node.
Used to isolate data frames, remote frames, and their preceding frames. Error frames and overload frames are not preceded by a frame interval.
Building nodes to implement corresponding controls, divided into four parts from bottom to top: CAN node circuit, CAN controller driver, CAN application layer protocol, and CAN node application program.
Although different nodes perform different functions, they all have the same hardware and software structure.
The CAN transceiver and controller correspond to the physical layer and data link layer of CAN, completing the sending and receiving of CAN messages; the functional circuit completes specific functions, such as signal acquisition or controlling peripherals; the main controller and application software parse messages according to CAN message format to complete corresponding controls.
The CAN hardware driver is a program running on the main controller (such as P89V51), which mainly performs 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 controllers, the upper application program needs to be modified, resulting in poor portability. Adding a virtual driver layer between the application layer and hardware driver layer can shield the differences between different CAN controllers.
A CAN node not only completes communication functions but also includes some specific hardware functional circuits. The functional circuit drives the functional circuit directly downward and provides a control function circuit function interface to the application layer upward. Specific functions include signal acquisition, human-machine display, etc.
The CAN transceiver is responsible for switching between the logical level of the CAN controller and the differential level on the CAN bus. There are two schemes to implement 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 latter is recommended.
The CAN controller is the core component of CAN, implementing all the functions of the data link layer of the CAN protocol and automatically completing the parsing of the CAN protocol. There are generally two types of CAN controllers: one is controller IC (SJA1000), and the other is MCU with integrated CAN controller (LPC11C00).
The MCU is responsible for controlling the functional circuit and CAN controller: initializing CAN controller parameters when the node starts; reading and sending CAN frames through the CAN controller; handling CAN controller interrupt exceptions when interrupts occur; outputting control signals based on received data;
Interface management logic: interprets MCU instructions, addresses the register units of various functional modules in the CAN controller, and provides interrupt 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 identifier; only 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 nodes receive messages, they must rely on application layer protocols 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), which defines CAN messages according to the application layer protocol and completes the parsing and assembly of CAN messages. For example, we use the frame ID to represent the node address. When the received frame ID does not match its own 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.
The output mode of SJA1000 has many options, the most commonly used is the normal output mode. The input mode usually does not select the comparator mode, which can increase communication distance and reduce current during sleep.
Transceivers are divided into high-speed CAN transceivers and fault-tolerant CAN transceivers based on communication speed.
In the same network, the same CAN transceiver must be used.
There will be many interference signals on the CAN connection line, and filters and anti-interference circuits need to be added in hardware:
CAN isolation transceivers (integrating filters and anti-interference circuits) can also be used.
Connection method between CAN controller and MCU:
SJA1000 can be regarded as external RAM, with an address width of 8 bits, supporting up to 256 registers
#define REG_BASE_ADDR 0xA000 // Register base address
unsigned char *SJA_CS_Point = (unsigned char *) REG_BASE_ADDR ;
// Write to SJA1000 register
void WriteSJAReg(unsigned char RegAddr, unsigned char Value)
{
*(SJA_CS_Point + RegAddr) = Value;
return;
}
// Read from SJA1000 register
unsigned char ReadSJAReg(unsigned char RegAddr)
{
return (*(SJA_CS_Point + RegAddr));
}
Write data from buffer continuously to registers:
……
for (i=0; i<len; i++)
{
WriteSJAReg(RegAdr + i, ValueBuf[i]);
}
……
Read multiple consecutive registers into buffer:
……
for (i=0; i<len; i++)
{
ReadSJAReg(RegAdr + i, ValueBuf[i]);
}
……
Header file inclusion scheme:
1. Each program includes the header files it uses
2. Each program includes a common header file, which includes all other header files
#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 conditions)
#define OSCCLK 11059200UL
// Macro definition of MCU clock frequency
#define CPUCLK (OSCCLK / 12)
#endif // __CONFIG_H__
The SJA1000 is in reset state after power-up and must be initialized before it can work:
(1) Set Bit0 of the mode register to enter reset mode;
(2) Set the clock division register to select clock frequency and CAN mode;
(3) Set acceptance filtering, defining the verification code and mask code;
(4) Set bus timer registers 0 and 1 to define the CAN baud rate;
(6) Clear Bit0 of the mode register to exit reset mode;
Only detection mode: The SJA1000 does not check the acknowledgment bit when sending CAN frames;
Listen-only 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. When a CAN frame is received, it indicates that the current baud rate matches the bus baud rate.
The CAN bus has no clock and uses asynchronous serial transmission; baud rate is the number of data bits sent per second;
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;
The SJA1000 has a 12-byte buffer, and the messages to be sent can be written through registers 16-28, or read or written through registers 96-108:
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 send
break;
}
return ret;
}
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 send message buffer
0x08, // Frame information, 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 is not allowed to 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 the CAN frame in the buffer.
Terminal resistance is very important. When the baud rate is high and there is no terminal resistance, signal overshoot can be very serious.
The SJA1000 has a 64-byte receive buffer (FIFO), which can reduce the requirements on the MCU.
The MCU can determine whether the SJA1000 has received a message through polling or interrupt methods.