CONTROLLER AREA NETWORK Dogan Ibrahim
ISBN 978-1-907920-50-9
DESIGN
www.elektor.com
The book should be useful source of reference to anyone interested in finding an answer to one or more of the following questions: • What bus systems are available for the automotive industry? • What are the principles of the CAN bus? • What types of frames (or data packets) are available in a CAN bus system? • How can errors be detected in a CAN bus system and how reliable is a CAN bus system? • What types of CAN bus controllers are there? • What are the advantages of the ARM Cortex-M microcontrollers? • How can one create a CAN bus project using an ARM microcontroller? • How can one create a CAN bus project using an Arduino microcontroller? • How can one monitor data on the CAN bus?
CONTROLLER AREA NETWORK
LEARN
Elektor International Media BV
This book is written for students, for practising engineers, for hobbyists, and for everyone else who may need to learn more about the CAN bus and its applications. The book assumes that the reader has some knowledge of basic electronics. Knowledge of the C programming language will be useful in later chapters of the book, and familiarity with at least one microcontroller will be an advantage, especially if the reader intends to develop microcontroller based projects using CAN bus.
PROJECTS WITH ARM AND ARDUINO
● DOGAN IBRAHIM
Dogan Ibrahim is a Fellow of the Institution of Electrical Engineers. He is the author of over 60 technical books, published by international famous publishers, such as Wiley, Butterworth, and Newnes. In addition, he is the author of over 250 technical papers, published in journals, and presented in seminars and conferences.
This book details the use of the ARM Cortex-M family of processors and the Arduino Uno in practical CAN bus based projects. Inside, it gives a detailed introduction to the architecture of the Cortex-M family whilst providing examples of popular hardware and software development kits. Using these kits helps to simplify the embedded design cycle considerably and makes it easier to develop, debug, and test a CAN bus based project. The architecture of the highly popular ARM Cortex-M processor STM32F407VGT6 is described at a high level by considering its various modules. In addition, the use of the mikroC Pro for ARM and Arduino UNO CAN bus library of functions are described in detail.
CONTROLLER AREA NETWORK
PROJECTS WITH ARM AND ARDUINO
Dogan Ibrahim LEARN
DESIGN
SHARE
SHARE
LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHAR GN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHAR
Preface
Preface It is becoming important for microcontroller users to adapt to new technologies quickly and learn the architecture and use of high performance 32-bit microcontrollers. Several manufacturers offer 32-bit microcontrollers as general purpose processors in embedded applications. For example, Microchip Inc offer the 32-bit PIC family of microcontrollers and development tools in addition to their highly popular 8-bit and 24-bit family. ARM offers 32-bit and 64-bit processors mainly for the embedded applications. Nowadays, the majority of mobile devices such as mobile phones, tablets, and GPS receivers are based on ARM processor technology. Their low cost, low power consumption and high performance make them ideal candidates to be used in complex communication and mixed signal applications. Arduino is a highly popular family of microcontroller development boards currently used by students, practising engineers and hobbyists. Controller Area Network (CAN) was originally developed to be used in passenger cars. CAN controllers are now available from over 20 manufacturers. CAN is finding applications in many industrial fields, including medical, aerospace, process control, automation, and so on. With the arrival of the CAN in Automation (CiA) association in 1992, manufacturers and users have come together to exchange ideas, and develop CAN standards and specifications. This book is about the use of the ARM Cortex-M family of processors and the Arduino Uno in practical CAN bus based projects. The book gives a detailed introduction to the architecture of the Cortex-M family. Examples of popular hardware and software development kits are briefly described. Using these kits simplifies the embedded design cycle considerably, making it easier to develop, debug, and test CAN bus based projects. The architecture of the highly popular ARM Cortex-M processor STM32F407VGT6 is described at a high level by considering its various modules. In addition, the use of mikroC Pro for ARM and Arduino UNO CAN bus library of functions are described in detail. This book is written for students, practising engineers, hobbyists and for anyone else who may want to learn more about CAN bus and its applications. The book assumes the reader has some knowledge of basic electronics. Knowledge of the C programming language will be useful in later chapters of the book, and familiarity with at least one microcontroller will be an advantage, especially if the reader intends to develop microcontroller based projects using CAN bus. The book should be a useful source of reference for anyone interested in finding an answer to one or more of the following questions: • What bus systems are available for the automotive industry? • What are the principles of the CAN bus? • What types of frames (or data packets) are available in a CAN bus system?
● 13
CAN Arduino Dogan.indd 13
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
• How can errors be detected in a CAN bus system?, and how reliable is a CAN bus system ? • What types of CAN bus controllers are there? • What are the advantages of ARM Cortex-M microcontrollers? • How can one create a CAN bus project using an ARM microcontroller? • How can one create a CAN bus project using an Arduino microcontroller? • How can one monitor data on CAN bus? I hope that you will find this book helpful in creating your next CAN bus project using an ARM Cortex-M microcontroller or Arduino.
Dogan Ibrahim London, 2016
● 14
CAN Arduino Dogan.indd 14
30-05-16 13:06
Chapter 1 • Automotive Bus Systems
Figure 1.2 Modern vehicle with an electronic network This Chapter provides an overview of the most important vehicle network systems currently used in vehicles, and provides a table to compare the advantages and disadvantages of each system. 1.1 Vehicle Network Systems
Vehicle network systems (or networks) were classified in 1994 by the Society of Automotive Engineers (SAE). According to this classification, bus systems were classified based on their bandwidth (i.e. data rate) and functions of the network system. The classification divides bus networks into four: Class A, Class B, Class C, and Class D. Class A networks are low-speed, low-cost networks with data rates less than 10 kbps. These systems are mainly used in body of the car. Class B networks operate between 10 and 125 kbps and are used for information exchange. e.g. instrument cluster, vehicle speed and so on. Class C networks operate between 125 and 1 Mbps, and are used in a wide range of applications, such as engine control. Class D networks operate above 1 Mbps and they are mainly used in telematics applications. There are many automotive network systems (or bus systems, since the vehicle networks are in the form of bus wires), some developed by vehicle manufacturers on their own, and some developed jointly with semiconductor manufacturers. Popular vehicle network systems include:
â—? 17
CAN Arduino Dogan.indd 17
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
• CAN bus • LIN bus • FlexRay • MOST • Byteflight • DSI bus • Intellibus • SAE J1850 • BST bus • NML bus And others…
In this section we shall be looking at the basic properties of the most commonly used automotive network systems, namely: • CAN bus • LIN Bus • FlexRay • MOST • Byteflight • Intellibus 1.2 CAN Bus
The Controller Area Network (CAN) bus is the main subject matter of this book. In this section we shall be looking at the basic properties of this bus together with other automotive busses. Detailed descriptions of the CAN bus and CAN bus related projects are provided in the remaining chapters of the book. CAN is a serial, two-wire multi-master bus developed by Robert Bosch GmbH in 1980s. It is one of the most widely used automotive busses today. The physical layer of CAN consists of a pair of twisted cables. CAN provides reliable, robust, and fast communication up to 1 Mbps (with 40m bus length). CAN 2.0A is the original CAN, consisting of the fields: Start of Frame bit, 18-bits header (having 11-bits message identifier), 0-8 bytes data, 15-bits Cyclic redundancy Check (CRC), 3-bits acknowledgement slot, and 7-bits of End of Frame. CAN bus is based on the CSMA/CR (Carrier Sense Multiple Access/Collision Resolution) mechanism to prevent frame collisions during transmissions on the bus. Each CAN node monitors the bus and when the node detects that the bus is idle, it may start transmitting data. If other nodes on the bus attempt to send data at the same time, arbitration will take place and the node with the highest priority (lowest message identifier) will win the arbitration and send its own data. CAN bus has a simple error detection and recovery mechanism. Receiving nodes check the integrity of the messages by looking at the CRC fields. If an error is detected, the other nodes on the bus are informed by error flag messages. Figure 1.3 shows a typical CAN bus implementation with two nodes, A and B. CAN is a Class A/B type network.
● 18
CAN Arduino Dogan.indd 18
30-05-16 13:06
Chapter 2 • Structure of the can physical layer
Chapter 2 • Structure of the CAN physical layer The physical layer forms the hardware interface that establishes connection between a number of nodes. A minimum of two nodes are required to communicate on a bus. Figure 2.1 shows a CAN bus with three nodes. The bus is made up of a twisted-pair cable and is terminated at both ends with a resistor so that the bus characteristic resistance is 120 ohms. The two wires of the bus are termed CAN_H and CAN_L.
Figure 2.1 CAN bus with three nodes 2.1 CAN Bus Termination
The bus is terminated to minimize signal reflections on the bus. Usually, a single 120 ohm resistor is connected to each end of the bus. Although the power rating of the chosen resistor is not particularly important, possible short-circuits to power supplies on the bus should be considered when selecting resistor power rating. A 1/4W 5% tolerance resistor is generally used, but it is recommended to use a higher rating (e.g. 1W) resistor to avoid any damage to the bus due to possible transceiver short-circuits. Although a single 120 ohm resistor is usually used, in general one of the following methods can be used to terminate the bus: • Standard termination • Split termination • Biased split termination • The most commonly used termination method is the standard termination where a 120 ohm resistor is used at each end of the bus as shown in Figure 2.2.
● 45
CAN Arduino Dogan.indd 45
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
Figure 2.2 Standard bus termination Figure 2.3 shows split termination which is gaining in popularity. In this method, two 60 ohm resistors and a capacitor are used at each end of the bus. The advantage of this method is that it eliminates high frequency noise from bus lines. Care must be taken to match the resistors so as not to reduce the effective immunity on the bus. Typically, a 4.7nF capacitor is chosen which generates a response with a 3dB point at approximately 1.1Mbps.
Figure 2.3 Split bus termination Figure 2.4 shows the biased split bus termination where a voltage divider circuit and a capacitor are used at each end of the bus. As in split termination, the biased split termination increases the EMC performance of the bus.
â—? 46
CAN Arduino Dogan.indd 46
30-05-16 13:06
Chapter 2 • Structure of the can physical layer
Figure 2.4 Biased split bus termination It is important to note that terminating resistors must be placed at the ends of the longest bus length. In Figure 2.5, one of the terminating resistors is placed in the wrong place. Both wrong terminating resistor values and wrong termination place cause errors on the bus.
Figure 2.5 Wrong placement of a terminating resistor Correct termination of the bus can be checked by using a digital voltmeter to measure the bus resistance. Set the meter to measure resistance and connect the two leads of the meter to the ends of a node on the bus (see Figure 2.6). The meter should measure 60 ohms.
Figure 2.6 Checking the bus termination
â—? 47
CAN Arduino Dogan.indd 47
30-05-16 13:06
Chapter 3 • CAN Bus Frames
Chapter 3 • CAN Bus Frames Messages on CAN bus are sent and received using Frames. A frame is basically like a Packet in a TCP/IP type network where the actual data is encapsulated with control data. CAN bus communication is not like the popular Client-Master type communication. In CAN bus, all nodes have the same rights and they can transmit as well as receive data at suitable times. Some important CAN protocol features are: • CAN bus is multi-master. When the bus is free, any device attached to the bus can start sending a message. When multiple devices attempt to send data at the same time then collisions can occur on the bus. Collisions are detected and avoided using an arbitration mechanism. • The CAN bus protocol is flexible. Devices connected to the bus have no addresses (or node IDs), which means that messages are not transmitted from one node to another based on addresses. Instead, all nodes on the bus receive every message transmitted on the bus, and it is up to each node to decide whether or not the received message should be kept or discarded. A single message can be destined for a particular device on a particular node, or for many nodes, depending on how the bus system is designed. Messages have message identifiers, and acceptance filters on each node decide whether or not to accept a message being transmitted on the bus. Another advantage of having no addresses is that when a device is added to or removed from the bus, no configuration data needs to be changed (i.e. the bus is “hot pluggable”). • Messages sent on the bus have priorities. A message with a lower message identifier has a higher priority. • CAN bus communication speed is not fixed. Any communication speed up to the allowed maximum can be set for the devices attached to the bus. • CAN bus offers remote transmit request (RTR), which means that a node on the bus is able to request data from other nodes. Thus, instead of waiting for a node to continuously send data, a request for data can be sent to the node. For example, in a vehicle, where the engine temperature is an important parameter, the system can be designed so that the temperature is sent periodically over the bus. However, a more elegant solution is to request the temperature as needed. This second approach will minimize bus traffic and CPU loading this increasing performance, while maintaining the integrity. • All devices on the bus can detect an error. The device that has detected an error immediately notifies all other devices. Nodes that transmit faulty data, or nodes that are always receiving data in error will remove themselves from the
● 59
CAN Arduino Dogan.indd 59
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
bus, thus allowing the normal bus operations to continue. • Receiving nodes on the bus check the validity of the received frame and acknowledge the consistency. The transmitting node monitors the bus during the acknowledgement slot. • Multiple devices can be connected to the bus at the same time, and there are no logical limits to the number of devices that can be connected. In practice, the number of nodes that can be attached to a bus is limited by the delay time of the bus and electrical load on the bus. There are four message frames in CAN bus: • Data Frame: Defines the data transfer between nodes. • Remote Frame: Used by a node to request transmission of a message (i.e. data) from another node. • Error Frame: Any node on the bus can send an error frame to signal an error condition. • Overload Frame: This frame is used by a receiving node to indicate that it is not yet ready to receive frames. We shall now look at each frame in greater detail. There are essentially two types of CAN protocols: 2.0A and 2.0B. CAN 2.0A is the earlier standard with 11 bits of identifier (see next section), while CAN 2.0B is the new extended protocol with 29 bits of identifier. 2.0B controllers are completely backwards compatible with 2.0A controllers and can receive/transmit messages in either format. We shall firstly look at the standard CAN 2.0A frames and then explore the CAN 2.0B frames in later sections. There are two types of 2.0A controllers. The first is capable of sending and receiving 2.0A messages only, and reception of a 2.0B message will flag an error. The second type of 2.0A controller (known as 2.0B passive) sends and receives 2.0A messages but will also acknowledge receipt of 2.0B messages and then ignore them. 3.1 Data Frame
The data frame is used by a transmitting device to send data to receiving devices on the bus, and this frame is the most important frame handled by the user. The data frame can be sent in response to a request, or it can be sent whenever it is required to send the value of some parameter to other nodes on the bus (e.g. the temperature can be sent at periodic intervals).
● 60
CAN Arduino Dogan.indd 60
30-05-16 13:06
Chapter 3 • CAN Bus Frames
Figure 3.1 shows the structure of a data frame. The bus is normally idle. Then, a standard data frame starts with the start of frame (SOF) bit, which is followed by an 11-bit identifier and remote transmission request (RTR) bit. The control field is 6-bits wide and indicates how many bytes of data are in the data field. The data field can be 0 to 8 bytes and it contains the actual data to be sent. The data field is followed by the 16-bit checksum (CRC) field which checks whether or not the received bit sequence is corrupted. The ACK field is 2-bits wide and is used by the transmitting node to receive acknowledgement of a valid frame from any receiver. The end of message is indicated by a 7-bit end of frame (EOF) field. Successive frames must be separated by at least 3-bit times, called the interframe space (ITM). The total number of bits required by the data frame are (assuming successive frames are to be sent): SOF 1 bit Identifier 11 bits RTR 1 bit Control 6 bits Data 0 to 64 bits (0 to 8 bytes) CRC 16 bits ACK 2 bits EOF 7 bits ITM 3 bits In total, 47 bits (no data) to 111 bits (8 bytes of data) are required by the data frame.
Figure 3.1 Standard data frame Figure 3.2 shows the standard data frame in more detail.
â—? 61
CAN Arduino Dogan.indd 61
30-05-16 13:06
Chapter 4 • Error conditions on can bus
Chapter 4 • Error conditions on CAN Bus Before going into the details of CAN bus error types, it is worthwhile to look at the Bit Stuffing mechanisms on the bus. 4.1 Bit Stuffing
The CAN standard specifies that any bits of the same polarity (recessive or dominant) on the bus that are longer than 5 bits long is a violation of the standard. In fact, this standard was used to send error frames on the bus consisting of 6 dominant bits in sequence. In some applications it may be a requirement to send more than 5 bits of the same polarity (e.g. the data bits may contain more than 5 bits of the same polarity). This type of situation is handled on the bus by the transmitting node inserting a bit of opposite polarity after the 5th bit. The receiving node then removes this bit. This mechanism is called Bit Stuffing and it allows to synchronize the transmit and receive operations to prevent timing errors. Note that error and overload frames are transmitted without Bit Stuffing. Also, during a reception, if the 6th bit is same as the 5th then a Stuffing Error occurs on the bus. Bit stuffing is allowed from the SOF field to the CRC field (see Figure 4.1). Bit stuffing is not allowed in the static fields of a frame. i.e. it is not allowed in the following fields: • CRC delimiter • ACK field • EOF field • Interframe gap Figure 4.2 shows an example of bit stuffing where the transmitting node added a recessive bit after the 5th dominant bit. The receiving node removed this bit and thus more than 5 dominant bits have successfully been transmitted on the bus. Similarly, in Figure 4.3, the transmitting node added a dominant bit after the 5th recessive bit. The receiving node again removed the stuffed bit and thus more than 5 recessive bits have successfully been transmitted on the bus.
Figure 4.1 Fields where bit stuffing can be used
● 73
CAN Arduino Dogan.indd 73
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
Figure 4.2 Bit stuffing example (adding a recessive bit)
Figure 4.3 Bit stuffing example (adding a dominant bit) 4.2 CAN Bus Error Detection
There are five types of error that can occur on the bus. If any of these errors is observed, the error frame is transmitted which causes the current frame on the bus to be declared as faulty and discarded by all nodes on the bus. The error types are: • Bit error • Bit stuffing error • CRC error • Frame error • ACK error Now let us have a look at these error conditions in more detail. 4.2.1 Bit Error
When a node transmits a bit on the bus it also monitors the bus and compares the transmitted bit with the actual level on the bus. A bit error is said to happen when the transmitted bit is not same as the bit level on the bus. Note that a bit error will not happen during the arbitration phase where a node transmits a recessive bit while another node transmits a dominant bit. Also, while a node is transmitting an error frame with 6 consecutive recessive bits, if a dominant bit is detected on the bus this will not create a bit error.
● 74
CAN Arduino Dogan.indd 74
30-05-16 13:06
Chapter 5 • Data exchange on CAN bus
Chapter 5 • Data exchange on CAN bus In this chapter we shall look at how data is exchanged on CAN bus. CAN bus is a multi-master bus where any node can be transmitting or receiving at any one time. When a node transmits on the bus, all other nodes listen and receive the transmitted message. Although all the receiving nodes receive all the messages they may decide not to act on the message contents as the message may not be relevant to the node. CAN bus nodes do not have addresses. Thus, messages are not transmitted to addressed nodes, but rather they are broadcast on the bus. Also, a node does not need to know where a message comes from. Similarly, a transmitting node may not necessarily know which nodes have actually acted on the message sent. The nodes only receive the messages they are programmed to receive. Although the internal workings of different CAN controllers may be different, as far as data exchange mechanisms are concerned, the basic principles of data exchange are described briefly in this chapter. 5.1 Data Exchange With Data Frames
Data frames are the most important frames in CAN bus as they enable data to be sent from a transmitting node to other nodes on the bus. A data frame has a dominant RTR bit. When a node wants to send data to other nodes on the bus it forms a data frame. The data frame basically includes a message identifier, actual data bytes, and error checking bits. The message identifier is very important as it is used by the receiving nodes to decide whether or not to accept this message. CAN bus controllers in receiving nodes have built in Acceptance Filters (or Receive Filters). These filters can be programmed and loaded with values by the programmer or system user. The message identifiers of data frames on the bus are compared with filter values, and the message is accepted by the controller if the filter value is same as the message identifier. If the message identifier and the filter values are not the same, then the message is not accepted by the controller. Thus, by programming acceptance filters we can enable a node to accept or reject a message (note that all receiving nodes receive all messages but they may not accept them all). Most CAN bus controllers also have built in Filter Masks. These are used to determine which bits in the message identifier are to be compared with the values in the acceptance filters. For example, setting all filter mask values to 1s will make sure that all the bits of the message identifiers are to be compared with all bits of acceptance filters. Figure 5.1 shows an example data exchange on the bus. In this example there are three nodes on the bus, A, B, and C. Assume that the acceptance filters in each node’s controller at the time of data transmission are set to the following values: Node A: Acceptance filter value = “00000000011” Node B: Acceptance filter value = “00000011111” Node C: Acceptance filter value = “00000000111”
● 79
CAN Arduino Dogan.indd 79
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
Assume that Node A has high priority and transmits a data frame with the message identifier set to bit pattern “00000000111”. The other two nodes are in receive mode and compare the message identifier on the bus with their acceptance filter values. Node C has the same acceptance filter value as the message identifier and thus its controller accepts the data frame sent by Node A. The controller in Node B compares its acceptance filter with the message identifier and ignores the data frame as the two are not same.
Figure 5.1 Data frame exchange on the bus Note that when a message is sent on the bus, the controllers of all nodes receive this message, but may not accept the message. Also, although the controller may accept a message, this message usually stays in a receive buffer of the controller until the application software makes a request to pull the message out of this buffer and copy it to its internal data structures. Figure 5.2 shows another example where Node A transmits a data frame and both Node B and Node C accept this data frame. In this example the acceptance filter of Node B is changed to “00000000111”.
● 80
CAN Arduino Dogan.indd 80
30-05-16 13:06
Chapter 6 • CAN Bus timing
Chapter 6 • CAN Bus timing Timing and proper synchronization of different nodes on CAN bus is very important for the proper operation of the bus. Basically, all the nodes on a CAN bus are synchronized by the falling edge (recessive to dominant transition) of the Start-Of-Frame (SOF) bit. This is actually a limited way of making sure that all the nodes are synchronized properly. In this chapter we shall be looking at CAN bus timing and synchronization methods. 6.1 Bit Timing
Signals on a CAN bus are based on the NRZ (Non-Return-to-Zero) signaling scheme where a signal can stay in the same state for a long time with no edges. This makes data synchronization very difficult as there may not be any signal edges to use for synchronization. Luckily the bit stuffing method ensures that a frame cannot keep the bus at the same polarity for more than 5 bits, and this feature helps to synchronize the data. Figure 6.1 shows an example NRZ signal where the same bit pattern is sent for long periods of time (10 bit time in this example), thus making it difficult for a receiver to know the start or end of the data, and thus requiring additional bit synchronization methods.
Figure 6.1 Example NRZ signal CAN bus timing is based on clock mechanisms employed within the CAN bus controller. Basically, a free running crystal clock provides pulses at a high rate. Inside the controller this clock rate is divided by a user programmable prescaler, BRP, (the prescaler usually has a minimum division rate of 2), and the resulting lower rate clock is used as the Baud Rate clock (or the node CAN clock) which determines the timing of the node. The CAN nominal bit rate is defined as the number of bits transmitted every second without synchronization. The inverse of the nominal bit rate is the nominal bit time. All devices on the CAN bus must use the same bit rate, even though each node can have its own internal clock frequency. As shown in Figure 6.2, the CAN nominal bit time consists of four non-overlapping time segments named: • Synchronization segment, Sync_Seg • Propagation segment, Prop_Seg • Phase buffer segment 1, Phase_Seg1 • Phase buffer segment 2, Phase_Seg2
● 85
CAN Arduino Dogan.indd 85
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
Figure 6.2 CAN controller oscillator and bit time The Sync_Seg segment is used to synchronize various nodes on the bus, and an edge is expected to lie within this segment. Any shift in the Sync_Seg will be detected by the nodes and each node will adjust the length of its phase buffer segments accordingly to re-synchronize the node. For a transmitting node, the new bit value is transmitted from the beginning of the Sync_Seg. For a receiving node, the start of the received bit is expected to occur during the Sync_Seg. The Prop_Seg segment compensates for physical delay times on the bus, such as the propagation times from a transmitter to receiver and back to a transmitter. The Phase_Seg1 and Phase_Seg2 segments compensate for edge phase errors. These segments can be lengthened or shortened to synchronize the node. The Sample Point (see Figure 6.2) is the point in time where the actual bit value is located and occurs at the end of Phase_Seg1. Each segment is divided into units known as time quantum, or T, where a quantum is basically equal to one period of the CAN clock (see Figure 6.2). A desired bit timing can be set by adjusting the number of T ’s that comprise one message bit and the number of T ’s that comprise each segment in it. The time quantum of each segment can vary from 1 to 8. The lengths of the various time segments are: • Sync_Seg is always 1 TQ • Prop_Seg is programmable from 1 TQ to 8 TQ • Phase_Seg1 is programmable from 1 TQ to 8 TQ • Phase_Seg2 is programmable and is equal to the larger of the Phase_Seg1 or to
● 86
CAN Arduino Dogan.indd 86
30-05-16 13:06
Chapter 7 • CAN Bus controllers
Chapter 7 • CAN Bus controllers In general, a CAN bus controller provides the interface between a microcontroller and CAN bus. A CAN bus controller is basically of two types: those with built-in transceivers and those without built-in transceivers. The CAN transceiver provides the physical interface to the CAN bus. It consists of bus driver and receiver logic. The controller is programmable and it contains error detection logic, acceptance filters, masks, and buffers. The controller receives CAN data from the transceiver, accepts or rejects this data, and if accepted transfers the data to a microcontroller system. Similarly, the controller sends data to the CAN bus through the CAN transceiver. Some high-end microcontrollers have built-in CAN controller modules and transceiver circuits and hence they can be connected directly to CAN bus as shown in Figure 7.1. If a microcontroller has no built-in CAN controller and no bus transceiver then external controller and transceiver chips can be connected to its I/O pins as shown in Figure 7.2.
Figure 7.1 Microcontroller with built-in CAN controller and transceiver
â—? 99
CAN Arduino Dogan.indd 99
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
Figure 7.2 Microcontroller with external CAN controller and transceiver In this Chapter we shall be looking at the basic structure of various CAN transceivers and CAN controllers available in the market. 7.1 The Basic Structure of a CAN Transceiver
As mentioned earlier in the Chapter, a CAN transceiver provides the actual physical interface to the CAN bus. A typical CAN transceiver consists of the following: • TX and RX pins to connect to the controller • CAN_H and CAN_L pins to connect to CAN bus • Power supply pins Figure 7.3 shows the pin configuration of MCP2551, which is a typical CAN transceiver from Microchip Inc. (source: http://www.microchip.com).
Figure 7.3 Pin configuration of MCP2551 CAN transceiver The internal structure of the MCP2551 chip is shown in Figure 7.4. Notice the open collector output of pin CAN_H. The chip supports operation up to 1 Mbps and is suitable for both 12V (e.g. cars) and 24V systems. MCP2551 includes short-circuit protection circuitry, and automatic thermal shutdown protection. Protection against high voltage transients is also provided. Low power standby operation provides energy saving in power critical applications. Up to 112 nodes can be connected to the CAN bus.
● 100
CAN Arduino Dogan.indd 100
30-05-16 13:06
Chapter 8 • CAN Bus development tools
Chapter 8 • CAN Bus development tools The development of a CAN bus project is easier when development tools are used. There are a variety of hardware and software tools available that can assist engineers in the development, testing, and production of CAN bus based projects. Some of the popular CAN bus development tools are: • CAN bus hardware development boards • General purpose microcontroller development boards with CAN bus modules • CAN bus analyzers • Logic analyzers with CAN bus additional options • CAN bus simulators • CAN bus stimulators • CAN bus programming libraries for high level languages In this Chapter we shall be looking at some of the most commonly used CAN bus tools. In general, we can divide CAN bus development tools into three types: hardware development tools, CAN bus analyzers, and software development tools. Some of these tools incorporate both hardware and software. 8.1 Hardware Development Tools
Hardware development tools are usually microcontroller based boards used during the development of CAN bus based projects. Such tools require knowledge of computer programming and basic electronic engineering skills. In this section we shall be looking at some of the hardware development tools. 8.1.1 CAN MicroMOD Development Kit
This development kit includes a PC CAN interface, a MicroMod evaluation board (Figure 8.1), a MicroMod CPU board, power adapter, and 3ft CAN cable. Users can create their CAN bus network and experiment with the kit. Configuration data is sent to the module via CAN bus and each individual node over the bus can be enabled to read or send data.
Figure 8.1 CAN MicroMod Evaluation board (www.peak-system.com)
● 107
CAN Arduino Dogan.indd 107
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
8.1.2 mikroElektronika CAN Communication Kit
This kit (see Figure 8.2), manufactured by mikroElektronika is based on their highly successful EasyPIC V7 microcontroller development boards. The mikroC Pro for PIC high level programming language compiler and IDE is included in the package. The kit can be used to set up a two node CAN network (can be expanded if required).
Figure 8.2 mikroElektronika CAN communication kit (www.mikroe.com) The kit includes: • 2 x EasyPIC v7 Development boards • mikroC PRO for PIC compiler and IDE with USB Dongle Licence • 2 x CAN SPI click 3.3V • 2 x SmartPROTO Board • 2 x EasyConnect Board • 2 x Character LCD 2x16 with blue backlight • 2 x DS1820 Temperature Sensor • 2 x Graphic LCD 128x64 with TouchPanel • Twisted Wire (2 meters long) • 2 x Serial Cable • 2 x Plastic Pen for TouchPanel • USB cable • Printed manual 8.1.3 The RCDK8C CAN Development Kit
This kit (See Figure 8.3) is developed by Renesas and can be used to set up a two node CAN network. The kit comes with two R8C23 target boards with network-ready CAN MCU, CAN transceivers, CAN twisted-pair cable and connectors. The kit is supplied with the following parts: • 2 starter kit boards (pre-programmed with demonstration boards) • DC power supply • LCD • CAN sniffer for monitoring CAN bus traffic • In system programmer and debugger • Cable assembly for USB and CAN bus
● 108
CAN Arduino Dogan.indd 108
30-05-16 13:06
Chapter 9 • Architecture of ARM microcontrollers
Chapter 9 • Architecture of ARM microcontrollers It is important to learn the basic architecture, advantages, disadvantages, and limitations of a microcontroller before it is used in a project. In this book we shall be using the highly popular 32-bit ARM microcontroller, the STM32F407VGT6 in CAN bus projects. This microcontroller is a member of the STM32 family of ARM microcontrollers. A brief description of the architecture of this microcontroller is given in this Chapter and its basic features are described so that we can develop projects easily and efficiently. Clock configuration and input-output ports are important parts of every microcontroller and are used almost in all projects. As a result, these are described in detail in this chapter. 9.1 The STM32 Family of ARM Microcontrollers
The STM32 family of 32-bit microcontrollers are based on ARM Cortex and there are over 300 compatible devices in the family. As described below, the family includes microcontrollers with the Cortex-M4, Cortex-M3, and Cortex-M0 architectures. Cortex-M4: Microcontrollers in this series start with the names STM32F4 and are designed for use in 32-bit applications. These are high performance microcontrollers having DSP and floating point arithmetic capabilities with a 168MHz clock, up to 1Mbyte of flash memory, up to 256Kbytes of SRAM, and a large number of peripherals including USB, Ethernet, and a camera interface. The PIC32F407CGT6 microcontroller is a member of the Cortex-M4 family. Cortex-M3: Microcontrollers in this series start with the names STM32F1, STM32F2, STM32W, or STM32L1 and are designed for use in 16/32-bit applications. STM32F1 devices operate up to 72MHz, have up to 1Mbyte flash memory, up to 96Kbytes of RAM, and a large number of peripherals, including Ethernet interface. STM32F2 devices operate up to 120MHz, have up to 1Mbyte flash memory, up to 128Kbytes of SRAM, and have a large number of peripherals including Ethernet and a camera interface. STM32W are wireless (IEEE 802.15.4) microcontrollers with clock frequencies up to 24MHz, up to 256Kbytes of flash memory and 16Kbyte of SRAM. STM32L1 microcontrollers are ultra-low power devices operating at up to 32MHz, having up to 384Kbyte flash memory, and up to 48Kbytes of SRAM. The operating voltage is down to 1.65V with standby current of only 0.3µA. Cortex-M0: Microcontrollers in this series start with the name STM32F0 and are entry level devices. The clock frequency is up to 48MHz, and they can have up to 128Kbytes of flash memory and 12Kbytes of SRAM. 9.2 The STM32F107VCT6 Microcontroller
In this book we shall be using the highly popular ARM microcontroller STM32F407VGT6 together with the Clicker 2 for STM32 development board (details are given in a later Chapter). In this Chapter we shall be looking at the features of the STM32F407VGT6 microcontroller. The internal architecture of this microcontroller is very complex and we shall only look at the important modules used in most projects, such as I/O, timers, ADC and DAC converters, interrupts, I2C, USART, and so on. Interested readers can get detailed informa-
● 121
CAN Arduino Dogan.indd 121
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
tion from manufacturer data sheets available for download on the Internet. 9.2.1 Basic Features of the STM32F407VCT6
The STM32F407VGT6 microcontroller is based on the Cortex-M4 architecture and has the following basic features: • ARM Cortex-M4 32-bit RISC architecture • Included Floating Point Unit (FPU) and Digital Signal Processor (DSP) • Up to 168MHz maximum operating frequency • Single-cycle multiplication and hardware division • Up to 1Mbytes of flash memory • Up to 192Kbytes of SRAM • 1.8 to 3.6V power supply • -40ºC to +105ºC operation • Clock PLL • 4 - 26MHz crystal oscillator • Internal 16MHz clock • Internal 32kHz oscillator for RTC • Low power with sleep, stop, and standby modes • 3 x 12-bit 24 channel ADC converters with 0 to 3.6V reference • Sample and hold capability • Temperature sensor • 2 x 12-bit DAC converters • Up to 17 timers • Up to 140 I/O ports (138 of them +5V tolerant) • 16 stream DMA controller • 2 x CAN bus interface (2.0B) • 6 x USART interface (with LIN and IrDA capabilities) • 3 x SPI interface (42Mbits/s) • 3 x I2S interface • 3 x I2C interface • 2 x USB interface • 2 x Watchdog timer • 2 x 16 bit motor control PWM • SDIO interface • 1 x 10/100 Ethernet interface • 8 – 14 bit parallel camera interface • Nested vectored interrupt controller • Random number generator • Serial wire debug and JTAG interface • Cyclic Redundancy Check (CRC) calculation unit The basic features of the STM32F407VGT6 microcontroller are summarized in Figure 9.1.
● 122
CAN Arduino Dogan.indd 122
30-05-16 13:06
Chapter 9 • Architecture of ARM microcontrollers
Figure 9.1 Basic Features of the STM32F407VCT6 microcontroller Figure 9.2 shows the pin layout (100 pin package) of the STM32F407VGT6 microcontroller. 9.2.2 Internal Block Diagram
The internal block diagram is shown in Figure 9.3. At the top left corner is the 168MHz Cortex-M4 processor with flash memory and SRAM, with DMA channels, USB and Ethernet modules just below the processor. The camera interface, voltage regulator and external crystal inputs are shown at the top right hand corner of the figure. The internal AHB (Advanced High Speed Bus) bus is divided into 84MHz high-speed bus APB2 (Advanced Peripheral Bus 2), supporting the some timers, SPI bus, USARTs and ADC channels. The 42MHz low-speed bus APB1 (Advanced Peripheral Bus 1) supports some timers, USARTs, I2C bus, CAN modules, DAC and the watchdog timer. Clocks to the GPIO ports are driven from the high speed 168MHz AHB1 bus in the middle of the figure. Memories are shown in the top middle part of the figure.
â—? 123
CAN Arduino Dogan.indd 123
30-05-16 13:06
Chapter 10 • Programming ARM Microcontrollers
Chapter 10 • Programming ARM Microcontrollers There are various programming languages and methods available for programming ARM microcontrollers. For example, ARM Cortex-M microcontrollers can be programmed in Java, Arduino, C, C++ and others. In this book we shall be using the mikroC Pro for ARM (called mikroC in the remainder of this book) programming language and the Integrated Development Environment (IDE) developed by mikroElektronika. mikroC Pro for ARM is a powerful, feature-rich development tool for ARM microcontrollers, designed to provide programmers with the easiest possible solution for developing applications for ARM based embedded systems. In this chapter we shall be looking at the specific features of the mikroC programming language when it is used to program the STM32 family of ARM microcontrollers (more specifically the STM32F407VGT6 microcontroller). The chapter is not intended to teach the C programming language as the readers are assumed to have practical knowledge the C language in a microcontroller environment. 10.1 mikroC STM32F407VCT6 Microcontroller Specific Features
mikroC is very similar to the standard C language but it has been developed specifically for programming microcontrollers. There are various versions of mikroC for programming PIC microcontrollers, the 8051 series of microcontrollers, AVR family, ARM Cortex microcontrollers, and so on. mikroC allows a programmer to: • Write source code using the built-in text editor • Include all libraries to speed up the development process • Manage your project easily • Monitor program structure, variables, and functions • Generate assembly and HEX files for programming the target processor • Use integrated simulator to debug code on your PC • Use the integrated hardware debugger to speed up program development and testing • Get detailed reports on memory usage, calling tree, assembly listing and more • Program the target processor using the integrated programming software mikroC includes libraries on hardware, digital signal processing, ANSI C, and others. Some more commonly used libraries are (there are over 60 libraries): ADC library • CAN library • EEPROM library • Ethernet library • GPIO library • LCD and Graphics LCD library • Keypad library • Sound library • UART library
● 141
CAN Arduino Dogan.indd 141
30-05-16 13:06
Controller Area Network - Projects with ARM and Arduino
• TFT display library • Touch panel library • USB library • Digital filter libraries (FIR and IIR) • FFT library • Matrices library • ANSI C Math library • Button library • Conversions library • Time library • Trigonometry library mikroC includes a built-in integrated Help facility that helps programmers to learn the format of various library statements and also to check the syntax of program statements. mikroC organizes applications into projects, consisting of a single project file (extension .mcarm) and one or more source files (extension .c). The IDE helps programmers to create multiple projects. A project file contains the following: • Project name • Target microcontroller device • Device clock • List of project source files • Header files • Binary files • Image files • Other files Figure 10.1 shows the structure of a mikroC program written for the STM32F407VGT6 microcontroller. Although comments are optional in a program, it is highly recommended as it makes a program easier to understand and maintain. This very simple program flashes an LED every second. We shall see in this chapter some of the STM32F407VCT6 specific features of the mikroC language. Most of the features described in this chapter are applicable to other members of the STM32 family. /*************************************************************************** FLASHING LEDs ============= In this project 16 LEDs are connected to PORTD of a STM32F407VCT6 type ARM Cortex-M4 microcontroller. The program flashes the LEDs every second.
Author: Dogan Ibrahim File
: LEDS.c
● 142
CAN Arduino Dogan.indd 142
30-05-16 13:06
Chapter 11 • Clicker 2 for STM32 Development Board
Chapter 11 • Clicker 2 for STM32 Development Board The Clicker 2 is a powerful development board using the STM32F407VGT6 32-bit ARM Cortex-M4 microcontroller operating at up to 168MHz. It has 1MB of flash memory and over 192Kbytes of SRAM. The board (see Figure 11.1) is developed and manufactured by mikroElektronika and has the following basic features: • STM32F407VGT6 microcontroller (100 pins) • 168MHz operation speed • 1MB flash memory • Over 192Kbytes SRAM • 25MHz and 32.768kHz external crystals • 52 programmable GPIO pins • 2 mikroBUS sockets to accept Click Boards (www.mikroe.com) • USB mini connector • 2 LEDs • 2 push-button switches • 2x26 connection pads • Power manager IC • Reset button • External battery connector
Figure 11.1 Clicker 2 for STM32 development board The microcontroller on the board can be programmed from a PC using a Bootloader program. The Clicker 2 for STM32 development board is used in all ARM and CAN bus based projects in this book. Thus, more details and a simple programming example are given in the remainder of this book familiarise the reader with this board. 11.1 LEDs
There are two LEDs, LD1 and LD2, on board connected to port pins PE12 and PE15 respectively. The cathodes of the LEDs are connected to ground via 2.2K current limiting resistors. Thus, the LEDs are turned on when logic 1 is applied to the corresponding output ports.
● 169
CAN Arduino Dogan.indd 169
30-05-16 13:07
Controller Area Network - Projects with ARM and Arduino
11.2 Push-button Switches
There are two push-button switches, T2 and T3 on the board connected to port pins PE0 and PA10 respectively. The switches are normally pulled HIGH through 10K resistors. Pushing a switch forces its output to logic 0. Figure 11.2 shows the LED and push-button connections on the board.
Figure 11.2 LED and push-button connections 11.3 Power Supply
The board can either be powered from a PC or a suitable 5V supply through its mini USB port (see Figure 11.3), or using an external Li-Polymer battery (see Figure 11.4).
Figure 11.3 Powering from the mini USB port
â—? 170
CAN Arduino Dogan.indd 170
30-05-16 13:07
Chapter 12 • mikroC Pro for ARM Built-IN CAN Bus functions
Chapter 12 • mikroC Pro for ARM Built-IN CAN Bus functions In general, any type of microcontroller can be used in a CAN bus-based project. A microcontroller with a built-in CAN controller module (such as ARM processors) will certainly simplify the design and also shorten the development and testing times. Figure 12.1 shows the block diagram of a CAN bus application where a general purpose microcontroller is used and where the microcontroller does not have a built-in CAN controller. As can be seen from this figure, a CAN controller chip (e.g. MCP2515) and a CAN transceiver chip (e.g. MCP2551) are required to establish a CAN node. In such applications, the communication between the microcontroller and the CAN controller module is usually via SPI bus.
Figure 12.1 CAN node where the microcontroller has no built-in CAN controller module In this book we shall be using the STM32F407VGT6 ARM Cortex-M4 microcontroller which has two built-in CAN controller modules. The only additional chip required to establish a CAN node is a CAN transceiver chip. Figure 12.2 shows the block diagram of a CAN node using an ARM processor.
Figure 12.2 CAN node where the microcontroller has built-in CAN controller module 12.1 STM32F407VGT6 Microcontroller Built-in CAN Controller Module
It is important to have some understanding of the operation of the STM32F407VGT6 microcontroller CAN controller module before looking at the functions available to program
● 177
CAN Arduino Dogan.indd 177
30-05-16 13:07
Controller Area Network - Projects with ARM and Arduino
the chip. The operational description given in this Chapter applies to the STM32F407VGT6 only. Similar microcontrollers and further details can be obtained from the manufacturer (www. STMicroelectronics.com) Reference Manual RM0090 (STM32F405/415, STM32F407/417, STM32F427/437 and STM32F429/439 advanced ARM®-based 32-bit MCUs), Document ID: DocID018909 Rev 11, 2015. The basic features of the CAN module that we are interested here are: • 2 CAN modules (CAN1 and CAN2) sharing the 512 byte SRAM memory • Both CAN 2.0A and 2.0B are supported • Support for standard identifiers (11-bit) and extended identifiers (29-bit) • Bit rate is up to 1Mbit/s • 3 transmit mailboxes • Configurable transmit priority • 2 receive FIFOs (with 3 stages) • 28 configurable Identifier filter banks (or acceptance filters) shared between CAN1 and CAN2 Three transmit mailboxes are provided for setting up messages. A CAN node uses acceptance filters to decide whether or not to accept a received message. Any unaccepted message is discarded. In CAN protocol, node addresses are not used and the identifier is associated with the content of a message. Two hardware managed FIFOs are used to store incoming messages, where three complete messages can be stored in each FIFO. The CAN module has three modes of operation: Initialization mode: The CAN module is initialized in this mode. All messages transfer to and from the CAN bus are stopped and the bus output status is set to recessive. Normal mode: This is the normal operation mode where both transmission and reception of messages are allowed. Normal mode follows the initialization mode. Sleep mode: This mode is entered on software request to reduce power consumption. In this mode, the clock is stopped. In addition to the three modes, there is also a Test and Debug mode. The Test mode has the options of: Silent mode (only receive), Loop back mode (own transmitted messages are received and stored), or the Loop back with Silent mode.
● 178
CAN Arduino Dogan.indd 178
30-05-16 13:07
Chapter 13 • CAN BUS projects using ARM Microcontrollers
Chapter 13 • CAN BUS projects using ARM Microcontrollers Developing a CAN bus based project using a microcontroller requires two things: hardware, and software. The hardware usually consists of a microcontroller development board with a suitable microcontroller, and the software is usually a high-level language compiler. In this Chapter, the Clicker 2 for STM32 microcontroller development board described in Chapter 11 is used as hardware. The software of the projects is based on the mikroC Pro for ARM Integrated Development Environment which includes a compiler, simulator, debugger, and ARM microcontroller programmer software. In this Chapter the design of several CAN bus based projects are given. All projects are described with the following sub-headings: • Project number and title of the project • Brief description of the project • Block diagram of the project • Circuit diagram of the project • Program description using PDL • Complete program listings • Description of the programs • Recommendations for future work (if necessary) In general, the following steps are required to develop a CAN bus based project: First of all, build the hardware, create the CAN bus nodes, making sure that the bus is terminated properly Create your CAN bus node software using the mikroC Pro for ARM Integrated Development Environment (www.mikroe.com). The software normally consists of the following: • Calculate the required CAN bus timing parameters • Initialize the CAN bus by calling to function CANxInitializeAdvanced • Set CAN bus to initialization mode by calling to function CANxSetOperationMode • Set CAN bus filter mask by calling to function CANSetFilterScale32 • Set CAN bus to normal mode to function CANxSetOperationMode • Use CANxWrite or CANxRead to write or read data from the CAN bus respectively The first project is simple but it is important as it describes the basic hardware and software used in all projects. Readers should learn the first project in detail before moving on to other projects. 13.1 PROJECT 1 – Remote LED
Description This project consists of two nodes, called BUTTON and LED. At node BUTTON there is a push-button switch. At node LED there is an LED. Pressing the push-button turns ON the LED, and releasing the push-button turns OFF the LED. This process is repeated continuously.
● 185
CAN Arduino Dogan.indd 185
30-05-16 13:07
Controller Area Network - Projects with ARM and Arduino
Block Diagram The block diagram of the project is shown in Figure 13.1. At node BUTTON, a Clicker 2 for STM32 ARM Cortex-M4 compatible development board is used. This board has two push-button switches and two LEDs on it as described in Chapter 11. In this project the push-button switch connected to port pin PE0 (bit 0 of PORTE) is used. A CAN-1 transceiver board (www.mikroe.com) is used to interface the development board to CAN bus. The CAN bus is made up of 3 meters of twisted wire cable, terminated with a resistor at each end. At node LED, another Clicker 2 for STM32 development board is used. The LED connected to port pin PE12 (bit 12 of PORTE) is used in this project. As in the other node, a CAN-1 transceiver board is used to interface the second node to the CAN bus.
Figure 13.1 Block diagram of the project Circuit Diagram The circuit diagram of the project is shown in Figure 13.2. At node BUTTON, the push-button switch connected to port pin PE0 is used as described earlier. The output of this button is pulled HIGH with a resistor as shown in Figure 13.3. Thus, pressing the button makes the switch output go to logic LOW. Port pins PB8 and PB9 are the CAN1 module CAN1_RX and CAN1_TX pins of the STM32F407VGT6 microcontroller respectively, and they are used for the CAN interface. Figure 13.4 shows these two pins at the edge connector of the Clicker 2 for STM32 board.
â—? 186
CAN Arduino Dogan.indd 186
30-05-16 13:07
Controller Area Network - Projects with ARM and Arduino
Figure 13.9 Terminating the CAN bus At node LED, the node hardware is the same as at node BUTTON. Here, the LED connected to pin 12 of PORTE (PE12) is used in this project (see Figure 13.3). The LED is turned ON when logic 1 sent to it. Figure 13.10 shows the two nodes and CAN bus. In this project the Clicker 2 for STM32 development boards are powered from the USB port of a PC.
Figure 13.10 The two nodes and the CAN bus Program Description (PDL) The program description is shown in Figure 13.11 as a Program Description Language (PDL), which basically consists of English like statements that describe the operation of the program.
â—? 190
CAN Arduino Dogan.indd 190
30-05-16 13:07
Chapter 13 • CAN BUS projects using ARM Microcontrollers
NODE: BUTTON (ID = 3)
NODE: LED (ID = 5)
Configure port pin PE0 as input
Configure port pin PE12 as output
Declare CAN bus flags
Declare CAN bus flags
Declare CAN bus timing parameters
Declare CAN bus timing parameters
Initialize CAN bus
Initialize CAN bus
Set operation mode to initialization Set operation mode to initialization Set filterscale Set filterscale Set operation mode to normal Set operation mode to normal DO FOREVER DO FOREVER Get push-button state
Read push-button state
Send push-button state to ID 5
IF state = 0 THEN
Wait 10ms ENDDO
Turn OFF LED ELSE
Turn ON LED
ENDIF Wait 10ms ENDDO
Figure 13.11 Operation of the program (PDL) Microcontroller Clock In this and all the remaining ARM based projects in this book, the Clicker 2 for STM32 development board with the STM32F407VGT6 microcontroller on-board is configured to operate from an external crystal of 25MHz. The microcontroller is configured to effectively operate from a clock frequency of 168MHz. The steps to set clock frequency are repeated below for convenience: Step 1: Click Project -> Edit Project Step 2: Set the clock parameters as shown in Figure 13.12 and 13.13.
Figure 13.12 Configuring the clock
â—? 191
CAN Arduino Dogan.indd 191
30-05-16 13:07
Chapter 13 • CAN BUS projects using ARM Microcontrollers
} } }
Figure 13.39 Node:DCMOTOR program listing 13.4 PROJECT 4 – CAN Bus With 3 Nodes
Description This project consists of three nodes, called BUTTONS, DCMOTOR, and STEPPER. At node BUTTONS, there are two push-button switches called DC_MOTOR and STEPPER_MOTOR. At node DCMOTOR there is a small DC motor. At node STEPPER there is a unipolar stepper motor. Pressing push-button DC_MOTOR activates the dc motor for 5 seconds. Similarly, pressing the push-button STEPPER_MOTOR turns the stepper motor one complete revolution. Block Diagram The block diagram of the project is shown in Figure 13.40. A Clicker 2 for STM32 ARM Cortex-M4 compatible development board is used at each node together with a CAN-1 transceiver module as in the previous projects. A twisted wire 3m long CAN bus is used in the project where each node is connected through the transceiver modules. The microcontroller (STM32F407VGT6) on the Clicker 2 for STM32 development board is operated from a 25MHz external crystal. The actual operating clock frequency of the microcontroller is set to 168MHz as described in Project 1. There are two push-button switches on the Clicker 2 for STM32 development board, connected to port pins PE0 and PA10. At node BUTTONS, the push-button switch at port pin PE0 is called DC_MOTOR, and the button at port pin PA10 is called STEPPER_MOTOR. At node DCMOTOR, a Relay Click board is plugged-in to mikroBUS Socket 2 of the development board. The Relay Click board has two solid-state relays on it, named as RELAY1 and RELAY2. In this project, when Socket 2 is used, RELAY1 and RELAY2 are controlled from microcontroller port pins PD12 and PE8 respectively. In this project, the relay connected to pin PD12 (i.e. RELAY1) is used (interfaced by two screw type terminal connectors at the top right hand side of the board, see Figure 13.31). Figure 13.32 shows the Relay Click board plugged-in to mikroBUS Socket 2. As in the other nodes, a CAN-1 transceiver board is used to interface to the CAN bus. At node STEPPER, a unipolar stepper motor driver module is used (see Figure 13.41) together with a stepper motor (see Figure 13.42). The driver module is connected to mikroBUS Socket 2 pins of the Clicker 2 for STM32 development board (see Figure 13.43).
● 225
CAN Arduino Dogan.indd 225
30-05-16 13:07
Chapter 13 • CAN BUS projects using ARM Microcontrollers
NODE: BUTTONS (ID = 3) NODE: DCMOTOR (ID = 5) Configure pins PE0 and PA10 as input Configure port pin PD12 as output Declare CAN bus flags Declare CAN bus flags Declare CAN bus timing parameters Declare CAN bus timing parameters Initialize CAN bus Initialize CAN bus Set operation mode to initialization Set operation mode to initialization Set filterscale Set filterscale Set operation mode to normal Set operation mode to normal DO FOREVER DO FOREVER Get DC_MOTOR state Read push-button state Send DC_MOTOR state to ID 5 IF state = 1 THEN Get STEPPER_MOTOR state Turn ON relay for 5s Send STEPPER_MOTOR state to ID7 ENDIF ENDDO ENDDO
NODE: STEPPER (ID = 7) Configure PD12,PE14,PD8,PD9 as output Declare CAN bus flags Declare CAN bus timing parameters Initialize CAN bus Set operation mode to initialization Set filterscale Set operation mode to normal DO FOREVER Read push-button state IF state = 1 THEN Rotate for 1 revolution ENDIF ENDDO
Figure 13.49 Operation of the program (PDL) Microcontroller Clock The microcontroller clock is set to 168MHz as described in the previous projects. CAN Bus Timing Parameters In this project, the CAN bus is assumed to have the following requirements (same as in the previous projects): Bit rate = 125 kbps Bus length = 3m Bus propagation delay = 5 ns/m
● 231
CAN Arduino Dogan.indd 231
30-05-16 13:07
Controller Area Network - Projects with ARM and Arduino
Controller TX delay = Controller RX delay =
80 ns 120 ns
Timing parameters are as obtained in the previous projects. i.e.: SJW = 4 BRP = 24 PHSEG1 = 4 PHSEG2 = 4 PROPSEG = 5 Node: BUTTONS Program Listing Figure 13.50 shows the program listing of node BUTTONS (program BUTTONS.c). At the beginning of the program the three node IDs are defined with node BUTTONS assigned value 3, node DCMOTOR assigned value 5, and node STEPPER assigned value 7. After defining the variables used in the program, port pins PE0 (button DC_MOTOR) and PA10 (button STEPPER_MOTOR) are configured as digital inputs. Then the CAN bus send initialization flags are defined. Timing parameters are then entered and the CAN bus is initialized using function CAN1InitializeAdvanced. CAN bus is set into initialization mode and function CANSetFilterScale32 is called to set the filter flags and the identifier. CAN bus is then returned to its normal operation mode. The remainder of the program is executed in an endless loop where the state of both push-button switches are read. If the button DC_MOTOR is not pressed (button state = 1) then the data to be sent is set to ‘0’, otherwise the data is set to ‘1’. Function CAN1Write is then called to send the data to node DCMOTOR. Similarly, if the button STEPPER_MOTOR is not pressed (button state = 1) then the data to be sent is set to ‘0’, otherwise the data is set to ‘1’. Function CAN1Write is then called to send the data to node STEPPER. /********************************************************************** NODE: BUTTONS ============== This project consists of three CAN bus nodes. One of the nodes is called BUTTONS, the second node is called DCMOTOR, and the third node is called STEPPER. Two push-button switches, named DC_MOTOR and STEPPER_MOTOR are connected to node BUTTONS. Node DCMOTOR has a small DC motor connected to it using a Relay Click board. Node STEPPER has a small unipolar stepper motor connected to it through a stepper motor driver circuit. Whenever the push-button DC_MOTOR is pressed the relay is activated at node
● 232
CAN Arduino Dogan.indd 232
30-05-16 13:07
Chapter 13 • CAN BUS projects using ARM Microcontrollers
DCMOTOR and the dc motor is activated and starts running for 5 seconds. Whenever the push-button STEPPER_MOTOR is pressed the stepper motor starts running at node STEPPER for a complete one revolution. This is the program of node BUTTONS of the CAN bus example. In this project three Clicker 2 for STM32 type ARM microcontroller development boards are used, one for each node. This development board uses the STM32F407VGT6 type ARM Cortex-M4 microcontroller chip, operating with a crystal of 25MHz. The actual operating frequency of the microcontroller is configured to 168MHz via the PLL. Two CAN-1 boards are used, one at each node. CAN-1 board consists of a MCP2551 type CAN bus transceiver which are connected to the CAN bus and to the Clicker 2 for STM32 development boards. Pin CANRX and CANTX of the microcontroller are connected to pins RXD and TXD of the transceiver chip respectively. Pins CANH and CANL of the transceiver chip are connected to the CAN bus. In this project, push-button switches are connected to port pins PE0 and PA10. The push button switch connected to PE0 (button DC_MOTOR) controls the dc motor, while the one connected to PA10 (button STEPPER_MOTOR) controls the stepper motor. Normally the switch outputs are at logic 1 and go to logic 0 when a pushbutton switch is pressed. The switch states are sent over the CAN bus to node DCMOTOR or to node STEPPER motor. CAN timing parameters used in this project are: Microcontroller clock: 25MHz crystal (actual operating frequency 168MHz) CAN Bus bit rate:
125 Kb/s
Prop_Seg:
5
Phase_Seg1:
4
Phase_Seg2:
4
SJW:
4
BRP:
24
Author:
Dogan Ibrahim
Date:
February 2016
File:
BUTTONS.C
***********************************************************************/ #define DC_MOTOR GPIOE_IDR.B0
// Button at port pin PE0
#define STEPPER_MOTOR GPIOA_IDR.B10
// Button at port pin PA10
//
â—? 233
CAN Arduino Dogan.indd 233
30-05-16 13:07
Chapter 14 • Using CAN Bus analyzers
Chapter 14 • Using CAN Bus analyzers Bus analyzers can be invaluable tools during the development of a new CAN bus based project. In addition, these devices can be very useful as teaching aids where students can analyze and learn collected frame structures and timing details. CAN bus analyzers are available with varied functionalities and prices. Basically, a bus analyzer consists of a small hardware device (called analyzer hardware), and a dedicated software (called analyzer software, usually running on a PC). One end of the analyzer hardware is attached to the CAN bus as a node, while the other is usually connected to a PC via USB. Once the analyzer software is activated, the analyzer hardware starts collecting all the frames sent over the bus, with time stamping. The collected data can then be analyzed, and any data transmission errors or timing errors can easily be detected. In this Chapter we shall be looking at two different types of CAN bus analyzer and give an example use for each one. 14.1 Using a Logic Analyzer as a CAN Bus Analyzer
In this section we shall be looking at the use of a logic analyzer which has additional software that allows it to be used as a CAN bus analyzer. The device will be connected to a CAN bus and frames sent over the bus will be collected and analyzed. Readers should find this section useful as it will demonstrate the actual data being sent over CAN bus. The analyzer device selected in this section is the LAP-C 16032 logic analyzer from Zeroplus Logic Cube (source: http://www.nkcelectronics.com). Figure 14.1 shows a picture of this analyzer.
Figure 14.1 LAP-C 16032 logic analyser
● 245
CAN Arduino Dogan.indd 245
30-05-16 13:07
Chapter 15 • CAN SPI
Chapter 15 • CAN SPI CAN SPI is the hardware and software used to create a CAN node when the microcontroller used in a project has no built-in CAN controller hardware. As a result, we can create a CAN bus node using CAN SPI hardware and any type of microcontroller. The only requirement is that the microcontroller must support SPI communications (either in software or hardware). CAN SPI hardware is usually a small board containing a CAN controller and transceiver chip. It usually sits between the microcontroller I/O pins and the CAN bus (see Figure 15.1).
Figure 15.1 CAN SPI This Chapter describes the mikroC Pro for ARM language CAN SPI library of functions that are available for the STM32 type ARM Cortex-M4 microcontrollers. An example is given in a later section to show how CAN SPI functions can be used in a two node CAN bus project. 15.1 CAN SPI Functions
mikroC Pro for ARM supports CAN SPI functions for the STM32 type ARM microcontrollers given in this section (notice that these functions are developed for hardware using MCP2510 or MCP2515 CAN bus controller chips). Before looking at functions, it is worthwhile to look at the basic architecture of MCP2515 type CAN controller chips. The MCP2515 CAN controller has the following modes of operation: Configuration Mode: The CAN module is initialized in this mode. Transmission or reception of frames are not allowed in this mode. Error counters are cleared in this mode. Normal Operation Mode: Where both transmission and reception of data frames are allowed. Listen-Only Mode: Usually used to monitor bus status. The module can receive messages, including errors, but cannot transmit frames. Loop-Back Mode: This mode is used for testing where messages can be directed from internal transmit buffers to receive buffers without actually being transmitted.
● 255
CAN Arduino Dogan.indd 255
30-05-16 13:07
Chapter 16 • Using Arduino with CAN Bus
Chapter 16 • Using Arduino with CAN Bus Arduino is one of the most popular microcontroller development systems used by computer and electronic engineering students and hobbyists. The first Arduino was introduced in the year 2005 with the aim of providing a low-cost, easy to use microcontroller development board. Arduino boards consist of an Atmel 8, 16, or 32-bit AVR microcontroller with connectors and sockets for external interface and programming. Many shields are available that can be stacked on top of an Arduino board and these shields provide additional peripheral capabilities, such as 7-segment displays, LCDs, motor controllers, CAN bus controllers, ADC and DAC converters, and many more. Arduino boards are supported by an integrated environment that includes a script language, compiler and programmer software. The boards are programmed through their serial ports. Currently there are many types of Arduino boards available with different sizes and capabilities. Some of the popular ones are: Entry Level Boards: Arduino Uno, Arduino Pro, Arduino Nano, Arduino starter Kit Enhanced Level Boards: Arduino Mega, Arduino Zero, Arduino Due Internet Of Things Compatible Boards: Arduino Yun, Arduino MKR1000, Arduino Ethernet Shield, Arduino Wi-Fi Shield Wearable Boards: Arduino Gemma, Lilypad Arduino USB, Lilypad Arduino Simple In this Chapter we shall not be going into details of Arduino hardware and software in any length. It is assumed that the readers are familiar and have used the Arduino Uno board in at least one project. There are many books, articles, projects, and internet sources on Arduino hardware and software and interested readers should refer to such sources. In this Chapter we shall look at using one of the most popular Arduino boards, the Arduino Uno (Figure 16.1) in a CAN bus based example project. A CAN bus shield is used in this example to provide a CAN bus controller interface to the Arduino development board. Readers should note that the example given in this Chapter is for the Arduino Uno board only and the example may not work on other Arduino boards. Also, the CAN bus shield used in this Chapter is applicable to the Arduino Uno only.
● 273
CAN Arduino Dogan.indd 273
30-05-16 13:07
Controller Area Network - Projects with ARM and Arduino
Figure 16.1 Arduino Uno board 16.1 Arduino CAN Bus Shield
The Arduino Can bus shield is hardware that can be stacked on top of the Arduino Uno board and provides a CAN bus interface to the Arduino board. There are several CAN bus shield boards available in the market. The one used in this Chapter is the one manufactured by Seeed Studio (www.seeedstudio.com), shown in Figure 16.2. The board can be connected to a CAN bus via the 9-pin connector or using the two pin screw terminal at the edge of the board. The board adopts MCP2515 CAN bus controller with SPI interface and MCP2551 CAN transceiver chip. The main features of the board are: • Implements CAN V2.0B • Data speed up to 1Mb/s • SPI interface • Standard (11 bit) and expanded (29 bit) data and remote frames • Two receive buffers • Two LED indicators • Bus terminator resistor (120 ohm) included on-board
Figure 16.2 Seeed Studio CAN bus shield
● 274
CAN Arduino Dogan.indd 274
30-05-16 13:07
Index
Index Symbols 82C200 CAN
D 29
A Acceptance Filters ADC converter Application Layer
Data Frame
60
Data Link
39
Data Link Protocols
40
79
Debugging 160
208
DeviceNet 31
41
DLC 67
B Bit Stream Processor
103
Bit Timing Segments
88
dominant state
50
D-type connector
53
E
Bootloader 169
ECU 32
Bus Fault
EMC performance
46
EOF frame
69
Error Active mode
76
Error Frame
60
Error Passive mode
76
150
C cable stubs
49
CAL 30 CAN 2.0A frames CAN bus analyzers
60 107
F
CAN bus arbitration
63
fiber-optics 26
CAN bus error states
77
FTDMA 23
CAN clock
86
FTP 41
CAN controller
99
CAN_HI 32
G
CAN_LO 32
GPIOs 136
CAN node
177
CANopen 29
H
CAN Overload frame
69
High Speed External
CAN SPI Click board
49
CAN SPI Functions CAN transceiver
255 99
128
I Intel 82526
29
CiA 29
Interframe gap
73
Class A networks
17
interframe space
Class B networks
17
Interrupt Assistant
Class C networks
17
ISO
Class D networks
17
ISO-11898 48
52
ISO 11898:1993 standard
CMOS logic Configuring the Clock correct grounding
61 151 30, 39 30
129 48
L
Cortex-M4 121
lambda sensor
CRC check
66
LM35DZ temperature sensor
CRC generator polynomials
65
Local Interconnect
CSMA/CR 18
Logical Link Control Logic Analyzer
36 203 19 42 245
â—? 285
CAN Arduino Dogan.indd 285
30-05-16 13:07
CONTROLLER AREA NETWORK Dogan Ibrahim
ISBN 978-1-907920-50-9
DESIGN
www.elektor.com
The book should be useful source of reference to anyone interested in finding an answer to one or more of the following questions: • What bus systems are available for the automotive industry? • What are the principles of the CAN bus? • What types of frames (or data packets) are available in a CAN bus system? • How can errors be detected in a CAN bus system and how reliable is a CAN bus system? • What types of CAN bus controllers are there? • What are the advantages of the ARM Cortex-M microcontrollers? • How can one create a CAN bus project using an ARM microcontroller? • How can one create a CAN bus project using an Arduino microcontroller? • How can one monitor data on the CAN bus?
CONTROLLER AREA NETWORK
LEARN
Elektor International Media BV
This book is written for students, for practising engineers, for hobbyists, and for everyone else who may need to learn more about the CAN bus and its applications. The book assumes that the reader has some knowledge of basic electronics. Knowledge of the C programming language will be useful in later chapters of the book, and familiarity with at least one microcontroller will be an advantage, especially if the reader intends to develop microcontroller based projects using CAN bus.
PROJECTS WITH ARM AND ARDUINO
● DOGAN IBRAHIM
Dogan Ibrahim is a Fellow of the Institution of Electrical Engineers. He is the author of over 60 technical books, published by international famous publishers, such as Wiley, Butterworth, and Newnes. In addition, he is the author of over 250 technical papers, published in journals, and presented in seminars and conferences.
This book details the use of the ARM Cortex-M family of processors and the Arduino Uno in practical CAN bus based projects. Inside, it gives a detailed introduction to the architecture of the Cortex-M family whilst providing examples of popular hardware and software development kits. Using these kits helps to simplify the embedded design cycle considerably and makes it easier to develop, debug, and test a CAN bus based project. The architecture of the highly popular ARM Cortex-M processor STM32F407VGT6 is described at a high level by considering its various modules. In addition, the use of the mikroC Pro for ARM and Arduino UNO CAN bus library of functions are described in detail.
CONTROLLER AREA NETWORK
PROJECTS WITH ARM AND ARDUINO
Dogan Ibrahim LEARN
DESIGN
SHARE
SHARE
LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHAR GN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHAR