Give away medical masks when you place an order. learn more

CAN Primer Creating Your Own Network

CAN is a flexible network that is easy to implement. If you are considering networking topologies for your next embedded design, this article will set you on the right path.

CAN is extensively used in automobiles and trucks and can be found in multiple applications. There are many “application” layers available for CAN, such as ISO 15765 (cars), J1939 (trucks), and CANopen (factory automation), but it is very easy to develop your own protocol to fit and simplify your needs. Modern CAN transceivers provide a stable and reliable CAN physical environment without the need for expensive coaxial cables. Most of the mystery of CAN has dissipated over the years. There is plenty of example CAN software available to help you quickly develop your own network.

A CAN controller is a sophisticated device. Nearly all the features of the CAN protocol described below are automatically handled by the controller with almost no intervention by the host processor. All you need to do is configure the controller by writing to its registers, write data to the controller, and the controller then does all the housekeeping work to get your message on the bus.

The controller will also read any frames found on the bus and hold them in a small FIFO memory. It will notify the host processor that this data is available, which is then read from the controller. The controller also contains a hardware filter mechanism that can be programmed to ignore the CAN frames you do not want passed to the processor.

For the purposes of this article; we will assume a CAN network consists of the physical layer (the voltages and the wires) and a frame consisting of an ID and a varying number of data bytes. CAN has the following general attributes:

  1. 11- or 29-bit ID and from zero to eight data bytes. These can be dynamically changed “on the fly.”
  2. Peer-to-Peer network. Every node can see all messages from all other nodes. A node cannot read its own messages.
  3. Nodes are easy to add. Attach one to the network with two wires plus a ground.
  4. Higher priority messages are sent first depending on the value of the ID. A lower ID has the highest priority.
  5. Automatic retransmission of defective frames. A node will “bus-off” if it causes too many errors.
  6. Speeds from approximately 10 Kbps to 1 Mbps. All nodes must operate at the same frequency.
  7. The twisted differential pair provides excellent noise immunity and some decent bus fault protection.
  8. The CAN system will work with the ground connection at different DC levels or no ground at all.
The CAN system layout

A CAN network consists of at least two nodes connected together with a pair of twisted wires, as shown in Figure 1. A ground wire can be included with the twisted pair or separately as part of the chassis. One twist per inch (or more) will suffice, and the integrity of the ground is not necessary for normal operation. As in any differential systems, the voltage levels between the wire pair are important, and not their values to ground. CAN is completely described in ISO 11898. The maximum length of the network is dependent on the frequency, number of nodes and propagation speed of the wire. It is relatively easy to have a 20 node (or more), 500 Kbps system running 30 or 40 feet (or more). The drops should be less than three feet and randomly spaced to reduce standing waves. These issues all become more important at higher bus speeds.

Figure 1: A CAN network.

Since the twisted pair is a transmission line, 120 ohm termination resistors are needed at both ends of the backbone. Do not put any resistors at the nodes. Your total resistance value as measured between the two twisted wires will be 60 ohms. CAN is a broadcast system. Any node can “broadcast” a message using a CAN frame on a bus that is in idle mode. Every node will see this message. A “message” can be considered the same as a CAN frame until you need to use more than one frame to send a long message. It is up to the individual node if it must react to a CAN frame or just ignore it.

A node schematic

Figure 2 shows the schematic diagram from the Keil MCBSTM32E™ evaluation board. IC1 is a Texas Instruments CAN transceiver that performs the conversion between the single-ended CAN controller CAN Tx and CAN Rx signals to the bidirectional differential pair of the CAN bus called CANH and CANL (High and Low). This schematic is complete.

Figure 2: Schematic diagram from the Keil MCBSTM32E evaluation board.

The STM32 CAN I/O is TTL, CMOS and 5 V tolerant, making it exceptionally easy to design the interface. This transceiver IC1 connects to the STM32 microprocessor IC2, which contains an integral CAN controller via two pins: D (Driver input) and R (Receiver output). The corresponding nomenclature on the STM32 is CAN Rx and CAN Tx. CAN Tx connects to D. CAN Rx connects to R. Some processors have multiple CAN controllers. These are usually used in routers, gateways or to create more receiver FIFO memory for intentionally slowed down CPUs (for EMI reasons). For general use, a node normally needs only one controller. If it had at least two, it could talk to itself.

RS on IC1 (slope control) is used to adjust the rise and fall times of the output edges to limit EMI from the twisted pair. Note R4 is a 120 ohm termination resistor. This evaluation board is meant to be used with one other board as a small test network. If this board is used as a node, and is not at one of the ends, this resistor should be removed and external resistors used. P17 corresponds to a generally accepted standard for CAN on DB9 connectors. P17 Pin 7 is the CAN Hi bus line and pin 6 is CAN Lo. If CAN Hi and CAN Lo are reversed, the network will not operate properly. It might not work at all.

There are three physical layers used in CAN: Hi-Speed, Fault Tolerant and Single Wire. Hi-Speed is the most common and is the one we will use in this article. Fault Tolerant offers more robustness as its name implies and is used more often in European autos. Single Wire is used by General Motors as a low-speed body network along with Hi-Speed main network.

Hi-Speed in cars has a speed of 500 Kbps, trucks are 250 kbps. CANopen runs up to 1 Mbps. Fault Tolerant is usually 125 kbps, and GM Single Wire is normally 33.33 kbps. One Mbps in a large system is difficult to handle. 500 kbps is easier.

To change from one to the other requires only the transceiver chip to be exchanged and probably changing the speed. These three layers cannot be physically connected to each other as the voltage levels are different. Use a router or gateway to join different CAN networks together. Any CAN controller will properly service all three layers of CAN.

The Hi-Speed CAN physical layer is a pair of twisted wires with a 120 ohm termination resistor at each end and twisted wire drops to the individual CAN nodes. A node can be directly connected to the bus.

CAN Hi voltage, with respect to ground, changes between 2.5 to 4 volts nominal. CAN Lo changes from 2.5 to 1 volt. Therefore, the difference between the two is either 0 volts (is logical “1”) or 3 volts (logical “0”). 0 is known as the “dominant” state and 3 volts is the “recessive” state.

These two signals, CAN Hi and CAN Lo, are 180 degrees out of phase. Bus idle is when the voltage difference is zero.

The CAN frame

The CAN frame has many fields but can be simplified to a Programming Model as shown in Figure 3. These fields must be written by software or read from the CAN controller registers. The CAN configuration registers are not included.

Figure 3: CAN Frame Programming Model.
  • IDE: Identifier Extension: 1-bit - specifies if the ID field is 11 or 29 bits.
    If IDE = 0, then the ID is 11 bits.
    If IDE = 1, then the ID is 29 bits.
  • DLC: Data Length Code: 4 bits - specifies number of data bytes in frame from 0 through 8.
  • ID: Identifier: 11 or 29 bits as set by IDE. This part of the CAN frame sets the priority.
  • Data Bytes: 0 through 8 bytes. A CAN frame with only an ID field and no data bytes is valid and useful.
ID: Identifier: 11 or 29 bits

The Identifier can be used for any purpose. It is often used as a node address or to identify requests and responses. CAN does not specify what the ID should be.11-bit is sometimes called Standard CAN and 29-bit is called Extended CAN.
  1. If two or more CAN messages are put on the bus at the same time; the one with the highest priority (the lowest value) ID will immediately get through. The others will be delayed and will be resent as soon as possible.
  2. An ID of 0 has the highest priority and will always get through. An 11-bit ID has priority over any 29-bit ID.
  3. The ID size can be changed at any time for a mix of 11- and 29-bit IDs. The controller can easily sort this out.
  4. Messages tend to start transmitting at the same time. It is not permissible for a CAN node to start transmitting if another is already transmitting. This will cause a bus error.
  5. Note that a CAN controller can be configured to pass only certain messages to its host processor. Choose ID values carefully to take advantage of this, if needed. This can take a large work load off of a node’s processor.
  6. Use the ID for data, node addressing, commands and request/response sequences. Commercial protocols use these in practice. Choose any method or create your own to best suit your purpose.
  7. Make sure two nodes will never send the same ID value at the same time. It is illegal but possible to do this. If two messages sent at the same time are identical, they will be seen as one. If the data bytes are different, this will result in a bus error, and the frames will be resent continuously, creating havoc on the bus until bus-off occurs.
Data bytes

Select from zero to eight data bytes using the 4-bit DLC field.
  1. Any number of data bytes can be mixed on the CAN bus. The controller can easily sort this out.
  2. By always using only one number of data bytes, software will be much simpler to write and maintain.
  3. The data bytes can contain anything. It will not be prioritized like the ID. CAN does not specify data contents.
  4. Commercial protocols such as J1939 use these for data as well as control bits for multi-frame transmission schemes.
Remote frames

Though not used often, a remote frame is a quick method of getting a response from another node(s). It is a request for data. The requesting node sends out a shortened CAN frame with only a user specified ID number and the number of data bytes it expects to receive (the DLC is set). No data field is sent. The responding node(s) sees this ID and DLC, recognizes that it has the desired information and sends back a standard CAN frame with the same ID, DLC and with its data bytes attached. All of this (except that the response node recognizes the ID and DLC) is implemented in the CAN controller hardware. Everything else must be configured by the user software.

Bus loading

Many CAN networks work on a bus loading from 15 to 35 percent and this is increasing. A higher bus loading can cause lower priority messages to be delayed, but these messages will still get through in a timely fashion. It is quite difficult to achieve 100 percent bus loading although one can come quite close. Overall system performance does not drop greatly at high bus loading.

