Essential CAN Bus Knowledge for Embedded Development

Essential CAN Bus Knowledge for Embedded Development

Welcome to join the technical exchange QQ group (2000 people): Power Electronics Technology and New Energy 905749978

High-reliability new energy industry top self-media

Here you can find power electronics, new energy dry goods, industry development trend analysis, latest product introductions, many technical experts sharing experiences with you. Welcome to follow the WeChat public account: Power Electronics Technology and New Energy (Micro_Grid), forum: www.21micro-grid.com. The original intention of establishing this platform is for technical communication. As a technical personnel dealing with products, market product information and industry technology dynamics are also essential. I hope everyone can not forget their original intention, have a sense of awe, and create better products!

Essential CAN Bus Knowledge for Embedded Development

Power Electronics Technology and New Energy Forum

www.21micro-grid.com

Power Electronics Technology and New Energy Store

Essential CAN Bus Knowledge for Embedded Development

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.

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 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:
Essential CAN Bus Knowledge for Embedded Development

CAN Bus Standards

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.
Essential CAN Bus Knowledge for Embedded Development
The CAN transceiver is responsible for converting between logical levels and physical signals.
Essential CAN Bus Knowledge for Embedded Development
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.
Essential CAN Bus Knowledge for Embedded Development
Low amplitude of high and low levels corresponds to fast transmission speed;
Essential CAN Bus Knowledge for Embedded Development
* 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:
Essential CAN Bus Knowledge for Embedded Development
Essential CAN Bus Knowledge for Embedded Development
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.
Essential CAN Bus Knowledge for Embedded Development
CAN bus, terminal resistance connection:
Essential CAN Bus Knowledge for Embedded Development
Why is it 120Ω? Because the characteristic impedance of the cable is 120Ω, simulating an infinitely long transmission line.
Data Link Layer
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.
Frame Start
Essential CAN Bus Knowledge for Embedded Development
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).
Arbitration Segment
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.
Essential CAN Bus Knowledge for Embedded Development
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.
Control Segment
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.
Essential CAN Bus Knowledge for Embedded Development
Data Segment
It ranges from 0 to 8 bytes, short frame structure, good real-time performance, suitable for automotive and industrial control fields;
Essential CAN Bus Knowledge for Embedded Development
CRC Segment
The CRC check segment consists of a 15-bit CRC value and a CRC delimiter.
Essential CAN Bus Knowledge for Embedded Development
ACK Segment
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.
Remote Frame
The remote frame consists of six segments and is divided into standard frames and extended frames, with the RTR bit being 1 (recessive level).
Essential CAN Bus Knowledge for Embedded Development
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.
Essential CAN Bus Knowledge for Embedded Development
Overload Frame
When a node is not ready to receive, it will send an overload frame to notify the sending node.
Essential CAN Bus Knowledge for Embedded Development
Frame Interval
Used to isolate data frames, remote frames, and their preceding frames. Error frames and overload frames are not preceded by a frame interval.
Essential CAN Bus Knowledge for Embedded Development
Building CAN Nodes
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.
Essential CAN Bus Knowledge for Embedded Development
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.
Essential CAN Bus Knowledge for Embedded Development
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;
Essential CAN Bus Knowledge for Embedded Development
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.
CAN Transceiver
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.
Essential CAN Bus Knowledge for Embedded Development
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:
Essential CAN Bus Knowledge for Embedded Development
CAN isolation transceivers (integrating filters and anti-interference circuits) can also be used.
Essential CAN Bus Knowledge for Embedded Development
Essential CAN Bus Knowledge for Embedded Development
Connection method between CAN controller and MCU:
Essential CAN Bus Knowledge for Embedded Development
SJA1000 can be regarded as external RAM, with an address width of 8 bits, supporting up to 256 registers
Essential CAN Bus Knowledge for Embedded Development
Essential CAN Bus Knowledge for Embedded Development
#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));
}
Essential CAN Bus Knowledge for Embedded Development
Essential CAN Bus Knowledge for Embedded Development
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]);
}
……
Essential CAN Bus Knowledge for Embedded Development
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;
(5) Set output mode;
(6) Clear Bit0 of the mode register to exit reset mode;
Mode Register
Essential CAN Bus Knowledge for Embedded Development
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.
Baud Rate Setting
The CAN bus has no clock and uses asynchronous serial transmission; baud rate is the number of data bits sent per second;
Essential CAN Bus Knowledge for Embedded Development
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.
Essential CAN Bus Knowledge for Embedded Development
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:
Essential CAN Bus Knowledge for Embedded Development
Essential CAN Bus Knowledge for Embedded Development
Set send mode:
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;
}
Send function:
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.
Essential CAN Bus Knowledge for Embedded Development
Essential CAN Bus Knowledge for Embedded Development
Terminal resistance is very important. When the baud rate is high and there is no terminal resistance, signal overshoot can be very serious.
Essential CAN Bus Knowledge for Embedded Development
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.

