The Controller Area Network (CAN) norm defines a fast and robust serial bus protocol, suited
for local networking of intelligent devices such as microcontrollers, sensors and actuators. It is
now widely used, mostly in the automoti ve dom ain, but also for hom e automation and i ndustrial equipment control.
Several members of the ST7 MCU family have a built-in CAN peripheral named pCAN, which
allows them to be used as nodes in a CAN network. A software driver provided is by ST to help
you start designing and writing applications using the ST7 pCAN cell.
The purpose o f t he follow ing ap plicati on note is to ex plain to y ou how t o u se the dri ver, and
how it works. Thus, you can either build your software from the provided files, or modify them
to meet specific needs.
You will find in this application note:
– a brief description of the CAN protocol
– an overview of the pCAN peripheral
– the complete description of the user interface
– the step-by-step development of an example application using the driver features
– a technical report including a description of algorithms and internal data types
In the early 80s, electronic appl icati ons appeared i n the automotive world. The need gradually
arose to establish real-time communications between various types of on-board equipment.
In 1986, the CAN bus protocol, designed by Robert Bosch GmbH, was presented to the public
for the first time. In 1989, the first silicon implementing the protocol was issued and in 1991,
the first car equipped with a CAN network was produced.
Today, the protocol is an international norm (ISO 11898). Its relative simplicity, the wide availability of products and services in terms of chips, softwar e libraries, starter kits, cour ses and
training makes the development of applications relatively fast and cheap.
The CAN p rotocol prov ides t he user with very r eliabl e comm unicati on, with a po werful e rror
detection/confinement m echanism. It allows baud rates up to 1Mbaud (for networks o f up to
40m) which makes it able to support real time applications. The bus can of course be configured with lower speeds for larger networks (50kbaud for networks up to 1km long for example).
There were more than 150 million CAN nodes installed at the beginning of 1999.
1.1 GENERAL CHARACTERISTICS
1.1.1 Prot oc ol pr ope r ties
■ Asynchronous serial bus (See “Bit timing” on page 9)
– No clock signal is transmitted, allowing a tw o-wires (high speed CAN see ISO 11898) or
even one-wire communication (low speed CAN, see ISO 11519)
– Each node resynchronizes itself on every falling edge occurring on the bus.
■ CSMA/CA (Carrier Sense Multiple Access/Collision Avoidance)
– Several nodes can request the bus simultaneously (CSMA).
– When such a situation occurs, there is no loss of data and the mes sage with the highest
priority is immediately sent (CA).
■ Multimaster capability (See “Arbitration Phase” on page 10)
– Every CAN node in the network is able to transmit data.
– The arbitration mechanism is decentralized.
■ Object oriented communication
– Each message on the bus carries its own identifier which is an 11-bit (or 29-bit) number.
This field describes the content of the message. It is not an address.
– Consequently, a transmitter doesn’t address data to a peer but simply broadcasts its data.
Each node in the network picks off data from the bus when it recogn izes an identifier that
concerns it.
4/100
ST7 pCAN PERIPHERAL DRIVER
■ Message prioritization
– The identifier of a message also indicates the priority of its carrier. During the arbitration
phase, a bitwise comparison of the different identifiers is performed. The message with the
higher identifier being the more urgent, it wins the arbitration and is immediately transmitted.
■ Error management system (See “Error Mana gem ent” on page 11)
– Detection: every node continuously monitors the bus, even if it is not concerned by the cur-
rent transmission, to detect potential violations of the protocol.
– Signalization: any node detecting an error, signals it to its peers and aborts the current
transmission meanwhile. The sender automatically retries transmission within a certain
amount of time. Thus, the consistency of data throughout the network is preserved.
– Confinement: each node implements counters which are incremented (or decremented)
after each detection of an error (or successful operation). A defective station can then
switch itself off when its counters reach a certain value, and thus stop disturbing the bus
operations.
1.1.2 CAN in the OSI reference mo del
The protocol occupies parts of the two lowest lev els (t he physical and data link layers) of t he
7-level ISO/OSI (Open System Interconnection) telecommunications reference model.
Table 1. ISO/OSI Standard Telecommunication Layers
In this reference model, the data link layer deals with physically passing data from one node to
another. It define s arbitrati on, me ssage f raming, er ror m anagem ent a nd tr ansmission timing
for example.
The physical layer deals with putting data on the physical network, and with taking it off. Consequently, it defines signal levels and timings, as well as the transmission support (wire types,
connectors, etc.).
The CAN protoc ol splits the Data L ink lay er into Object and Transfer sublayers, corre-
sponding to the ISO/OSI Logical Link Co nt rol and Medium Access Control sublayers. The
Transfer l ayer is the interf ace betw een the user ap plic ation an d the CA N. The Objec t layer
5/100
1
ST7 pCAN PERIPHERAL DRIVER
manages frame s ha ping and a ckno wle dgm ent m e chani sms, b us a rbit ration an d check s t he
formal correctness of the data transmitted and received.
The physical layer is only partly defined, and the user is free to choose the transmission medium for example.
Figure 1. Layered architecture of CAN (ISO 11898 definition)
Data Link Layer
Logical Link Control
Acceptance filtering
Overload Notification
Recovery manageme nt
Medium Access Control
Data encapsulation/decapsulation
Frame coding (stuff/destuff)
Medium access management
Error detection
Error signaling
Acknowledgement
Serialization/Deserialization
Fault confinement
(MAC-Layer Management Entity)
Physical Layer
Physical Layer Signaling
Bit encoding/decoding
Bit timing
Synchronization
Physical Medium Attachment
Driver/Receiver characteristics
Medium Dependent Interface
Connector
Bus Failure Management
(PLS-Layer Management
Entity)
1.2 CAN FRAME
There are four different CAN frame types: Data frame, Error frame , Remote frame and
Overload frame
There are also two versions of the CAN protocol: 2.0A (or base format) and 2.0B (or extended
format). The 2.0B standa rd introduc es a n ex ten ded data fr ame with a longe r identifi er. B oth
frame types coexist on a CAN 2.0B bus, and its nodes must be at least able to recognize and
acknowledge both.
We will only describe here the 2.0A format, or base format.
1.2.1 CAN Data Frame
The CAN Data frame is used for data transmission and contains the following fields:
■ A start of frame field, consisting of one bit.
■ A 12-bit arbitration field, including:
– An 11-bit identifier
6/100
ST7 pCAN PERIPHERAL DRIVER
–A RTR bit used to differentiate data and remote frames. It is dominant in a data frame.
■ A 6-bit control field, including:
– A 4-bit data length code bits giving the size (in bytes) of the data field
–1 IDentifier Extension (IDE) bit ( dom inant for CAN 2.0A frame) and 1 bit reserved for fur-
ther development.
■ A data field of up to 8 bytes.
■ A 16-bit long CRC field. The Cycli c Redundancy Check (CRC) is based on a BCH encoding.
■ A 2-bit acknowledgment field. The transmitters sends it as all recessive. (See “Message
Acknowledgement” on page 11)
■ A 7-bit end-of-frame field.
The interframe space (or Intermission) is the minimum amount of time between two consecutive transmissions.
Figure 2. CAN Data Frame
19 bits
Arbitration Field
Control
Field
0..64 bits
Data Field
CRC Field
25 bits
EOFACK
Interframe
Space
R
11-bit Identifier
DLC
Data
15 bits
7 bits
3 bits
Bus Idle
D
CRC
ACK Delimiter
ACK Slot
SOF
RTR = 0
Delimiter
IDE = 0
1.2.2 CAN Remote Frame
The CAN Remote frame is used to request data. This frame has the same overall constitution
as the data frame. However, in this case, the Rem ote bit (RTR) i s recessive and there is nodata field.
7/100
ST7 pCAN PERIPHERAL DRIVER
Figure 3. CAN Remote Frame
19 bits25 bits
Arbitration Field
IDE = 0
Field
DLC
15 bitsBus Idle3 bits7 bits
CRC
Delimiter
R
11-bit Identifier
D
RTR = 1
SOF
EOFACKCRC FieldControl
ACK Delimiter
ACK Slot
Interframe
Space
1.2.3 CAN Error Frame
The CAN Error frame is sent by a node as soon as it detects a protocol violation in the current
operations on the bus. This frame is composed of 6 successive dominant bits (active error
flag) or recessive (passive error flag), followed by 8 recessive Frame Delimiter bits. The cur-
rent error state of the node sending the error frame (See Section 1.5 "Error Management") will
determine whether it is an acti ve frame (node i n error active state) or a passive frame (node in
error passive state).
1.2.4 CAN Overload Frame
The CAN Overload Frame can be sent during the interframe space to delay the next transmission on the bus. This frame has the same constitution as the active Error frame.
Figure 4. CAN Error/Overload Fram e
Max. 12 bits
Data Frame
R
D
Error/Overload
Flag
6 bits
Error Detection
Error/Overload
Delimiter
8 bits
Interframe
Space
3 bits
Bus Idle or Data Frames
1.3 PHYSICAL REPRESENTATION OF DATA
The CAN data is enco ded w ith NRZ (Non Re turn to Z ero) c ode. The tw o logical l evels us ed
are named dominant ( 0) and recessive (1). Because the CAN cells are connected on the bus
according to the wired-AND principle, it follows that the default bus state is recessive, and that
8/100
ST7 pCAN PERIPHERAL DRIVER
transmission of a dominant bit forces this state to dominant, no matter how many other nodes
are transmitting recessive bits.
1.3.1 Bit Stuffing
Once built, a frame is passed t o the T ransfer sub-layer, where the CRC is calculated. Then,
Stuffing Bits are inserted in the frame . Each time fiv e conse cutiv e bits of th e same logical
level are detected, a bit of the opposite value is inserted. This is used to generate a minimum
edge rate on the bus for resynchronisation purpose (See “Bit timing” on page 9).
The CAN standard divides the bit time into four segments:
– A synchronisation segment (SYNC),
– A propagation segment (PROP),
– A phase buffer 1 segment (TSEG1),
– A phase buffer 2 segment (TSEG2),
– Each segment is divided into time quanta. The synchronisation segment lasts, by defini-
tion, 1 time quantum.
Figure 6. CAN Bit Segm ents
Previous
Bit
Bit Time
SYNCPROPTSEG1
TSEG2
Sample Point
Next Bit
The CAN communication is asynchronous, i.e. no clock signal is sent together with data. Each
node in the network maintains its own bit timing calculated from the internal clock of the device.
9/100
ST7 pCAN PERIPHERAL DRIVER
To deal with signal phase variations on the transmission line due mostly to desynchronization
between clocks of bus participants, TSEG1 and TSEG2 are of variable length. A resynchronization of the local clock occurs on every r ecessive-to-dominant state change. If such a change
arises before (or after) the SYNC segment expected by the cell, TSEG1 (or TSEG2) is lengthened (or shortened) to correct the detected variation. If the edges occur during the SYNC segment, the node assumes that it is synchronized.
The PROP segmen t takes into accoun t the m axim um propag ation ti me of the si gnal on the
network, ensuring that all the nodes sample the same bit at the same ti m e .
The sampling point of the bit takes place between TSEG1 and TSEG2.
1.4 ARBITRATION PHASE
1.4.1 Arbitration Phase
All the cells connected on the CAN network are likely to transmit a message at any time. A cell
can initiate a transmission only when the bus is idle. On transmission of a message, a cell simultaneously monitors the state of the bus to detect potential problems.
If the bus is idle, any cell that is ready for transmission begins to send its data. The other
nodes listen.
If the bus is already in use when a cel l requests i t, the cell waits u ntil the end of the curr ent
transmission. Then, all the nodes that are ready to transmit begin their transmission. If a dom-
inant and a recessive bit are sent in the meantime, the first one erases the second. This
causes the cell that is sending the recessive bit to lose the arbitration and switch to Reception
mode. This way, messages with the highest identifiers are sent before the others. This mechanism also prevents collisions occurring on the bus, which saves bandwidth. This is referred to
as non-destructive bitwise arbitration.
Figure 7. Arbitration example: node 1 win s
Node 1
Node 2
Node n
CAN Bus
Recessive
Dominant
10/100
ST7 pCAN PERIPHERAL DRIVER
1.4.2 Message Acknowledgement
Any cell having received a message correctly, regardless of the result of the acceptance test,
must acknowledge it by sending a dominant bit during the ACK slot of the current frame, thus
overwriting the recessive bit sent by the current transmitter.
1.5 ERROR MANAGEMENT
The Error Management System of the CAN protocol i s proof of the protocol’ s robustness. T his
system provides a way to automatically distinguish permanent failures from sporadic errors. It
can lead to self-disconnection of a failing node from the bus. This feature i s named Error Con-finement. An error is defined as a violation of one of the protocol’s rules. It can happen after
one of following events:
Bit error:
–
A transmitter detects a difference between the actual bus state and what it
sends.
–
Acknowledgement error:
Stuffing e rror:
–
–
CRC error:
–
Format error:
More than five identical bits were received consecutively.
The CRC received does not match the calculated CRC.
One of the f ixed -format fi elds ( CRC delimi ter, ACK delimi ter, End Of Frame )
A frame is not acknowledged (ACK slot recessive).
does not have the expected format.
An Error frame is immediately sent by all the cells that have detected an error on the bus. Note
that the Error frame does not yield to the Stuffing r ule. Upon reception of this frame, al l cells in
the network detect a Stuffing error and react by sending an Error frame. The dominant state of
the bus caused by the occurrence of an error can last at most 12 bits (case when a node detects the error only at the end of the error flag).
The Error Confinement system is based on two counters:
– A TransmissionError counter (TEC)
– A ReceptionError Counter (REC)
The rules handling the counters are basically the following:
– When an emitting node detects an error, it increments its TEC and sends an error frame.
– When a receiving node detects an error it increments its REC and sends an error frame.
– When a transmission is successful, the TEC counter is decremented.
– When a reception is successful, the REC counter is decremented.
Note: The complete set of rules is quite complicated taking into account the possibility of receiving over-
load frames, etc. Consequently, it’s beyond the scope of this document. This docume nt describes
the basic reactions of the cell. For more information, refer to the original Robert Bosch GmBH document or to the ISO 11898 norm.
The behaviour of the cell con cerning the sta te of the counters is sho wn in the following dia gram.
11/100
ST7 pCAN PERIPHERAL DRIVER
Figure 8. CAN Error States
Error Active
128 blocks of 11 successive recessive b its
TEC<127 and REC<127
Bus Off
When both counters contain values between 0 and 127, the CAN node is in Error Activestate, which means that it can send and receive normally. If it detects an error, it will send Active Error flags.
When one of the two c ount ers rea ches a value bet ween 12 8 and 2 55, th e node is in ErrorPassive state. It will go on receiving and sending normally but will only be authorized to send
Passive Error flags. Therefore, if this node causes trouble by sending unjustified Error frames,
it will not disturb the network for too long.
When one of the counters reaches a value over 255 ( i.e. it overf lows), the CAN node enters
Bus Off state. It is then physically disconnected from the bus. It can go back to Active mode
if it successfully detects 128x11 consecutive recessive bits on the bus.
TEC >255
TEC>127 or REC>127
Error Passive
1.6 ST7 PCAN PERIPHERAL
1.6.1 Main Features
The ST7 pCAN peripheral implements a CAN 2.0B passive protocol. This means that extended frames are recognized and acknowledged, but cannot be saved nor processed by the
microcontroller.
– The pCAN peripheral is based on three 10-byte hardware buffers that can be used either
for transmission or reception. They are prioritized in the increasing priority order 1 to 3 for
transmission and 3 to 1 for reception. Each buffer has a control register indicating if a job is
pending, if new data has been received or if the buffer is currently being written/read. A bit
in this register is used to lock the buffer for transmission (See ST72511 datasheet p.116).
– The baud rate is programmable up to 1 Mbps. The length of the bit synchronisation fields is
also programmable. The baud rate is configured by setting three values: the size of time
quanta (in clock ticks) and the length of the two synchronization segments (in time quanta).
See ST72511 datasheet p.114, Baud Rate Prescaler Register and Bit Timing Reg ister.
12/100
ST7 pCAN PERIPHERAL DRIVER
– Two 11-bit filters and two 11-bit masks are used for hardware filtering with identifier/iden-
tifier-range definition. The masks define which bits of the filters are to be ignored and which
are to be tested. Any message whose identifier does not match will not be saved in the buffers.
– The cell automatically enters Low Power mode after the reception of 20 recessive bits, or
Standby state on command.
– The pCAN peripheral can wake-up the ST7 microcontroller from HALT mo de. See Section
2.1.3.2 "Waking-up from HALT Mode" to learn how.
– The CAN Erro r Confinement feature, as defined by the CAN protocol, is fully implement-
ed, with read-only access to the counters and maskable interrupts on state changes. Once
in Bus Off state, the cell automatically returns to Bus Ac tiv e state if it has detected 128x11
recessive bits on the bus (see Section 2.1.3.1 "Controlling Status Changes"). See note on
Section 2.1.3.2 "Waking-up from HALT Mode" to see how the driver can provide you with full
control over the bus-off to bus-active transition.
– The three Send/Receive buffers, filters, masks and counters are mapped at a unique ad-
dress space, allowing efficient software access.
1.6.2 Cell Behaviour
In Standby state, the node monitors the bus in order to detect a dominant pulse that could generate an interrupt (See ST72511 datasheet p.112, Interrupt Control Register, SCIE bit).
When the RUN bit of the Co ntrol Status Regi ster is set (See ST 72511 datasheet p.113), the
cell leaves
standby
mode. It then enters
resynchronization
mode before it r eally starts running.
If the WKPS bit of the Control/Status Register is set, then the cell will send a dominant pulse
when it wak es up . You c an choos e bet ween two resyn chron ization duration s: 11 recessiv e
bits if the FSYN bit of the C SR is set or 128*11 recessive bi ts if not (See ST72511 datasheet
p.113).
If the cell resynchronizes after leaving bus-off st ate, it will wait 128*11 recessi ve bits, whatever
the value of FSYN may be.
To send data, a buffer has to be selected first by writing to the Page Selection Register (See
datasheet p. 114). Then it has to be locked for transmission by setting the LOCK bit in the
Buffer Control/Status Register (See datasheet p.116: LOCK bit and RDY bit). Then data can
be written in the buffer registers: identifier, data length code, data bytes. Writing in the seventh
data register starts transmission.
Received data is automatically stored in one of the buffers configured for reception (LOCK bit
reset) each time a message identifier matches the hardware filters of the pCAN cell, and provided th at thi s b uff er is m ark ed as fre e (R DY b it res et. Se e dat ashe et p .116: L O CK bit a nd
RDY bit). The masks/filters can be configured through the Filter/Mask High/Low Registers
(See datasheet p.117).
13/100
ST7 pCAN PERIPHERAL DRIVER
Any event (succ essfu l transm ission , data recep tion, er ror, s tate ch ange , overru n) can generate a maskable interrupt. The Interrupt C ontrol Regis ter (see datasheet p.112) al lows you to
set/reset these masks. Note that each buffer has its own reception interrupt, allowing the data
to be saved rapidly.
Note: For further, more detailed explanations, please read the ST72511R/ST72512R/ST72532R Datash-
eet, downloadable from the ST web site, http://mcu.st.com.
Figure 9. ST7 pCAN State Diagram
RESET
RUN
Transmission
RUN
& WKPS
FSYN & BusOFF
(FSYN
TX Error
| BusOFF) & 128*11 Recessive bits
TX OK
Standby
RUN
Resynchronisation
& 11 Recessive bits or...
Idle
RX OK
Arbitration lost
RUN & WKPS
Wake-up Pulse
Generation
Start of frame
Reception
RX Error
14/100
BusOFF
Error
BusOFF
ST7 pCAN PERIPHERAL DRIVER
2 CAN DRIVER
To quickly start developing your own CAN applications using the ST7 pCAN peripheral, STMicroelectronics provides you with a driver. The source code (can.h and can.c) is given as an example, and can therefore be used as provided or be modified to fit specific needs.
There are two customizatio n files which make the dr iver’s f unctionality flexib le a nd able to
meet a wide range of needs.
The entire processing is interrupt driven, so no polling is required. The application is notified of
CAN events through function calls from the interrupt routine.
To immediately use the driver, without modifying its structure, see Section 2.2 "How to Use the
CAN Driver: A Dem o Applicat ion" .
The following sections will explain the details of the driver architecture and describe all the
functions and data types implemented in the software.
2.1 USER INTERFACE
2.1.1 Files Furnished
The driver consists of five files:
– can.c. Driver function definitions and internal data types. This file may not be modified.
– can.h. Header file of can.c. This file may not be modi fied.
– can_hr.h. Hardware description (register mapping of the ST7 MCU memory space). This file
is hardware dependent and must not be modified.
– can_custom.c. Frames of customization functions. They are called (some optionally) by the
driver to notify the application of events when some user-specific processing is required (for
example on reception of data). This file has to be completed by the user.
– can_custom.h. Contains a pre-processor directive list (
#define
types) which allows user
customizations to be taken into account at compilation time. T his file has to be m odified by
the user.
2.1.2 Architecture
The cell is statically configured with one transmi ssion buffer and two reception buffers, which
reduces the need for processor responsiveness in reception.
For the same purpose, a 3-message deep transmission FIFO is implemented. It is not accessible by the user, and is automatically managed by the software.
The entire processing is interrupt driven. The user can choose which interrupts are to be taken
into account and which are not, due to the compilation options in can_custom.h. Some interrupts request an immediate answer from the application, e.g. a reception event. To avoid
having the user modify the interrupt routine (in can.c), the routine calls one of the notification
15/100
ST7 pCAN PERIPHERAL DRIVER
functions defined in can _custom. c on c ertain ev ents . Th e user only has t o enter these func tions according to his needs before compiling the software.
2.1.3 Principle of Use
During compilation, the values of the hardware control registers are calculated by the preprocessor according to the compilation options selected in can_custom.h.
If the software filtering feature is enabled, the values of accepted identifiers hav e to be entered
by the user as a list in can_custom.h (See “Filtering” on page 29)
The functions in can.c are compiled or not, according to the selected
unwanted ones are simply left as comments).
Figure 10. Driver Customization System
CAN_CUSTOM.H FILE
#define INIT_BRPR 0x11
...
#define STATUS_CHANGE_NOTIFICATION
...
//#define DEBUG
CAN_CUSTOM.C FILE
#ifdef STATUS_CHANGE_NOTIFICATION
void CAN_Bus_Passive_Notification(void)
{
//To implement if defined
}
#endif
...
...
#ifdef DEBUG
void CAN_Overrun_Notification(void)
{
//To implement if defined
}
#endif
Compilation
Compiled
Not Compiled
BRPR Reg ister
ST7 Registers
#define
0x11
directives. (The
Compilation
During the first initialization (performed using the CAN_First_Init function), the periph eral’s
registers are written with the values defined at compilation time, the transmission FIFO is initialized and the cell starts (a wake up by bus can be chosen).
Then:
– The
CAN_Transmit_Request
function initiates a transmission which begins with an in-queuing of the message to be sent. Then, hardware buffer no.1 (the static transmission buffer ) is
filled according to hardware requirements. (See Section 1.6.2 "Cell Behaviour").
16/100
ST7 pCAN PERIPHERAL DRIVER
– The
CAN_Switch_Off
and
CAN_Sleep
functions are used to switch the cell to Standby mode.
The first function kills any pending jobs and erases all data in the reception buffers, even if
the data is unread. The second function is executed the same way as long as no work is in
progress, the transmission FIFO is empty and all reception buffers have already been read.
These two functions also define the way the cell will be woken-up: either by bus or by software (by enabling or disabling the corresponding interrupt). They can help you to manage
status changes by controlling the transition between Bus Off and Bus Active states (See Sec-
tion 2.1.3.1 "Controlling Status Changes").
–
CAN_Switch_On
resets the cell and returns to RUN mode. It can also place the cell in a state
waiting for a dominant pulse to be woken-up.
–
CAN_Get_Status
–
CAN_Get_TEC
–
CAN_Get_REC
returns the current status of the peripheral (run, standby, error passive...)
returns the current content of the transmission error counter.
returns the current content of the reception error counter.
2.1.3.1 Controlling Status Changes
Your application can be notified by the dri ver when the error state of the cell changes . (See
“Compilation Options” on page 25). If you don’t want the microcontroller to directly resynchro-
nize after leaving bus-off state for example, you can call the CAN_Switch_Off function from inside o f the C AN _Bu s _Off_Notifica ti on fu nc tion ( Se e “C an_cus tom.c Fil e” on page 26), then
perform any operations you want before calling the CAN_Switch_On function to restart the peripheral.
2.1.3.2 Waking-up from HALT Mode
If you want to switch the ST7 to HALT mode and have it woken-up by the CAN, the correct interrupt routine must be enabled. Before switching to HALT mode, call the CAN_Sleep or
CAN_Switch_Off function with the BUS_WAKEUP parameter that is used to enable the CAN
interrupt on the bus dominant state while in Standby state.
Then, enter the CAN_Dominant_Bit_Reception_Notification function to customize the waking
up of the microcontroller.
Note: See ST72511 datasheet p.37 for more information about HALT mode.
2.1.4 Interrupts (ITs)
Once the interrup t r outin e is enter ed, th e f irst thi ng you wan t t o kno w is “Wha t t rigger ed the
event?” Priority is then given to reception if more than one IT has occurred simult aneously, unless the DEBUG compilation option was set. In this case, the Error ITs are processed first.
– In the event of a Transmission IT, the driver tries to send the following message in the queue,
if it’s not empty. The driver then notifies the application of the event before leaving the routine.
17/100
ST7 pCAN PERIPHERAL DRIVER
Figure 11. Transmission IT Proced ure
What
you
see
Application
3
Notification
Error notification, only
5
if DEBUG defined
ST Driver
4
Fills buffer
with next data
Driver
Processing
1
IT
2
Clears flags
ST7 Hardware
Successful
Transmission
CAN Bus
– In the event of a reception IT, after having found which buffer is i nvolved, the dri ver performs
an optional software filtering, then noti fies the application. If the cell r eceived a remote frame,
the CAN_Remote_Reception_Notification function is called. Otherwise, if the cell received
data, the CAN_Request_Buffer function is called to request a buffer from your application.
After the buffer is filled, the dr iver calls the CAN_Data_Reception_Notification function to notify you that the data is ready. If the DEBUG option is set, the CAN_Reception_Status function is called just before leaving the IT routine, which passes the status of the reception
processing procedure (Error, Success...) as a parameter. This is used to detect the causes
of any problems. See “Can_custom.h File” on page 24 for more information about notification
routines.
Next
Transmission attempt
Figure 12. Reception IT Procedure
What
you
see
Driver
Processing
18/100
1
Notification:
2
Data or Remote
IT
Successful
Reception
3
Application
Notification
4
(case data)
5
ST Driver
Save data in software buffer
(case data) + clears flags
ST7 Hardware
CAN Bus
Buffer free for
reception
next
Error notification
Only if DEBUG defined
ST7 pCAN PERIPHERAL DRIVER
– Error ITs are only processed if the DEBUG option was chosen in can_custom.h. Then, the
application is notified of any other events through function calls. (Functions entered in
can_custom.c).
2.1.5 User Interface Description
This section describes the user interface in a “black-box” way. The parameters and the return
values of the function declared in can.h and can_custom.h are described in this section. For a
complete description of the algorithms and internal data type variables, please see Section 3
Software repres enta tion of C AN data . The trans latio n into hardwar e buffers is pe rform ed b y
the driver.
A variable of this data-type must be passed to the driver each time it is requested by the
CAN_Request_Buffer notification function (See “Functions called unconditionally” on
page 26). Otherwise, data in the hardware buffer will be lost.
A pointer to this structure i s also us ed as param eter of the CAN_Trans mit_Req uest function
(See “Functions” on page 21).
–
msg_identifier:
2 bytes field containing the identifier of the CAN message. The identifier is
stored in the 12 most significant bits. The 4 least significant bits MUST be zero. The u16
type means 2 bytes unsigned variable and is defined in lib.h.
–
data_size:
1 byte field containing the length of the data in the m essage (in bytes). The
CAN_Data_Size type is an enum type (See below for its description).
–
CAN_msg_data
: array of 8 bytes containing the data to be sent. The u8u16 type means 1
byte unsigned variable and is defined in lib.h.
–
buffer_rw
: this boolean variable is to be us ed as a flag to prevent simultaneous writing/
reading on the structure. It is checked and modified by the driver each time an operation
is being performed on the buffer. If CTRUE, the structure will not be read or written. If
CFALSE, it can be used. Always check/modify this variable in your application for this purpose.
–
buffer_free
: boolean variable used to mark if the data in the buffer can be overwritten or
not. It has to be used as the s ecurity by the user’s application. If C FALSE , the driver will
refuse to perform any write operation on the data in the structure and return an error code.
19/100
ST7 pCAN PERIPHERAL DRIVER
If CTRUE, the data can be modified. Take care to check and/or initialize it before passing
a buffer to the driver.
This structure contains the value of registers tha t can be reinitialized when switching on the
cell after a passage in Standby state (see Section 2.1.5.2 "Functions", CAN_Switch_On).
It is used for hardware initialization.
–
brpr_init
: value of the CANBRPR register (set length of a CAN time quantum in number of
CPU clock ticks). S ee “Bit timing” on page 9.
btr_init
–
: value of the CANBTR register (length of both time segments 1 and 2 in number of
time quanta). See “Bit timing” on page 9.
fhr1_init
–
–
flr1_init
–
mhr1_init
mlr1_init
–
–
fhr0_init
–
flr0_init
–
mhr0_init
mlr0_init
–
: value of Filter 1 High Register.
: value of the Filter1 Low Register.
: value of the Mask 1 High Register.
: value of the Mask 1 Low Register.
: value of Filter 0High Register.
: value of the Filter 0 Low Register.
: value of the Mask 0High Register.
: value of the Mask 0Low Register.
Enum -type variables
The names of the variables are in principle self-explanatory.
Error codes used in Reception functions. (See Section 3.2.2 "Internal Routines").
Note: With some compilers, an option is used to define the size, in bytes, of enum-type variables. We rec-
ommend selecting 1 byte, if possible, to save memory space.
You can see in which case the different error codes are returned by the functions by studying
the flow charts in Section 3.2.2 "Internal Routines" for internal functions and Section 3.1 "User
interface functions" for user interface functions.
You als o fin d th is info r ma tion i n t he a rr ays o f Section 2.1.5.2 "Functions" for user-interface
routines and Section 3.2.2 "Internal Routines" for internal routines.
CAN Cell Power-on initialization routine.
During its execution, all registers are initialized with values entered in can_custom.h
Description
CommentsCalls CAN_Init() (See Section 3.2.2 "Internal Routines")
or calculated from the compilation options chosen
It initializes the transmission queue.
This function must be called in the main routine prior to any use of the CAN cell.
Possible return values: CAN_INIT_FAILURE and CAN_INIT_SUCCESS.
void CAN_It_Dis(void):
Input-Output-DescriptionDisables all CAN interrupts.
Comments--
CAN_Status CAN_Get_Status (void):
Input-OutputCurrent status of the cell
Retrieves the current status of the CAN cell.
Description
CommentsUseful if the STATUS_CHANGE_NOTIFICATION option is enabled in can_custom.h
Possible return values: CAN_STANDBY, CAN_BUS_PASSIVE, CAN_BUS_OFF
and CAN_BUS_ACTIVE following the current state of the cell.
u8 CAN_Get_TEC(void):
Input-OutputValue of the TECR register (Transmission Error Counter)
DescriptionReturns the value of the TECR
Comments--
u8 CAN_Get_REC(void):
Input-OutputValue of the RECR register (Reception Error Counter)
DescriptionReturns the value of the RECR
Comments--
CAN_Switch_Error CAN_Switch_Off(WakeUp_Cause):
InputChip Wake-up function: BUS_WAKEUP or SOFT_WAKEUP
OutputError status
22/100
ST7 pCAN PERIPHERAL DRIVER
Puts the CAN node into Standby state.
This function aborts any pending transmissions and does not wait for the reception
buffers to be read. Then, it resets the driver in the same state as after power-on initialization.
If BUS_WAKEUP is selected, the next dominant bit detected on the bus will restart
Description
CommentsCalls CAN_Clean (See Section 3.2.2 "Internal Routines".)
the cell. If SOFT_WAKEUP is selected, the cell will not take the bus state int o account. It can only be woken up by the CAN_Switch_On function.
Possible return value: CAN_SLEEP_SUCCESS or CAN_FATAL_ERROR (if the
RUN bit fails to reset after a time out or if the CAN_Clean function fails).
There is a time out mechanism implemented in this function (about 30ms), waiting for
the RUN bit to be actually reset. So if your application uses the watchdog REFRESH
IT BEFORE calling the function
CAN_Switch_Error CAN_Sleep (WakeUp_Cause):
InputChip Wake-up function: BUS_WAKEUP or SOFT_WAKEUP
OutputError status
Puts the CAN node into Standby state.
Returns CAN_SLEEP_ ERROR if a tra nsmiss ion r equest is pending, or i f a hardware
receptio n bu ff er is still un s av e d.
Description
CommentsThis function will not reset the CAN node.
Possible return values:
CAN_SLEEP_ERROR if there are jobs pending in the hardware registers,
CAN_FATAL_ERROR if the RUN bit fails to reset after a time out,
or CAN_SLEEP_SUCCESS
CommentsCalls CAN_Init (See Section 3.2.2 "Internal Routines").
Pointer on an Init_Data structure (See Section 2.1.5.1 "Data-type Variables"),
Boolean (CTRUE, CFALSE)
Puts the CAN node into Active state
The Boolean is used to transmit a dominant pulse (CTRUE) or not (CFALSE) upon
wake-up.
The bit timing and the mask/filter parameters can be reinitialized in this function. In
most cases, the cell will be initialized the same way as in the Power-on sequence.
So, you can re-use the first_init_data structure is declared in can.h.
Possible return values: SWITCH_ON_SUCCES and SWITCH_ON_FAILURE.
Input Pointer to the CAN message to be sent
OutputError status
23/100
ST7 pCAN PERIPHERAL DRIVER
Puts a buffer into the transmission queue, and may request an immediate transmission if the queue is empty.
The buffer_rw field has to be CFALSE before passing it to the function. It is immediately marked as CTRUE after entering the routine. In case of an error, during the execution, this parameter is reset to CFALSE before exiting. Else it is only reset by
Description
Comments
CAN_Fill_Transmission_Buffer (See Sec tion 3.2.2 "Internal Routines").
Possible return values:
CAN_TRANSMIT_FAILURE if the cell is in stand-by,
CAN_FIFO_FULL if the 3 messages deep FIFO is full,
CAN_TRANSMIT_FATAL if CAN_Fill_Transmission_Buffer fails,
or CAN_TRANSMIT _ SUC CESS o th e r wise.
This function MUST NOT be interrupted, so protect it with SIM and RIM statements
when used OUTSIDE the notification functions of CAN_custom.c!
Calls CAN_Init_Queue and CAN_Fill_Transmission_Buffer (See Section 3.2.2 "Inter-
nal Routines")
2.1.5.3 Constants
Those constants are defined internally, but are made visible to the user because they may be
useful.
extern const Init_Data first_init_data
This is the initialization data structure that is used on power-on. It is made visible to allow you
to pass it to the CA N_Switch_On function when you do no t want to modi fy the param eters it
contains. (See Section 2.1.5.1 "Data-type Variables")
extern const u16 i_filters[];
This is the array of filters used to perform software filtering on incoming messages. The maximum number of identifiers stored is 127 (See “Filtering” on page 29). It is made visible in case
you would like to link the behaviour of your application upon reception of a message with the
offset of the id entifier in the array (ma naging an arr ay of pointe rs to func tions fo r example) .
One can of course imagine other applications.
2.1.5.4 Can_custom.h File
The preprocessor directive s used to configure the har dware an d to customize the driver are
located in this file .
Cell Configuration Values
#define INIT_BRPR 0x00
#define INIT_BTR 0x00
These values are used to initialize bit timing registers. (See Section 2.2.2.1 "Bit Timing").
You may decide whether or not to include these options in the code.
If enabled:
– WAKE_UP_PULSE enables the cell to send a domi nant bit when leaving Standby mode.
– RUN_ON_START_UP starts the cell in the Initialization function CAN_First_Init. If not en-
abled, make sure that a dominant bit detected on the bus can make the cell start. To do
this, complete the
These options are used for software filtering.
Select both of them if you want to use the feature.
If selected, en ter the li st of ide ntifi ers to b e accep ted b etwee n the c urly brac es as s hown i n
“Software Filter Configuration” on page 30.
Enabling one of the following options implies modifying the corresponding function in the
can_custom.c file:
//#define STATUS_CHANGE_NOTIFICATION
This option is used to monitor status changes (active/passive/bus-off). Setting this option will
change th e pri ority ord er in w hic h the i n terru pt s are t ak en i nt o ac c ount. T he i nte rrupts con cerning status change will be checked first, before considering reception and transmission interrupts. It will also allow compilation of the cor responding notificatio n function s
(CAN_Bus_Passive_Notification, CAN_Bus_Acti ve_Notification, CAN_Bus_Off_Notification).
To use the Error Notification functions (called when an Error IT is received), enable:
//#define DEBUG
25/100
ST7 pCAN PERIPHERAL DRIVER
If DEBUG is defined, you can then chose to add the following options:
//#define GENERAL_RECEPTION_ERROR
All reception errors trigger an interrupt. You CANNO T us e this option and the
Notification
function together because both use the same IT flag. This option does not exclude
Status Change
the bus Wake-Up feature.
//#define SIMULTANEOUS_EMISSION_RECEPTION
Only if Debug is also defined.
This function is used for forcing the cell to simultaneously send and receive any message it is
ordered to transmit to check the hardware integrity of the CAN transceiver and controller.
2.1.5.5 Can_custom.c File
This is a source file you have to complete, to allow your applicati on to react on hardware
events as they happen. An example of implementation is given in Section 2.2.3 "Implementing
This function is called unconditionally when a new data message is available in the hardware
buffer of the cell. This function has to be completed to return a pointer on a buffer structure. To
ignore it, return NULL. To help you to manage your reception buffer(s), the ID of the message
is passed as a parameter.
This function is called unconditionally when a r emote message has been saved in a hardw are
buffer. Its ID is passed as a parameter for a quick answer.
This function is called unconditi onally when a data message has been successfully saved i n a
software buffer supplied by the application. Its ID is passed as a parameter.
void CAN_Transmission_Notification(void)
This function is called unconditionally upon the successful transmission of a message.
Functions called conditionally
The following functions are called only if the corresponding option is set in can_custom.h.
This function is called upon reception of a dominant bit while in Standby mode, if the
RUN_ON_STARTUP option was not defined in can_custom.h. The corresponding interrupt
will be accepted only once. Then its acceptance flag will be cleared.
This function notifies the application of any hardware transmission errors.
Option: #define DEBUG
2.2 HOW TO USE THE CAN DRIVER: A DEMO APPLICATION
In this section, we will des cribe step-b y-step the c onfigurati on and pr ogrammi ng of a s imple
test application using the ST7 CAN driver.
2.2.1 Application
First of all, we mus t define how th e applicati on will lo ok, i.e. w hich m essages our cell w ill be
able to send, which ones it will accept to receive, and how it will behave when sp ecific messages are received.
Let’s imagine the following:
– The cell has to run immediately after power-on, and does not have to send a dominant pulse.
– Every 15 ms the cell must send the contents of the ST7 A/D Converter data register. The
identifier (ID) of this message could be, for example, 0x402.
– Upon reception of a remote frame (see Section 1.2 "CAN Frame") it must reply with the trans-
mission of a given message. The ID of the remote frame could be, for example, 0x500 (consequently, the ID of the answer will also be 0x500).
– Upon reception of a given data item, the CAN cell must shut down. This ID of the message
could be 0x600, and the data item 0xFF, in its first data byte.
– The cell is supposed to receive 3 other data messages coming from other nodes. Let’s im-
agine they are identified by 0x127, 0x311, 0x3A5.
27/100
ST7 pCAN PERIPHERAL DRIVER
– Identifiers may exist on the bus that do not concern our cell.
2.2.2 Cell Configuration
Open then the can_custom.h file. You can see the two first lines of code:
//#define WAKE_UP_PULSE
//#define RUN_ON_START_UP
According to ou r requi reme nts (Se e Sec tion 2 .2.1 "Ap plica tion"), w e only want to define the
RUN_ON_STARTUP option.
So modify the code the following way:
//#define WAKE_UP_PULSE
#define RUN_ON_START_UP
2.2.2.1 Bit Timing
First of all, we have to decide the speed of our network. Let’s say, for example, 250 kilobaud.
Look in your can_custom.h file. You see the following code:
#define INIT_BRPR 0x00
#define INIT_BTR 0x00
The following two registers define the bit timing in the cell.
The BRPR regi ster c onta ins the size o f t ime qu antum , i n num b er of clo ck tic ks, in a bit f ield
named BRP (See Section 1.3.2 "Bit timing").This field ranges from 0 to 63. The true value for
a time quanta is then BRPR+1.
The BTR register contains the size of the two synchronization segments in time quanta, in two
different bit fields: BS1 and BS2(“). BS1 ranges from 0 to 7and BS2 from 0 to 3. The actual
length of bit segments in time quanta is then BS1+1 and BS2+1.
You must always chose BS1>BS2, so that the sampling point takes place in the second half of
the bit.
For example, in our case, fcpu = 8 MHz.
So, fbus = fcpu/32.
We have then the following possibilities:
28/100
BTR+1BS1+BS2+3
216
ST7 pCAN PERIPHERAL DRIVER
BTR+1BS1+BS2+3
48
84
Let’s choose, for example, BTR = 3, BS1 = 3, BS2 = 2 (second row).
We have to complete the code:
#define INIT_BRPR 0x03
#define INIT_BTR 0x23
2.2.2.2 Filtering
The driver is able to filter out all messages not needed by the application. First by using hardware filters, and second by using software filters.
Use the hardware filters to eliminate as many identifiers as possible and to avoid further
processing. Use the software filters to elimi nate IDs that are unwanted, but that can not
stopped by the hardware.
Hardware Filter Config uration
Let’s define the values of hardware masks and filters. To do this, we must split the IDs into two
groups:
– 0x127, 0x311 and 0x3A5, on one hand; and,
– 0x500 and 0x600 on the other.
Note: When grouping the IDs, try to maximize the number of identical bits inside the same group, thus
minimizing the width of the ID ranges accepted by the cell.
Then let’s find the first filter/mask pair (12 bits to be determined):
– 0x500 is written in binary: 101 0000 0000
– 0x600 is written in binary: 110 0000 0000
In the first three bits, only the most significant bit (MSB) of both identifiers is the same, the following two bein g d ifferent. S o, the thr ee MS Bs of the mas k wi ll b e 1 0 0 (m atch, don ’t c are,
don’t care) and the three MSBs of the filter will be 1 and then either 1 or 0.
The following eight bits are identically null. So the last eight bits of the filter will be 0, and the
last eight bits of the mask will be 1 (match required).
The least signi ficant bit (LSB) of t he filter/ma sk is used to s epa rate rem o te fr ames a nd d ata
frames. Here we have a data frame and a remote frame, so it does not have to be checked (1
or 0 into the filter, 0 into the mask).
So we have:
– Filter 1000 0000 0000
– Mask 1001 1111 1110
29/100
ST7 pCAN PERIPHERAL DRIVER
Now look at the can_custom.h file:
There are several #define statements, including:
#define INIT_FHRi 0x00
#define INIT_FLRi 0x00
where i is either 0 or 1.
These are the two registers containing hardware filters. In the FHRi register, the 8 MSBs for
the filters are given, and in the second register the 4 LSBs are given followed by 4 zeros.
We have to do the same thing for the mask. First, let’s write 0 for the filter.
Finally we have:
To allow software filtering, remove the “//” comment signs, and enter the identifiers between
the parentheses. Please note that the filters must be given in h exadecimal format with fourdigits, always terminated by zero, and in increasin g order.