It is possible to get very high bus loads for a very short period of time in any CAN network. CAN does not automatically space out messages. It is possible to get a series of back-to-back messages that will equal nearly 100 percent bus loading. One solution is to select only those messages needed by a node by programming its acceptance filter. Another is to have your software space out the messages. This problem is difficult to diagnose.

Bus speed

Bus speed in a system is a balancing act between things such as propagation delays (from bus length) and EMI emissions versus necessary data throughput. Run the network as fast as possible for stable operation and with enough throughput. Do not run it faster than necessary, but make some room for later expansion.

If the network is not stable, make sure there are two good termination resistors at each end of the network. Try slowing the CAN speed down to see if this helps. Resistors can be ordinary 120 ohm 1/2 watt carbon type. This is not critical.

TIP: How to determine the frequency of a CAN signal: (This is the best and sometimes only way to determine this.)
  1. Connect an oscilloscope hot lead to CAN Hi and its ground to CAN Lo. The scope ground must be isolated from the CAN ground. You can go from ground to one of the CAN leads, but the signals will be lower and noisier.
  2. Display a trace. A storage scope may be needed to see just one trace due to the non-repetitive nature of CAN.
  3. Pick the smallest width signal pulse and measure its time period in seconds as accurately as possible.
  4. Invert this value (divide into 1) to obtain the CAN speed in bits per second.
Bus errors

Recall that all the nodes (including the transmitting node) check each CAN frame for errors. If an error is detected, the following occurs:
  1. Any or all of the nodes will signify this fact by driving the bus to logical 0 (dominant state) for at least six CAN bits.
  2. This violates the Bit Stuffing rule (never greater than 5 bits the same polarity), so every node sees this as an error.
  3. This so called “Error Frame” signals to all nodes a serious error has occurred.
  4. The transmitting bus abandons the current frame and adds four to its 8-bit TEC (Transmit Error counter) register.
  5. If this TEC equals 0xFF, the transmitting node goes BUS OFF and takes itself off the bus (it is zero at RESET).
  6. If not, it attempts to retransmit its message. It will still have to go through the priority process with other messages.
  7. All other nodes also abandon reading the current frame, and adds four to each REC (Receive Error Counter) register.
  8. Any nodes that have messages queued up for transmission will transmit now. All others start listening to the bus.
  9. Hopefully, this time the message(s) will be broadcast and received error free. Each time a frame is transmitted and/or received successfully, the corresponding TEC and REC registers are decremented (usually by only one).
TIP: Error counters? These are two 8-bit registers in every CAN controller and you can read these with your software. This is a good idea because it gives some indication of general bus health and stability. In a good CAN network, TEC and REC will equal zero. If it starts having higher values, something has happened to your network. The usual suspect is bad hardware. The problem is usually in either the wires or the transceiver chip.

Don’t forget that if something happens to the integrity of the twisted pair, such as CAN Lo disconnected; it might still work but with greatly reduced noise immunity (that is what differential signals do best). If the network is in a very noisy environment, there might be a lot more transient bus errors. This is very tricky to debug without knowledge of the REC and TEC register contents. Put this in the software and report it to the diagnostic routines.

In a general sense, TEC represents a given node’s errors and REC indicates the other nodes’ errors.

Bus off: As mentioned, if a transmitting node detects it has put too many bad frames on the bus, it will disconnect itself. It will assume that there is something very wrong with itself. To get back on the bus depends on how the controller is configured. It can take a controller RESET or a certain number of good frames received or what is configured to get back on.

TIP: How can you create a Bus Error for testing?

Have a node send a message at the wrong frequency. When this frame tries to get on the bus, this is certain to create a bus error condition. Some CAN controllers can send a one-shot frame.

BUS faults

This is different from a bus error. We normally think of a bus fault as something that has happened to the “wires” or the output transistors of the transceiver chip. Not all bus faults will result in a bus error. A bus error can be thought of as the CAN controllers’ reaction to a problem on the bus such as noise, faulty node that includes a bus fault.

What happens if one of the twisted pair opens or is shorted out? CAN has an automatic mechanism for this. Not all transceiver chips implement all of them. You can usually short CAN Lo to ground (ISO 11898 says CAN short Hi also) or open one CAN line. The ground needs to be connected for these to function. You cannot short both Hi and Lo together (Fault Tolerant will work) or open both up. You can cut the ground or have a large ground loop present and CAN will still work.

These will be detected as a bus error as described above. At least one node must try to transmit a frame in a bus fault condition to trigger a bus error. A bus in idle mode cannot trigger a bus error. When the bus fault is removed, in many systems the network will come back alive, if so configured. CAN has excellent noise immunity because of the twisted pair. The common mode noise gets cancelled out and the CAN signal is not affected (because it is 180 degrees out of phase).

The ground: The ground is not needed for CAN operation if the twisted pair is intact. This is readily shown with simple experiments. One experiment showed a small network still worked properly with two nodes having a 40 volts DC ground difference.

However, it is a good idea to include a good ground in the system design. Some bus faults need the ground to allow the transceiver to compensate.

Here are some bonus items that are not part of the CAN specification that might prove helpful in your system:

  1. Transmitting data sets greater than 8 bytes:
    Clearly, transmitting a data set greater than 8 bytes will take multiple frames and this will require some planning. Such schemes can become very complicated as they have to deal with a wide-ranging set of contingencies. By focusing on a narrow requirement set, design of a simpler protocol is possible.

    Most current schemes use the first data byte to contain the number of total data bytes to follow plus a counter to help determine which data byte is which. The ID usually identifies the node plus whether it is a request or response message. To use an existing protocol, see ISO 15765. This is what automobiles use. This includes OBDII diagnostics which is public information. This is a good example where one message can be comprised of many CAN frames.

  2. Periodic, Request/Response and Command Frames:
    Periodic: This technique sends a frame out periodically – several times a second is typical. This frame will contain data that any node can use and is identified by its ID. Examples are speed, position, pressure, and events.

    Request/Response: A node sends out a frame requesting certain specified information. Any other nodes that have the requested information then put it on the bus. The ID identifies the Request frame and the Response by changing one bit of the Request ID. ID 0x248 is a Request frame and 0x648 is its Response. The Request frame data bytes will specify what information is requested. The Response frame will contain the requested information or an error message.

    Command: A frame commanding some event is performed. The ID usually contains the address of the commanded node and the data bytes the actual command(s). Sometimes an acknowledge frame is returned.

    TIP: Consider a blend of these three types of traffic depending on your system’s needs.

  3. Time-outs:
    Automotive CAN networks use time-outs. This concept is easily and effectively transferred to systems in other fields. A time-out occurs when a node fails to respond to a request in a timely fashion. Time-outs are handled completely by software. The CAN specification does not provide this mechanism. A time-out is helpful to recover from problems with the network such as severe bus errors, catastrophic bus faults, faulty nodes, or intermittent connections.
The result is usually a limp-home mode in which a node will attempt to run itself without information from the rest of the network. In some cases, a punitive limp-home mode is entered that forces the user to perform repairs.

A good example is if the transmission fails and proper shifting becomes impossible. In this case, the module will go into limp-home mode and the transmission might be put into one gear, such as second, to allow the vehicle to still be driven.

This can be for safety reasons or to prevent further damage to the power train.

Heart-beats and Address Claiming: The other side to a time-out is a heartbeat. Periodic messages can be sent out to determine that all nodes are on the bus and active. CANopen uses such heartbeats. J1939 has a software mechanism in which each node can declare itself to be on the bus and be recognized by the other nodes. This is called “Address Claiming” and occurs during the system startup. These mechanisms are provided by your software.

Sequence of transmitting data on the CAN bus:
  1. Any node(s), seeing the bus idle for the required minimum time, can start sending a CAN frame.
  2. All other nodes start receiving it except those also starting to transmit a message. (They all start at the same time.)
  3. If any other node starts transmitting, the priority process starts. The node with the highest priority continues on and those with a lesser priority stop sending, immediately turn into a receiver, and receive the higher priority message.
  4. At this point, only one node is transmitting a message and no other nodes will start at this time.
  5. When the transmitting node has completed sending its message, it waits one bit time for the 1-bit ACK field to be pulled to a logic 0 by any other node (or usually all of them) to signify the frame was received without errors.
  6. If this happens, the transmitting node assumes the message reached its recipient, sends the end-of-frame bits and goes into receive mode or starts to send its next message if it has one. The receiving nodes pass the received message to their host processors for processing unless the acceptance filtering prevents this action.
  7. At this time, any node can start sending any messages or the bus goes into the idle state. Go to 1.
  8. If this does not happen (ACK bit not set), then the transmitting node retransmits the message at the earliest time allowed. If the ACK bit is never set, the transmitting node will send this message forever.
Transmitting notes:
  • How does a node know when it should transmit a message? Create the CAN frame you want to send by loading up the IDE, ID, DLC. Any data byte registers in the CAN controller and then, in most controllers, you set a bit that triggers sending the frame as soon as legally possible. After this, the controller takes care of sending all frame bits. Until the controller signals otherwise to the processor, you can assume the message was sent.
  • What if there is an error? All nodes, including the transmitting node, monitor the bus for any errors. If an error condition is detected, a node (or nodes) signify to the other nodes there is an error by holding the bus at logical 0 for at least six bus cycles. At this point, all nodes take appropriate action. The message being sent (and now aborted) will be resent but only a certain number of times.
  • What if no node wants or uses the message? Nothing. The ACK bit only says that the CAN frame was transmitted without errors and at least one node saw this frame error free. Remember the transmitting frame cannot ACK itself. CAN does not provide any acknowledgment mechanism that a frame was used or not received by its intended recipient. If needed, you will have to provide this in your software as many systems do.

  • TIP: In a periodic system, if a node misses a message, it does not matter much as another copy will be along shortly.
Sequence of receiving data from the CAN bus:
  1. All nodes except those currently transmitting frames are in listening mode.
  2. A CAN frame is sent using the procedure as described previously in “Sequence of Transmitting data on the CAN Bus.”
  3. This frame is received by all listening nodes. If deemed to be a valid CAN message with no errors, the ACK bit is set. In CAN terminology, the bus is set to the “dominant” state as opposed to the “recessive” state.
  4. The frame is sent through the controller’s acceptance filter mechanism. If this frame is rejected, it is discarded. If accepted, it is sent to the controller FIFO memory. If the FIFO is full, the oldest frame is lost.
  5. The host processor is alerted when a valid frame is ready to be read from the FIFO. This is done either by an interrupt or a bit set in a controller register. This frame must be read as soon as possible.
  6. The host processor decides what to do with this message as determined by your software.
Receiving notes:
  • Use polling or interrupts to alert the host processor that a frame is available. Polling is where the host processor “polls” or continuously tests the bit mentioned in sequence 5. Polling runs the risk of losing or “dropping” a frame but is sometimes easier to implement and debug. Interrupts cause the processor to jump to an interrupt handler in which the frame is read from the controller. Using interrupts is the recommended method.
  • What happens if a message is “dropped?” This can cause some problems as CAN itself does not have a mechanism for acknowledging a CAN frame. If desired, this must be added to your software. In the case of Periodic Messages, it doesn’t normally matter as a replacement message will be along shortly.
  • How fast do I have to read the FIFO to not drop messages? It depends on the CAN speed, frame size, and bus loading. It is a good idea to read these frames as soon as possible because once a frame is dropped, it will not be automatically recovered or resent by the transmitting node. It is gone forever unless you provide a suitable mechanism in your software to have it resent.
CAN controllers and their errata sheets

As mentioned before, CAN controllers are very sophisticated modules. When experiencing trouble getting something to work or an unexpected crash or result, it is common to search the code for the error causing this. Sometimes the answer lies in the errata sheet and not in your software.

Note that technical support staff statistics show that most errors are in the user software code, so check this carefully.

Obtain all the latest errata sheets and read them, to save time. Sometimes the weirdest problems are caused by these defects. And then, of course, you might have to be prepared for the day these bugs get fixed and show up in real silicon on your board. Most issues will be in the controllers and not the simpler transceivers.

There are several CAN newsgroups that can help you with your network. Remember that not all people in these groups are experts and there is some risk of getting poor information. Fortunately, these people are in the minority.

Test tools

The biggest problem in getting your first CAN network running is that in order to see some messages, you have to have both a receiving node and a transmitting node properly working at the same time. This can be quite the onerous job. There are two ways to help here. One way is to use a working node such as an evaluation board with proven CAN examples provided. You can attempt to receive these known good CAN frames with your node.

Second, you can purchase a CAN test tool. This is the best idea. These provide both sending and receiving capabilities and act as a CAN node. There are two types: simple low-cost devices that provide basic creating and displaying bus traffic and those offering advanced capabilities.

Typical sources for inexpensive tools are SYS TEC (, and PEAK which is also sold in the USA through
When developing a more capable and powerful CAN system, consider a CAN analyzer. These offer very advanced features such as triggering, filtering and a database where your ID and data bytes are displayed in words rather than raw hex numbers. This will save a lot of time and make for a better, more reliable product. Typical suppliers are Dearborn Group, Vector CANalyzer, National Instruments, and Intrepid. Do not be afraid to use an automotive type device even if your application is something else. CAN is CAN no matter where it is used.

Bit stuffing

The CAN protocol states that when there are five consecutive bits of the same polarity, one bit of opposite polarity will be inserted to maintain the counter accuracy. These bits make the CAN frame longer and are very common. These bits are inserted and removed automatically by the CAN controller and are visible only when an oscilloscope is attached to the bus.

When bits are added (or not) to the CAN frame as various messages are sent on the bus, the changing frame length will look like jitter on the bus. It is not jitter of course; CAN just works this way.


You now have enough CAN theory to enable you to develop and troubleshoot a small CAN network. Now, on the next few pages, let us look at how we can program a real CAN controller to transmit and receive messages. There are some hands-on experiments you can try – the Keil evaluation software is free and no hardware is needed for one experiment. For the other, you will need an evaluation board with an STM32 processor and a Keil ULINK2 or ULINK-ME USB to JTAG adapter.

For more information relating to CAN please see:

For information regarding testing CAN networks:

A differential twisted pair of wires:

CAN demonstration software

In order to experiment with a CAN network it is useful to try a simulator before the real hardware. This document shows how to use the complete device simulation included in the Keil® Microcontroller Development Kit (MDK-ARM) for the STM32 ARM Cortex™-M3 microcontroller. No hardware is needed.

You can download the latest evaluation version of MDK-ARM at: and install it.

Keil also provides simulation software for NXP ARM processor-based devices and various 8051 processors that have CAN controllers. Luminary processors are supported by using the Luminary evaluation boards with either the ULINK2 or ULINK-ME adapters or connection to the Luminary USB on-board JTAG adapter.

Complete technical information on the ST CAN module is found in the Reference Manual RM0008 available from Other manufacturers have similar documentation available on their websites.

STMicroelectronics CAN controller for Cortex-M3 processors

Shown is a block diagram of the CAN controller. Here are the main points of all CAN controllers:

  1. I/O Pins: These connect to the CAN transceiver chip pins R and D as previously described.
  2. Parallel-Serial Converters: CAN is a serial bus while the processor is parallel. Conversion happens here.
  3. Tx mailbox: The messages to be transmitted are written here. ID, data (if any) and the DLC go here.
  4. Acceptance Filter: This passes only specified messages to the processor via the FIFOs. By default at RESET, these filters pass all messages to the FIFOs. Your software must configure them to filter messages.
  5. FIFO 0 & 1: Each Receive FIFO can hold three CAN messages. They provide a buffering system to the processor.
  6. Control, Status, Configuration registers: Your software must configure these registers, usually at initialization. Various flags and switches are found here. Examples are set CAN speed, request transmission, manage receive messages, enable interrupts and obtain diagnostic information. Keil provides examples on how to set and use these registers.
All CAN controllers have the same basic architecture. Different controllers will have differences in the number of receive FIFO buffers, transmit buffers, size of acceptance filters and the bit mapping, addresses and definitions of the various configuration registers. All CAN controllers are licensed by Robert Bosch GmbH in Germany and therefore they are able to exert considerable control over basic CAN attributes to make them consistent with various manufacturers.

This means that all CAN controllers can communicate with other brands in a reliable and predictable manner.

Figure 4: STMicroelectronics CAN controller for Cortex-M3 processors.

Keil example CAN program
  1. Start µVision by clicking on its icon on your desktop.
  2. Select Project/Open Project. Open the file C:\Keil\ARM\Boards\Keil\MCBSTM32\CAN\CAN.Uv2.
  3. Make sure “Simulator” is selected in the Target window.
  4. There is a typo in a source file. In the file CanDemo.c, go to line 126. It will probably be: delay (45000000); // Wait for initial display (~5s) This delay will be too long. Please change this to a lower value. 45000 works well.
  5. Compile the source files by clicking on the Build icon. They will compile with no errors or warnings.
  6. Click on the Options for Target icon. Then, select the Debug tab and confirm “Use Simulator” is checked.
  7. Enter the Debug mode by clicking on the debug icon. Select OK when the Evaluation Mode box appears.
  8. Position the Toolbox, CAN: Communication and CAN: Controller windows as appropriate.
  9. Click on the RUN icon. Note: Stop the program with the STOP icon.
  10. Note CAN messages with an ID of 0x21 will appear in the CAN: Communications window. You can see both the transmit and receive frames. The CAN controller is in a special Test Mode that allows it to see its own messages.
  11. In the Toolbox window, click on the “Analog Sweep 0…3.3 V” button.
  12. Changing data values representing output from the A/D convertor will now appear in the CAN messages.
The Keil CAN demonstration software: How it works…

Keil provides a working CAN example with their development tools. You have already compiled and run this example. You can view and edit the C source files whether in debug mode or not, but to compile them you must not be in debug mode. This example uses almost no assembly code as it is (nearly) entirely written in C. Any source file can be opened in µVision, if not already visible, by clicking on File/Open and selecting it. There are three source files we will look at:

Can.h: This file defines a structure to contain the information used to construct the CAN frame and create two instances of it.

Can.c: This C code initializes the CAN controller, writes and transmits a message, receives a message, configures the Acceptance Filters and provides the transmit and receive interrupt handlers.

CanDemo.c: The main function is located in this file. CanDemo.c is the heart of the demonstration program and calls the functions in Can.C.

1) Can.h
The CAN structure CAN_Msg: (lines 23-29, 42 & 43)

The structure declaration in Can.h is shown. You should now be able to recognize each of these elements. You can enter either an 11- or 29-bit identifier. Two instances of CAN.msg are invoked and are shown below: CAN_TxMsg and CAN_RxMsg. CanDemo.c writes to these to create the CAN messages with data.

The prototypes for functions used in Can.c are listed in Can.h in lines 32 to 40. These are visible in µVision.

23 typedef struct {  
24 unsigned int id; // 29 bit identifier
25 unsigned char data[8]; // Data Field
26 unsigned char len; // Length of data field in bytes
27 unsigned char format; // 0 - STANDARD, 1 - EXTENDED
28 unsigned char type; // 0 - DATA FRAME, 1 - REMOTE FRAME
29 } CAN_msg;  
42 extern CAN_msg CAN_TxMsg; // CAN message for sending
43 extern CAN_msg CAN_RxMsg; // CAN message for receiving

2) Can.c
Configuring the CAN controller (Can.C) There are several things that must be done to properly configure the CAN controller. These are done in Can.C by functions that are called by CanDemo.c. Examples are found in the function CAN_setup as shown in µVision:
  1. Enable and set the clock for the CAN controller. The clock must be stable for CAN. No R-C oscillators here.
  2. Configure GPIO ports PB8 and PB9 for the transmit and receive lines to the transceiver chip.
  3. Enable the interrupts for the transmit and receive functions.
  4. Set CAN_BTR: This is a 32 CAN controller register in which things such as bit timing, bus frequency, sample point and silent and loop back modes are set. In the Keil example, the baud rate is set to 500 Kbps. All CAN controllers on a network should have consistent BTR values for stable operation.
Sometimes timing settings can cause strange problems. If you experience some unusual problems, you might want to study CAN timing in greater detail. For small systems, the default settings or those suggested by the processor manufacturer will work satisfactorily. You can adjust these settings for the most robust bus performance.

All CAN controllers have the same general settings for bit timing because of the licensing agreements with Robert Bosch GmbH.

For a detailed explanation of CAN bit timing, see, and for the calculations, see page 505 of the ST Reference Manual RM0008.

Other functions in Can.c

  • CAN_start: Starts the CAN controller by ending the initialization sequence.
  • CAN_waitReady: Waits until transmit mailbox is ready – then can add another message to be transmitted.
  • CAN_wrMsg: Writes a message to the CAN controller and transmit it.
  • CAN_rdMsg: Reads a message from the CAN controller and releases it to be sent to the STM32 processor.
  • CAN_wrFilter: Configures the acceptance filter. This is not discussed in this article.
  • USB_HP_CAN_TX_IRQHandler: The transmit interrupt handler.
  • USB_LP_CAN_RX0_IRQHandler: The receive interrupt handler.
These functions are called by CanDemo.c and in the main function.

3) CanDemo.c
This contains the main function and contains the example program that reads the voltage on the A/D converter and sends its value as a CAN data byte with an 11-bit ID of 0x21. CanDemo.c contains functions to configure and read the A/D converter, display the A/D values on the LCD and call the functions that initialize the CAN controller.

Transmitting a CAN Message:

Lines 131 to 135 put the frame values into the structure CAN_TxMsg. (Except for the data byte from the A/D converter.)