Article sponsorship is formally open for business, powerdevices: IGBT, MOS,SiC, GaN, magnetic devices, power chips, DSP, MCU, new energy manufacturers can cooperate, those interested can add WeChat ID 1768359031 for details.

Note: This article is sourced from the internet; the views in the article are for sharing and communication only and do not represent the position of this public account. Please indicate the source when reprinting. If there are copyright issues, please let us know, and we will handle it in a timely manner.

Contact list for Power Electronics Technology and New Energy:

Essential CAN Bus Knowledge for Embedded Development

Please click the advertisement and exit

Key Points

How to download the “Power Electronics Technology and New Energy” high-definition PDF e-book in the section

Click the bottom of the articleRead the original text, visit the Power Electronics Technology and New Energy Forum (www.21micro-grid.com) to download!

Or forward the article you want to your Moments without grouping or filtering, then take a screenshot and send it to the editor ( WeChat1413043922), the editor will send the article to you after review!

Essential CAN Bus Knowledge for Embedded Development

Recommended Reading: Click the title to read

LLC_Calculator__Vector_Method_as_an_Application_of_the_Design

Some notes on the layout of power supply boards that I summarized

High_Frequency_Transformers_for_HighPower_Converters_Materials

Huawei Electromagnetic Compatibility Structural Design Specification V2.0

Communication-less Coordinative Control of Paralleled Inverters

Soft Switching for SiC MOSFET Three-phase Power Conversion

Designing Compensators for Control of Switching Power Supplies

100KHZ 10KW Interleaved Boost Converter with full SiC MOSFET

Huawei – Single Board Thermal Design Training Material

Did you gain something from reading? Please share it with more people

Announcement:

Power Electronics Technology and New Energy WeChat group, welcome to add the editor’s WeChat ID: (QQ number) 1413043922, please indicate research direction or industry (for example, photovoltaic inverter hardware). The editor is optimistic about the market development of power electronics technology and new energy and is interested in its key technologies. If you have technical questions, please add the editor on WeChat for discussion.

Essential CAN Bus Knowledge for Embedded Development

Essential CAN Bus Knowledge for Embedded Development

Here you can find power electronics technology: photovoltaic grid-connected inverters (PV modeling, MPPT, grid control, LCL filtering, islanding effect), photovoltaic off-grid, photovoltaic energy storage, wind power converters (doubly-fed, direct drive), bidirectional converter PCS, new energy vehicles, charging piles, on-board power supplies, digital power, bidirectional DCDC (LLC, phase-shifted full bridge, DAB), energy storage (lithium batteries, supercapacitors), low voltage ride-through (LVRT), high voltage ride-through, virtual synchronous generators, multi-agent systems, electrolysis, fuel cells, energy management systems (DC microgrids, AC microgrids), as well as harmonic treatment and reactive power compensation devices such as APF, SVG, DVR, UPQC, etc.
PSCAD/MATLABsimulink/Saber/PSPICE/PSIM——Software simulation + DSP + (TI) TMS320F2812, F28335, F28377, (Microchip) dsPIC30F3011, FPGA, ARM, STM32F334——Hardware products.
Technicians are welcome to join for more exchange and mutual progress!

For more exciting content, click on the bottomRead the original text!

Light upLooking, the editor’s salary will increase by 1 dime!

Leave a Comment