Controller Area Network (CAN Bus) (Controller Area Network Projects With Arduino Uno and Raspberry Pi 3)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

CONTROLLER

AREA NETWORK
PART – 1 THEORY
V ITALI M UELLER

Copyright © 2016

Get the video training course on Controller Area Network Projects at:
vitalimueller.com/courses

PREFACE

The Controller Area Network (CAN Bus) was developed in the mid 1980’s by Bosch and
Intel, for use in the automotive industry. Today, CAN Bus is not only used in passenger
cars, but it is also used in many other applications such as
Bus
Train
Aviation
Lift
Medical Equipment
Space application
And much, much more …

My goal in this series of eBooks is to explain the fundamentals of the Bus System and
CAN Bus protocol, and to give you a detailed understanding how communication between
microcomputers in the automotive industry transmit-, receive, and process data.
In the Controller Area Network Projects – Part 2, you will learn about the Arduino and
Raspberry Pi Framework, and you will be walked through the installation process, what
software needs to be installed, and how to prototype software application. We will also
hack into an instrument cluster to identify CAN Bus Ids from the modules and write
functionalities in the software to control the module unit.
At the end of this eBook you will have a good understanding,
- How Network Communication works
- How Controller Area Network works
- Have the knowledge to proceed to Part 2 (CAN Bus Projects)
CONTACT THE AUTHOR
Despite all efforts in preparing this eBook, there is always the possibility that some errors
will occur. As the author, the responsibility for any such errors is mine alone. If you would
like to suggest any amendments or corrections, please send me your comment and I will
respond to you as soon as I can.
To submit amendments and corrections please visit the author’s website at
http://vitalimueller.com/contact/


TABLE OF CONTENTS

Preface
Contact the Author
Table of Contents
Chapter 1. Bus System Fundamentals
Communication
Direct Connection
Point to Point Interface
Bus System
Only one can send
Master Control
Priority Control
Time Control
Protocol – Speak same language
Transmission rate
Communication Medium
Topology
Serial Communication
Parallel Communication
OSI Model
Chapter 2. CAN Bus Fundamentals
History
CAN Milestones
Topology
Difference in Voltage
Dominant & Recessive
Transceiver (Physical Layer)
Bit synchronization
CAN Controller (Data Link Layer)
Chapter 3. CAN Bus Protocol
Data Frame
Start Of Frame (SOF)
Identifier
Arbitration Field
CAN Bus 2.0A & 2.0B (Standard/Extended)
RTR Field
Control Field
Data Field
CRC Field
ACK Field
EOF Field
Acceptance Filter
Acceptance Filter Example
Acceptance Mask Register – Filter
Acceptance Code Register – Mask
Example:
Chapter 4. Error Handling
Introduction
Troubleshooting
Fault detection – CRC Check
Fault Detection – Frame Check
Fault Detection – ACK Error
Fault Detection – Bit Monitoring
Fault Detection – Bit Stuffing
About The Author
One Last Thing…
CHAPTER 1. BUS SYSTEM FUNDAMENTALS
COMMUNICATION
People can only communicate effectively with each other when they speak the same
language (English, German, etc.). The communication language for computers (Bus) is the
protocol.

People participate in a conversation. For computers (Bus systems) to communicate with


each other they must be connected to a network (CAN Bus).

Figure 1Bus Nodes

Children learn in the school that they cannot speak when they want. There must be rules
that govern who and when someone may say something. There are also rules in Bus
systems, called arbitration, that govern when computers may speak to each other. Our
communications take place by these 3 methods, which are also be found in Bus systems:
1. Communication is event driven, to a question we provide the answer
2. Communication is time driven, each has only a short time to say something.
3. Communication is from a master. For example, teacher at school
A conversation between two people at a concert is disturbed by loud noises that might
even make it impossible to hear what is being said. In comparison Bus systems are
affected by electromagnetic interference. Bus systems cannot exchange signals over
considerable distances. To do so requires the signals have to be amplified electronically.
People also aids, such as loudspeakers, microphone, and headphones to boost the sound
level so that it is audible.
However, there are some people who, while participating in a conversation, adhere to no
rules and talk incessantly seemingly without stopping. That can also be found in Bus
systems where defective nodes are permanently sending signals. These are called
“babbling idiot” nodes.
The name ‘Bus system’ is derived from the idea that many pieces of information are
placed into a message container and transmitted on the road (bus) from the stop (node) and
transported to another stop (node).