131 CAN_TxMsg.ed = 33; // initialise message to send
132 for (i = 0; i < 8; i++>[i] = 0;
133 CAN_TxMsg.len = 1;  
134 CAN_TxMsg.format = STANDARD_FORMAT;
135 CAN_TxMsg.type = DATA_FRAME;

This CAN message will send one data byte. For example, if you change the value in the member CAN_TxMsg.len to “3,” three data bytes will be sent on the bus. What data will be in them depends on the contents of the array

If you send more data bytes than you have data, it is a good idea to fill the empty data bytes with either 0 or 0xFF.

141[0]=adc_Get (); // data[0] field = ADC value
142 CAN_wrMsg (&CAN_TxMsg); // transmit message
143[0]; // send to LCD screen

Line 141 puts the A/D value into the data member in data byte 0 and line 142 transmits it.

Receiving a CAN Message:

Lines 148 to 151 indicate when a CAN message is received, but something more must be going on here. Line 151 shows that the data byte received and inserted in the array[0] is sent to be displayed on the LCD. How exactly does the CAN data byte get into the member array[0]?

148 if (CAN_RxRdy) {
149 CAN_RxRdy = 0;
151 val_Rx =[0];  

It was stated earlier in this article that the function to read the CAN data was located in Can.c. If we look in Can.c, we find the function CAN_rdMsg at lines 130 to 159. Examining it, clearly it is here that the array[0] is loaded at line 148. How does this function get called? It is not called from CanDemo.c.

If we set a breakpoint on Can.c line 132 (the first assembly instruction of the function CAN_rdMsg) by double-clicking on the left side of Line 132, we can check the Call Stack window to see from where it was called. This is shown in the screen shot below. This would indicate line 148 in the main function called CAN_rdMsg. Examining the assembly code at line 148 shows this cannot be true.

We can use the Trace function of µVision that is available in Simulator mode to figure out how CAN_rdMsg is called.

Figure 5: CAN Call Stack window.

  1. Click on Enable Trace Recording icon.
  2. Run the program to the breakpoint set previously at line 132.
  3. Click on View Trace Records. View the Disassembly window that opens up as shown in next window.

The yellow arrow points to the start of the function CAN_rdMsg. The arrow represents the program counter.

The grey area shows a recording of the instructions that were executed. The white area displays unexecuted instructions.

Just before line 132 is the source line 213: that calls CAN_rdMsg. This is actually the assembly instruction at addresses 0x8000A10 BL.W CAN_rdMsg. Reading higher to 210, we can see this source line comes from the function USB_LP_CAN_RX0_IRQHandler, which is the Receive Interrupt Handler in Can.c.

So, this interrupt handler called the function that reads the CAN frame from the CAN controller and inserts it into the structure.

If you right click on line 210 and select Show Source at Current Line, this will be displayed in the source file.

Figure 6: Trace Window showing source code behind current instruction.

If you have more than one CAN controller in your processor, you can operate these as parallel receivers. Divide the messages with the Acceptance Filters. This will help capture all the messages on a very busy bus without losing any. Each CAN controller will handle its share of the messages. This effectively multiplies the number of FIFO buffer memories and is an excellent method of getting all the CAN frames.

Exception, PC, and data tracing

The ST Cortex-M3 processor possesses significant debugging capabilities. These features are grouped under the Serial Wire Viewer and are supported by Keil µVision and the USB-JTAG adapter ULINK2 and ULINK-ME. Recall that Can.c contains two interrupt handlers: for transmit and receive. These can be displayed in real-time (no CPU cycles are stolen) in the Trace Records window as shown below. This works only with a real target Cortex-M3 connected to µVision with a ULINK2 or ULINLK-ME USB to JTAG adapter.

The Serial Wire Viewer can be used to display PC samples, data read and write cycles, exceptions and other events. The ITM is a print type instrumentation output.

To show our example using the Serial Wire Viewer and a STM32 chip:

  1. Connect an STM32 processor to µVision and run the same CAN program using the ULINK Cortex debugger.
  2. Activate the Serial Wire Viewer as described in the appendix of
  3. Configure the Logic Analyzer to display[0]. This will also display it in the Trace Records.
  4. Set a breakpoint at the instruction at line 148in Can.c. This is the first instruction after the write to the array CAN_RxMsg. data[0]. This is needed because the instruction the breakpoint is set on is not executed. We want to see and record this write, so we must execute this source line.
  5. Run the program to the breakpoint. The resulting Exception Trace window is displayed in Figure 7.

Figure 7: Exception Trace window.

Two IRQ events are shown. Note an IRQ is a subset of Exceptions. Referring to the ST RM0008 reference manual, IRQ 19 is the CAN Transmit IRQ and IRQ 20 is the Receive IRQ. The Trace Records window will also be displayed (Figure 8).

Figure 8: Trace Records window.

We can see the following lines:
  • 3rd and 4th Line: Exception Entry and Exit: 35: This is the transmit IRQ. Translate the 35 into IRQ19 in the Exception Trace window (Figure 6).
  • 5th Line: Exception Entry: 36: This is the entry of the receive IRQ 20 – this is the Receive IRQ Handler.
  • 6th Line: Data Write: The value 0x8F is written to address 0c2000004C by the instruction at 0x8004910. You can confirm that these values represent an assembly instruction that is part of source line 148 and that the address written to is[0].
  • That finishes a partial demonstration of the Serial Wire Viewer trace feature of the Cortex-M3 processor. Visit for more information concerning the Serial Wire Viewer interface in Cortex-M3 processors.
An example CAN network

Figure 9 shows a real two-node CAN network using Keil MCBSTM32 (right) and the MCBSTM32E evaluation boards using the same example code discussed in this article. The Tx of one node is transmitted to the Rx of the other node and this is clearly seen on the LCDs.

Note the twisted differential pair of wires CAN Hi and CAN Lo.

Note that no ground wire is used in this small network.

This setup is part of the Keil lab available for the STM32. Full details are in the lab.

Figure 9: A two node CAN network using Keil MCBSTM32 and the MCBSTM32E evaluation boards.

How can I learn more about these CAN examples?

With a hardware board, you can generate and receive real CAN messages and connect to other nodes or a CAN test analyzer. The lab for the Keil MCBSTM32™ board has instructions on how to do this. This document has some interesting CAN examples. For instance, you can use the Cortex-M3 Serial Wire Viewer to see the CAN messages and interrupts displayed in real-time. You can compile these examples with the evaluation version of the software. Please see

STMicroelectronics supplies a complete software library for all their peripherals in the STM32 family using the Cortex-M3 processor. This includes CAN support. Search for STM32F10xFWLib. A zip file,, and an application note, UM0427.pdf, are available. Keil µVision project and source files are included. There is no charge for these libraries. Keil uses portions of these libraries in their own examples programs. These are identified by the letters STLIB in the Keil µVision project filename.

Keil makes NXP evaluation boards with CAN examples. Luminary Micro also offers some with CAN controllers that are supported by Keil examples. You now know how CAN works and are familiar with the Keil software and will have no problem getting a real CAN system operating. You have already run an accurate simulation of a CAN network. If you obtain real target hardware, such as the MCBSTM32, you can also connect up to any CAN network and communicate with it.

Keil offers a complete CAN stack for all ARM7™, ARM9™ and Cortex-M3/M1 processors. This comes as part of RL-ARM™. (Please visit for more information.) This comprehensive package contains the RTX™ RTOS source (the actual RTOS is already included free with the MDK toolset), USB, TCP/IP networking and the CAN interface.