DIRECT CONNECTION
Before Bus systems, each connection required a separate line for information to flow. As
shown in the image below, each switch (transmitter) with the corresponding lamp
(receiver) is connected directly via an electrical wire.

Figure 2 Direct Connection

The disadvantages are obvious:


- Many electrical wires have to be laid
- Changes are very inconvenient and expensive
POINT TO POINT INTERFACE
Point to Point connection can only be used if all switches and bulbs are located at the same
location. In the image below you can see that four switches are placed together and the
same applies to the bulbs. This enables the switches and bulbs to communicate over point
to point communication, which has only one wire connection.
Specific modules have to be introduced to control the electrical switch information into
the corresponding interface protocol. This module is represented as red box in the image
below and their functionality is to identify which bulb has to be controlled based on the
switch id.

Figure 3 Point to Point Interface,


BUS SYSTEM
How do you to connect the switches and lights when they are all physically far apart?
The answer is to connect them over a Bus system. Every switch now has a green box (see
image below). A green box represents a node which has a logic unit to understand the
signal information and to know when to process the signal further or reject it.

Figure 4 Bus system - Green Box (Node)

The term ‘Bus system’ reflects the functionality for forwarding information. Several
individual information carriers (signals) are forwarded together in a frame on the Bus
system, from one location to several locations. On the road, however, only one Bus is
allowed to drive at a time. Driving another vehicle, such as a car or another Bus along the
same road at the same time would lead to congestion higher costs, and data conflicts.
ONLY ONE CAN SEND
To avoid congestion on a Bus system, only one node can transmit a message and the other
nodes are in the listening mode. There must be a rule in the Bus system to prevent two
nodes from simultaneously accessing the Bus system (Arbitration).
If a node does not have the latest information, then it takes this information from the Bus
and simply discards the old data. The information has to be taken off the Bus first,
otherwise the node does not know which message was transmitted. When the node is
currently in transmitting status then all other nodes have to wait until the sending is
completed. This is a disadvantage of the bus systems.
MASTER CONTROL
We have previously learned that only one node at the time has access to the Bus system.
Who controls the entire communication in a bus system? For this purpose, there are 3
different methods:
The first method is Master controlled. In this method there is only one node, which is
called Master, and it decides which node can access the Bus system. An example of this
method is the LIN Bus.

Figure 5 Master Control



PRIORITY CONTROL
The second method is the priority method and is a well-known CAN Bus protocol. In this
method nodes with higher priority can access the bus.

Figure 6 CAN Bus


TIME CONTROL
The third method is the time control method. The messages are sent cyclically in the space
reserved for it in a time window. Each message has a constant cycle, a time window in
which only they can send their messages. An example of this method is FlexRay.
PROTOCOL – SPEAK SAME LANGUAGE
We know now that only one node (or person) can talk and the rest is listening.
Communication is ineffective if everyone is talking in a different language (Spainish,
German, English).
That’s why it is also important to select one language (protocol) for the communication
(Bus system).
The information on the Bus system is transmitted in digital (high/low) signal. High can be
5 or 3 Volts and Low is normally 0 Volt. It contains several bits and all bits together are
representing a frame. A frame consists of a head, data and a checking unit. A frame
delivers many pieces of information, such as the start of the frame, length of the data
messages, and much more.
Each protocol normally has a head, data and a check unit but the details can vary based on
the protocol. In the image below you can see a general representation of a frame.

Figure 7 Frame

TRANSMISSION RATE
In a Bus System all nodes need to know how long is a Bit (High/Low), otherwise they
could not clearly identify the Bits.
The transmission rate on a Bus system will be measured in Bit/s NOT in Byte/s! This unit
is also stated as Baudrate, or bps (bits per second).

Figure 8 Baudrate

Each participant (microcontroller) responds to the flanks in the bit stream. When after
each High signal a Low signal would follow, then the flanks for the High/Low detection
would be sufficient. This it is not the case in digital technology as in most scenarios we
have several zeros or ones behind each other that need to be recognized. Therefore, every
participant (microcontroller) knows how high the transmission rate is and also its own
clock rate.
In the image there are 6 cycles per bit. The sampling time for the clock rate needs to be
clearly higher than the transmission rate of the Bus system.

Today you can find bus systems with transmission rates in kBit/s (LIN, CAN) and high-
speed bus systems in MBit/s range, such as FlexRay at 10 MBit/s or ETHERNET with 10
to 100 MBit/s, GigaEthernet 1000 Mbit/s and more.
COMMUNICATION MEDIUM
Each node has a so-called transceiver, which has the task to adapt the bit frames to the
physical bus and read the incoming bits. It operates as an A/D or D/A converter.

Figure 9 Network

In a copper cable the voltage is adjusted and the signal is amplified. In an optical
fiber the bits have to be converted into light pulses.
TOPOLOGY
The topology tells how the individual nodes are connected together.

Figure 10 Topology

The most common structure is the Bus structure (line structure). Nodes are connected via
short stub lines to a common data line.
A star structure has a central distributer, and all other nodes are connected to it.
In a ring structure, all nodes are connected in a circle.
SERIAL COMMUNICATION
In serial transmission, the individual bits are consecutively transmitted from sender to
recipient.

Figure 11Serial Communication


PARALLEL COMMUNICATION
In the parallel transmission all bits will be transmitted parallel from sender to recipient.

Figure 12 Parallel Communication


OSI MODEL
The model is a product of the Open Systems Interconnection project at the International
Organization for Standardization (ISO), maintained by the identification ISO/IEC 7498-1
and consists of a 7-layer reference model as show in the image below.
The OSI model is a way of subdividing a communications system into smaller manageable
parts called layers. A layer is a collection of functions that receive information from the
layer below and provide information to the layer above. The OSI reference model is now
considered as a primary standard for computer networking. Today many network
communication protocols are based on the standards of this model.

Figure 13 OSI Model


CHAPTER 2. CAN BUS FUNDAMENTALS

HISTORY
The Controller Area Network (CAN) was founded by Robert Bosch GmbH and first
introduced in February of 1986, at the Society of Automotive Engineers (SAE) congress.
The idea behind it was to reduce the wiring complexity, simplify and to improve the
functionality of the increasingly complex automotive electronics.
With the help of CAN, the automotive industry could handle the massive problems arising
from the increasing use of electronic modules.
The engineers were working on a system that could be easily modified by adding modules
(e.g. ABS, etc.) to the existing network, but also at the same time not to be concerned
about the necessary wiring to the hardware components which were conventionally done
in the older cars. For the development of high-performance and cost-efficient controller
solutions Robert Bosch GmbH cooperated with the Intel company and in 1989 brought the
first “CAN Controller” as an integrated circuit to the market.
This required the CAN protocol to adapt to the OSI model. The CAN bus is distinguished
by the existing networking through:
Error handling
Prioritization of messages
Real time capability
High data transfer rate
Multi master principle

CAN MILESTONES
TOPOLOGY
The CAN Bus is connected in the bus topology (Line structure). The participants are also
called nodes. CAN is a Multi-Master system in which all nodes have equal access rights.

Figure 14 CAN Bus

The nodes are connected by a twisted wire and have at the end of a network a resistor.
CAN Bus is a serial communication system and the data is transmitted on CAN-High and
CAN Low wires.
In the praxis maximal 64 nodes could be connected to the network, but in theory you can
add as many as you want.
The transmission rate of a CAN Bus is between 60 kBit/s to 1 Mbit/s. The transmission
rate depends also on the distance of the connected nodes.
DIFFERENCE IN VOLTAGE
Electrical noise immunity is among other things achieved by transmitting simultaneously
one bit on two lines CAN High and CAN Low with a potential change in opposite
directions.

Figure 15 CAN Signal

This is known as a differential signal. The differential voltage is transferred between the
two lines which are also called CAN High and CAN Low.
DOMINANT & RECESSIVE
CAN Bus defines the status bit low as Dominant (0) and Bit High as Recessive (1)
TRANSCEIVER (PHYSICAL LAYER)
The lowest layer in the OSI model is the physical layer (transceiver).

Figure 16 Transceiver

The task of this level will be performed by the so-called transceiver. One participant
(microcontroller, PC, etc.) is connected via a transceiver directly to the bus.
Transceivers can be connected externally or located internally in the microcontroller. A
transceiver has the task of taking the data, bit by bit, from the bus and also to write to the
Bus.
The transceivers communicate with the two ports RX (Read) and TX (Write), which are
depicted in the image above.
The transceiver performs the following tasks:
Protection against overvoltage
Amplify signals
Level adjustment
Bit encoding / decoding
Synchronization
Bit time - determination

The transceiver has a transistor for CAN High and CAN Low on each line. For CAN High
there is a PNP transistor to protect against Voltage and, for CAN LOW there is an NPN
transistor connected to GND. This allows three states as shown in the table below:
BIT SYNCHRONIZATION
Nodes on the Bus does not transmit at the same clock speed. The nodes usually have
different crystals and therefore have different clock frequencies.
All nodes know at what data rate they have transmit at on the CAN Bus. For example,
500kBit/s the bit length is known. It is at 500kBit/s 2µs.
All the nodes must be synchronized to the same time points and scan the Bus in order to
recognize the same bit within the 2µs. If they were not synchronous, the nodes might fail
to recognize different bits.

Figure 17 Bit timing


CAN CONTROLLER (DATA LINK LAYER)
The transceivers are connected to the CAN controller. The CAN controller forms the
second layer, called the Data Link Layer. CAN Controllers have the task of processing the
CAN protocol. This includes the generation of a transmission frame, satisfying the
requirements of the Bus with the necessary recognition of the Bus state (free, busy), and
possibly the implementation and continuation of access (decentralized arbitration). The
following list show the tasks of a CAN Controller:

Send
Receive
Frame encode
Frame decode
Parallel-serial transformation
Bit stuffing
Reconversion

Figure 18 Node - CAN Controller - Transceiver – Microcontroller


CHAPTER 3. CAN BUS PROTOCOL
DATA FRAME
The data frame is transmitting actual user data (Signal) with additional information. User
data is created in the microcontroller and is sent to the CAN Controller where additional
information is added and sent over the transceiver to the Bus. This additional information
contains all the other frames except the data frame.

Figure 19 Frame Process

The image below shows the complete CAN Frame.

Figure 20 Data Frame


START OF FRAME (SOF)
Start of Frame (SOF) is always dominant logic zero. It indicates the beginning of the
frame. SOF bit shall not be sent before the Bus is in the idle state. The idle state is present
if a sequence of 11 recessive bits are on the Bus.
1 ACK-Delimiter + 7 EOF + 3 ITM
IDENTIFIER
CAN Bus 2.0A defines a standard frame with an 11-bit identifier. 11-bit is the number of
the message. Thus 2,032 different messages can be encoded. 16 ID numbers are reserved
for special messages. The CAN 2.0B defines an extended frame format with 29 identifier
bits, which can encode 536,870,912 different messages.
ARBITRATION FIELD
The arbitration field is used to resolve Bus conflicts that occur when several devices
simultaneously send messages on the Bus. During the arbitration phase, each transmitting
device transmits its identifier and compares it with the existing level on the bus. If the
levels are equal, the device continues to transmit its identifier. If the device detects a
dominant level on the bus while it is trying to transmit a recessive level, it stops
transmitting and becomes a receiving device. After the arbitration only one transmitter
continues to send the remainder of its frame bits.
So let’s have a look at the following example:

Figure 21 Identifier

Node A (Identifier 0x150), Node B (Identifier 0x350) and Node C (Identifier 0x200) will
simultaneously send a message to the Bus. Here, the bits of each node are consecutively
(Bitwise) sent on the Bus, (from bit 11 to bit 1). The recessive level of a bit is (Logical ”
1”) and dominant levels (Logical “0”). The recessive bit is overwritten without
transmission to interfere or cancel.
Next step you can see the removal from Node B and C.
On bit number 10 you can see that Nodes B and C have recessive bit and lose the
arbitration to Nodes A and D. From now on Nodes B and C are in receiving mode.
Node A and D are still in the transmission mode.
In the next step you can see that Node D is losing to Node A because the RTR bit from
Node D is in recessive state and from here Node A wins the arbitration and has now the
Bus access. All other Nodes are in listening state.
CAN BUS 2.0A & 2.0B (STANDARD/EXTENDED)
The format of the Arbitration Field is different for Standard Format 2.0 A and Extended
Format 2.0 B Frames.

Figure 22 CAN 2.0 A and 2.0 B

The Standard Format consists of an 11-bit identifier and the RTR-Bit.


The Extended Format consists of a 29-bit identifier, the SRR-Bit, the IDE-Bit and the
RTR-Bit.
In order to distinguish between Standard Format and Extended Format the IDE bit for
CAN Bus 2.0 A (Standard) is dominant and for the Extended Format, CAN Bus 2.0 B is
recessive bit.
The Extended Format comprises two sections:
Base id with 11 bits
Extended id with 18 bits
The extended format has some trade-offs:
The bus latency time is longer
Messages in extended format require about 20% more bandwidth
The error detection performance is lower because there are more bits in a frame
and the CRC calculation takes longer time
RTR FIELD
Remote Request Frame (RTR) is 1 bit long and indicates the mode of a frame. If RTR is
recessive bit 1, that means it request a data frame with the identifier. RTR 0 means it is in
transmission mode. It sends the message of the identifier.
CONTROL FIELD
The Control Field follows after the Identifier and RTR bit . It is 6-bit wide and consists of
the IDE-Bit, Res.-Bit and Data Length Code (DLC) bits.

Figure 23 Control Field

The IDE bit is set to identify which CAN Bus protocol is sending over the Bus. CAN 2.0
A standard protocol will have IDE = 0 and CAN 2.0 B extended protocol will have IDE =
1.
DLC indicates the number of bytes in the transmitting message. The maximum length is 8
bytes.
Res Bit stands for reserve bit and is used for development purpose of the CAN Bus. Both
recessive and dominant states will be accepted by the receiver node.
DATA FIELD
This is the actual information which is sent over the Bus and has a maximum length of 8
bytes or 64 bits. The data field is created in the microcontroller. One CAN Bus message
could contain maximum 64 different Boolean signals.

Figure 24 Random 8 Byte Data Message


CRC FIELD
After the data field follows the first 15 -bit CRC field (Cyclic Redundancy Check) for
error detection. CRC Field calculates CRC using all bits from SOF to data field and places
the calculated CRC value after the data field.

Figure 25 CRC

Every receiving node on the Bus calculates the CRC based on the transmitted frames and
compares it with the transmitted CRC value. A CRC error will occur if the value is not the
same.
The CRC Check is used solely for error detection and not for error correction.
ACK FIELD
This field enables the sender to check whether the transmitted data were received correctly
by the recipient node. ACK Field consists of 1 Acknowledge Bit and 1 Delimiter Bit. The
transmitting node expects a dominant bit.

Figure 26 ACK

Error occurs when the receiving node reads a recessive bit.


EOF FIELD
The completion of the data message is completed by the 7 recessive bits EOF (End Of
Frame).

Figure 27 SOF

In addition, there are 3 last recessive bits ITM (Inter Frame Space). These 3 bits are used
in the processing time of a node to receive the data. These 3 bits identify the minimum
distance between two frames, leaving the CAN controller time to write the decoded data in
the receive buffer. The ITM bits and SOF bit are also used for synchronization.
ACCEPTANCE FILTER
Data frames contain the most important information on the CAN Bus. Nodes or modules
connected to the network can send and receive data.
When a particular node wants to transmit sensor values or other information to other
nodes on the CAN network, it needs to populate a data frame. The data frame includes an
identifier, data bytes (content of the message) and error checking bits.
Acceptance Filter resides in CAN Controller and serves to reduce the amount of data to be
processed. Each node can be programmed to select incoming data that are relevant for
their usage and functionality and restrict irrelevant CAN messages. This procedure is set
by the acceptance filter.

Figure 28 Acceptance Filter


ACCEPTANCE FILTER EXAMPLE
Here is an example how it works, and what you need to know. First, I will explain:
1. Acceptance Mask Register (Filter)
2. Acceptance Code Register (Mask)

Figure 29 Acceptance Mask

ACCEPTANCE MASK REGISTER – FILTER


In the Acceptance Mask Register, bits are set to a specific value of either 1 or 0. The
number indicates which locations in the Acceptance Code Register are relevant for the
filtering and which are not. Bits with 1 are irrelevant and Bits with 0 are relevant for the
filtering.

ACCEPTANCE CODE REGISTER – MASK


Masks are used to filter out the amount of incoming messages. Also, here you have to set
the value of the location with either 0 or 1 to identify which values have to be evaluated.
Let’s jump over to an example to make it clear.

EXAMPLE:
Your CAN Bus Node should only receive Rx ID of 0x0AA.

Figure 30 Example - Acceptance Filter


You can see the acceptance filter example in the snippet of code below.
CHAPTER 4. ERROR HANDLING
INTRODUCTION
In theory everything has gone smoothly, but what happens when errors occur in the
network? Network errors can include:
1. One or more bits are changed during transmission
2. A node cannot send
3. A node sends constantly without interruption (a “babbling idiot”)
4. There is a cable break
5. Etc.

Figure 31 Error
TROUBLESHOOTING
The CAN nodes are all equally responsible for the Bus access. This also applies to error
handling and error monitoring. Each node is responsible for itself. An error occurring at a
node will stop the whole Bus system from sending.
Error Generating -> Error Detection -> Error Handling -> Error Isolation
The CAN protocol can detect and signal errors. To do that,, three mechanisms at the
message level and two mechanisms at the bit level are required.


FAULT DETECTION – CRC CHECK
The CRC Check (Cyclic Redundancy Check) verifies the information of the frames. The
transmitting node calculates the CRC using all frames from SOF to the end of the data
field and places this value into the CRC frame.
The receiving node also calculates the CRC value and compares it with the CRC frame
from the transmitted node.
If the value is not equal an error flag is raised.

Figure 32 CRC Check


FAULT DETECTION – FRAME CHECK
The Frame Check monitors the structure of the transmitted frame by the bit fields with the
predetermined fixed format and the frame length.
FAULT DETECTION – ACK ERROR
All receiving nodes are sending a positive ACK (Acknowledgement), which indicates an
error free signal. The transmitted node expects to receive a dominant bit. A recessive bit
will raise an error flag.
FAULT DETECTION – BIT MONITORING
The transmitting node monitors the bit level on the Bus and compares it with the
transmitted bit level. If the level is not the same an error flag is raised. This kind of error
will not occur during the arbitration phase, because here we can have different signals
simultaneous to be in contact with.
FAULT DETECTION – BIT STUFFING
Bit stuffing is used to maintain synchronization on the Bus. The idea behind bit stuffing is
to insert after 5 consecutive bits with the same polarity an opposite bit (Bit stuffing bit) on
the Bus. A Bit stuffing error will be raised if 6 consecutive bits with the same polarity are
received by a node. A Bit stuffing error will not occur if an error frame or an overload
frame is sent.
ABOUT THE AUTHOR

Vitali Mueller is an Automotive Software and Machine Learning Engineer. He started his
career in 2005 as Mechatronic for MAN Truck & Bus in Germany. In 2009, he traveled to
Australia and worked in Brisbane as an Automotive Consultant for Ultimate Car care
workshop. He was involved in two Formula Student Projects during his Automotive
Engineering studies and today he is working for a British Automotive Company as a
Software Engineer. He is also an online educator for Automotive Industry and active
blogger on vitalimueller.com.
ONE LAST THING…
If you enjoyed this book or found it useful, I’d be very grateful if you’d post a short
review on Amazon. Your support really does make a difference and I read all the reviews
personally so I can get your feedback and make this book even better.
If you’d like to leave a review, then all you need to do is click the review link on this
book’s page on Amazon here:
https://www.amazon.co.uk/review/create-review/ref=cm_cr_dp_no_rvw_e?
ie=UTF8&asin=B01KD30DVE&channel=detail-
glance&nodeID=341677031&store=digital-text
Get the video training course on Controller Area Network Projects at:
vitalimueller.com/courses

Thanks again for your support!

You might also like