Advanced PIC18 Projects-CAN Bus Projects
Advanced PIC18 Projects-CAN Bus Projects
Advanced PIC18 Projects-CAN Bus Projects
The Controller Area Network (CAN) is a serial bus communications protocol developed
by Bosch (an electrical equipment manufacturer in Germany) in the early 1980s.
Thereafter, CAN was standardized as ISO-11898 and ISO-11519, establishing itself as
the standard protocol for in-vehicle networking in the auto industry. In the early days of
the automotive industry, localized stand-alone controllers had been used to manage
various actuators and electromechanical subsystems. By networking the electronics in
vehicles with CAN, however, they could be controlled from a central point, the engine
control unit (ECU), thus increasing functionality, adding modularity, and making
diagnostic processes more efficient.
Early CAN development was mainly supported by the vehicle industry, as it was used in
passenger cars, boats, trucks, and other types of vehicles. Today the CAN protocol is
used in many other fields in applications that call for networked embedded control,
including industrial automation, medical applications, building automation, weaving
machines, and production machinery. CAN offers an efficient communication protocol
between sensors, actuators, controllers, and other nodes in real-time applications, and is
known for its simplicity, reliability, and high performance.
The CAN protocol is based on a bus topology, and only two wires are needed for
communication over a CAN bus. The bus has a multimaster structure where each device
on the bus can send or receive data. Only one device can send data at any time while
all the others listen. If two or more devices attempt to send data at the same time,
the one with the highest priority is allowed to send its data while the others return to
receive mode.
www.newnespress.com
476 Chapter 9
As shown in Figure 9.1, in a typical vehicle application there is usually more than one
CAN bus, and they operate at different speeds. Slower devices, such as door control,
climate control, and driver information modules, can be connected to a slow speed bus.
Devices that require faster response, such as the ABS antilock braking system, the
transmission control module, and the electronic throttle module, are connected to a
faster CAN bus.
Air Door
conditioner Satellite
switch CD
navigation
125Kb/s 500Kb/s
Head Instrument
lamps DVD Radio
panel
Gateway
Oil
pressure Brakes
Engine
5Mb/s
The automotive industry’s use of CAN has caused mass production of CAN controllers.
Current estimate is that 400 million CAN modules are sold every year, and CAN
controllers are integrated on many microcontrollers, including PIC microcontrollers,
and are available at low cost.
Figure 9.2 shows a CAN bus with three nodes. The CAN protocol is based on CSMA/
CDþAMP (Carrier-Sense Multiple Access/Collision Detection with Arbitration on
Message Priority) protocol, which is similar to the protocol used in Ethernet LAN.
When Ethernet detects a collision, the sending nodes simply stop transmitting and wait
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 477
CAN BUS
Terminator Terminator
a random amount of time before trying to send again. CAN protocol, however, solves
the collision problem using the principle of arbitration, where only the higheest priority
node is given the right to send its data.
There are basically two types of CAN protocols: 2.0A and 2.0B. CAN 2.0A is the
earlier standard with 11 bits of identifier, while CAN 2.0B is the new extended standard
with 29 bits of identifier. 2.0B controllers are completely backward-compatible with
2.0A controllers and can receive and transmit messages in either format.
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.
Some of the CAN protocol features are:
CAN bus is multimaster. When the bus is free, any device attached to the bus
can start sending a message.
CAN bus protocol is flexible. The devices connected to the bus have no
addresses, which means messages are not transmitted from one node to another
based on addresses. Instead, all nodes in the system receive every message
transmitted on the bus, and it is up to each node to decide whether the received
message should be kept or discarded. A single message can be destined for a
particular node or for many nodes, depending on how the system is designed.
Another advantage of having no addresses is that when a device is added to or
www.newnespress.com
478 Chapter 9
removed from the bus, no configuration data needs to be changed (i.e., the bus is
“hot pluggable”).
CAN bus offers remote transmit request (RTR), which means that one node on
the bus is able to request information from the other nodes. Thus instead of
waiting for a node to continuously send information, a request for information
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 the temperature is
sent periodically over the bus. However, a more elegant solution is to request
the temperature as needed, since it minimizes the bus traffic while maintaining
the network’s integrity.
CAN bus communication speed is not fixed. Any communication speed can be
set for the devices attached to a bus.
All devices on the bus can detect an error. The device that has detected an error
immediately notifies all other devices.
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 units that can be attached to a bus is limited by the bus’s delay time
and electrical load.
The data on CAN bus is differential and can be in two states: dominant and recessive.
Figure 9.3 shows the state of voltages on the bus. The bus defines a logic bit 0 as a
dominant bit and a logic bit 1 as a recessive bit. When there is arbitration on the bus, a
Voltage
level
Dominant
3.5 CANH
Recessive Recessive
2.5 Vdiff
1.5 CANL
Time
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 479
dominant bit state always wins out over a recessive bit state. In the recessive state, the
differential voltage CANH and CANL is less than the minimum threshold (i.e., less than
0.5V receiver input and less than 1.5V transmitter output). In the dominant state, the
differential voltage CANH and CANL is greater than the minimum threshold.
The ISO-11898 CAN bus specifies that a device on that bus must be able to drive a
forty-meter cable at 1Mb/s. A much longer bus length can usually be achieved by
lowering the bus speed. Figure 9.4 shows the variation of bus length with the
communication speed. For example, with a bus length of one thousand meters we can
have a maximum speed of 40Kb/s.
1120
Bus length (m)
760
400
40
40 100 1000
Speed (bps)
A CAN bus is terminated to minimize signal reflections on the bus. The ISO-11898
requires that the bus has a characteristic impedance of 120 ohms. The bus can be
terminated by one of the following methods:
Standard termination
Split termination
Biased split termination
In standard termination, the most common termination method, a 120-ohm resistor is
used at each end of the bus, as shown in Figure 9.5(a). In split termination, the ends
of the bus are split and a single 60-ohm resistor is used as shown in Figure 9.5(b).
Split termination allows for reduced emission, and this method is gaining popularity.
Biased split termination is similar to split termination except that a voltage divider
www.newnespress.com
480 Chapter 9
60 ohm
VDD
R1 60 ohm
R2 60 ohm
circuit and a capacitor are used at either end of the bus. This method increases the EMC
performance of the bus (Figure 9.5(c)).
Many network protocols are described using the seven-layer Open Systems
Interconnection (OSI) model. The CAN protocol includes the data link layer, and
the physical layer of the OSI reference model (see Figure 9.6). The data link layer
(DLL) consists of the Logical Link Control (LLC) and Medium Access Control
(MAC). LLC manages the overload notification, acceptance filtering, and recovery
management. MAC manages the data encapsulation, frame coding, error detection,
and serialization/deserialization of the data. The physical layer consists of the
physical signaling layer (PSL), physical medium attachment (PMA), and the
medium dependent interface (MDI). PSL manages the bit encoding/decoding and
bit timing. PMA manages the driver/receiver characteristics, and MDI is the
connections and wires.
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 481
Application
Presentation
Session
Transport
Netwok
Data Link Logical Link Control
Physical
Physical Signaling
There are basically four message frames in CAN: data, remote, error, and overload. The
data and remote frames need to be set by the user. The other two are set by the CAN
hardware.
Start of ACK
frame Control Data
RTR CRC
11-bit End of
identifier frame
www.newnespress.com
482 Chapter 9
CRC field, which checks whether or not the received bit sequence is corrupted.
The ACK field is 2 bits and is used by the transmitter to receive acknowledgment of
a valid frame from any receiver. The end of the message is indicated by a 7-bit end
of frame (EOF) field. In an extended data frame, the arbitration field is 32 bits wide
(29-bit identifier þ1-bit IDE to define the message as an extended data frame þ1-bit
SRR which is unused þ1-bit RTR) (see Figure 9.8).
Start of ACK
frame SRR 18-bit
identifier CRC
11-bit End of
identifier IDE RTR frame
Control
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 483
1 2 3 4 5 6 7 8 9 10 11
Node 1
Node 2
Node 3
Bus
Start of frame
Assuming the recessive level corresponds to 1 and the dominant level to 0, the
arbitration is performed as follows:
All the nodes start transmitting simultaneously, first sending SOF bits.
Then they send their identifier bits. The 8th bit of Node 2 is in the recessive
state, while the corresponding bits of Nodes 1 and 3 are in the dominant state.
Therefore Node 2 stops transmitting and returns to receive mode. The receiving
phase is indicated by a gray field.
The 10th bit of Node 1 is in the recessive state, while the same bit of Node 3 is
in dominant state. Thus Node 1 stops transmitting and returns to receive mode.
The bus is now left to Node 3, which can send its control and data fields freely.
Notably, the devices on the bus have no addresses. Instead, all the devices pick up all
the data on the bus, and every node must filter out the messages it does not want.
www.newnespress.com
484 Chapter 9
0 D D D D
1 D D D R
2 D D R D
3 D D R R
4 D R D D
5 D R D R
6 D R R D
7 D R R R
8 R D or R D or R D or R
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 485
SOF CRC
Control field EOF
Arbitration ACK
field
www.newnespress.com
486 Chapter 9
Bit errors are detected when the output level and the data level on the bus do not
match. Both transmit and receive units can detect bit errors. CRC errors are detected
only by receiving units. CRC errors are detected if the calculated CRC from the
received message and the received CRC do not match. Form errors are detected
by the transmitting or receiving units when an illegal frame format is detected.
ACK errors are detected only by the transmitting units if the ACK field is found
recessive. Stuffing errors are detected when the same level of data is detected for 6
consecutive bits in any field that should have been bit-stuffed. This error can be
detected by both the transmitting and receiving units.
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 487
device can have its own different clock frequency. One message bit consists of four
nonoverlapping time segments:
Synchronization segment (Sync_Seg)
Propagation time segment (Prop_Seg)
Phase buffer segment 1 (Phase_Seg1)
Phase buffer segment 2 (Phase_Seg2)
The Sync_Seg segment is used to synchronize various nodes on the bus, and an edge
is expected to lie within this segment. The Prop_Seg segment compensates for
physical delay times within the network. The Phase_Seg1 and Phase_Seg2 segments
compensate for edge phase errors. These segments can be lengthened or shortened by
synchronization. The sample point is the point in time where the actual bit value is
located and occurs at the end of Phase_Seg1. A CAN controller can be configured
to sample three times and use a majority function to determine the actual bit value.
Each segment is divided into units known as time quantum, or TQ. A desired bit
timing can be set by adjusting the number of TQ’s that comprise one message bit
and the number of TQ’s that comprise each segment in it. The TQ is a fixed unit
derived from the oscillator period, and the time quantum of each segment can vary
from 1 to 8. The lengths of the various time segments are:
Sync_Seg is 1 time quantum long
Prop_Seg is programmable as 1 to 8 time quanta long
Phase_Seg1 is programmable as 1 to 8 time quanta long
Phase_Seg2 is programmable as 2 to 8 time quanta long
By setting the bit timing, a sampling point can be set so multiple units on the bus can
sample messages with the same timing.
The nominal bit time is programmable from a minimum of 8 time quanta to a maximum
of 25 time quanta. By definition, the minimum nominal bit time is 1ms, corresponding
to a maximum 1Mb/s rate. The nominal bit time (TBIT) is given by:
TBIT ¼ TQ ðSync Seg þ Prop Seg þ Phase Seg1 þ Phase Seg2Þ ð9:1Þ
www.newnespress.com
488 Chapter 9
The time quantum is derived from the oscillator frequency and the programmable
baud rate prescaler, with integer values from 1 to 64. The time quantum can be
expressed as:
TQ ¼ 2 ðBRP þ 1Þ=FOSC ð9:3Þ
where TQ is in ms, FOSC is in MHz, and BRP is the baud rate prescaler (0 to 63).
Example 9.1
Assuming a clock frequency of 20MHz, a baud rate prescaler value of 1, and a
nominal bit time of TBIT ¼ 8 * TQ, determine the nominal bit rate.
Solution 9.1
Using equation (9.3),
TQ ¼ 2 ð1 þ 1Þ=20 ¼ 0:2ms
also
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 489
In order to compensate for phase shifts between the oscillator frequencies of nodes
on a bus, each CAN controller must synchronize to the relevant signal edge of the
received signal. Two types of synchronization are defined: hard synchronization and
resynchronization. Hard synchronization is used only at the beginning of a message
frame, when each CAN node aligns the Sync_Seg of its current bit time to the
recessive or dominant edge of the transmitted start of frame. According to the
rules of synchronization, if a hard synchronization occurs, there will not be a
resynchronization within that bit time.
With resynchronization, Phase_Seg1 may be lengthened or Phase_Seg2 may be
shortened. The amount of change in the phase buffer segments has an upper bound
given by the synchronization jump width (SJW). The SJW is programmable between
1 and 4, and its value is added to Phase_Seg1 or subtracted from Phase_Seg2.
CAN Node
CAN Bus
www.newnespress.com
490 Chapter 9
built-in CAN module. The microcontroller is connected to the CAN bus using an
external MCP2515 CAN controller chip and an MCP2551 CAN bus transceiver chip.
This configuration is suitable for a quick upgrade to an existing design using any PIC
microcontroller.
For new CAN bus–based designs it is easier to use a PIC microcontroller with a built-in
CAN module. As shown in Figure 9.12, such devices include built-in CAN controller
hardware on the chip. All that is required to make a CAN node is to add a CAN
transceiver chip. Table 9.2 lists some of the PIC microcontrollers that include a CAN
module.
PIC18F
Series 8-bit
CAN RX Microcontroller
Transceiver &
MCP2551 CAN controller
TX module
CAN Node
CAN Bus
Table 9.2: Some popular PIC microcontrollers that include CAN modules
Flash SRAM EEPROM CAN
Device Pins (KB) (KB) (bytes) A/D module SPI UART
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 491
www.newnespress.com
492 Chapter 9
A node uses filters to decide whether or not to accept a received message. Message
filtering is applied to the whole identifier field, and mask registers are used to specify
which bits in the identifier the filters should examine.
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 493
The CAN module in the PIC18F258 microcontroller has six modes of operation:
Configuration mode
Disable mode
Normal operation mode
Listen-only mode
Loop-back mode
Error recognition mode
www.newnespress.com
494 Chapter 9
communicating with each other. The baud rate can be determined by testing
different values until valid messages are received. The listen-only mode cannot
transmit messages.
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 495
Acceptance Filter
RXM2
Accept
Acceptance Mask Acceptance Filter
RXM0 RXF3
RXB0 RXB1
The CAN module uses message acceptance filters and masks to determine if a
message in the MAB should be loaded into a receive buffer. Once a valid message is
received by the MAB, the identifier field of the message is compared to the filter
values. If there is a match, that message is loaded into the appropriate receive buffer.
The filter masks determine which bits in the identifier are examined with the filters.
The truth table in Table 9.3 shows how each bit in the identifier is compared against
0 Accept
1 0 0 Accept
1 0 1 Reject
1 1 0 Reject
1 1 1 Accept
www.newnespress.com
496 Chapter 9
the masks and filters to determine if the message should be accepted. If a mask
bit is set to 0, that bit in the identifier is automatically accepted regardless of the
filter bit.
Example 9.2
Assuming the microcontroller oscillator clock rate is 20MHz and the required CAN bit
rate is 125KHz, calculate the timing parameters.
Solution 9.2
With a 20MHz clock rate, the clock period is 50ns. Choosing a baud rate prescaler
value of 4, from Equation (9.4), TQ ¼ 2 * (BRP þ 1) * TOSC, gives a time
quantum of TQ ¼ 500ns. To obtain a nominal bit rate of 125KHz, the nominal bit
time must be:
TBIT ¼ 1=0:125MHz ¼ 8ms; or 16TQ
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 497
The Sync_Segment is 1TQ. Choosing 2TQ for the Prop_Seg, and 7TQ for Phase_Seg1
leaves 6TQ for Phase_Seg2 and places the sampling point at 10TQ at the end of
Phase_Seg1.
By the rules described earlier, the SJW can be the maximum allowed (i.e., 4). However,
a large SJW is only necessary when the clock generation of different nodes is not
stable or accurate (e.g., if ceramic resonators are used). Typically, a SJW of 1 is
enough. In summary, the required timing parameters are:
Baud rate prescaler (BRP) ¼ 4
Sync_Seg ¼1
Prop_Seg ¼2
Phase_Seg1 ¼7
Phase_Seg2 ¼6
SJW ¼1
The sampling point is at 10TQ which corresponds to 62.5% of the total bit time.
There are several tools available for free on the Internet for calculating CAN bus timing
parameters. One such tool is the CAN Baud Rate Calculator, developed by Artic
Consultants Ltd (http://www.articconsultants.co.uk). An example using this tool
follows.
Example 9.3
Assuming the microcontroller oscillator clock rate is 20MHz and the required CAN
bit rate is 125KHz, calculate the timing parameters using the CAN Baud Rate
Calculator.
Solution 9.3
Figure 9.14 shows the output of the CAN Baud Rate Calculator program. The device
type is selected as PIC18Fxxx8, the oscillator frequency is entered as 20MHz, and the
CAN bus baud rate is entered as 125KHz.
Clicking the Calculate Settings button calculates and displays the recommended timing
parameters. In general, there is more than one solution, and different solutions are given
in the Calculated Solutions field’s drop-down menu.
In choosing Solution 2 from the drop-down menu, the following timing parameters are
recommended by the program:
www.newnespress.com
498 Chapter 9
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 499
bus for PIC microcontrollers having no built-in CAN modules. In this section we
will discuss only the library functions available for PIC microcontrollers with built-in
CAN modules. Similar functions are available for the PIC microcontrollers with no
built-in CAN modules.
The mikroC CAN functions are supported only by PIC18XXX8 microcontrollers
with MCP2551 or similar CAN transceivers. Both standard (11 identifier bits) and
extended format (29 identifier bits) messages are supported.
The following mikroC functions are provided:
CANSetOperationMode
CANGetOperationMode
CANInitialize
CANSetBaudRAte
CANSetMask
CANSetFilter
CANRead
CANWrite
9.10.1 CANSetOperationMode
The CANSetOperationMode function sets the CAN operation mode. The function
prototype is:
void CANSetOperationMode(char mode, char wait_flag)
The parameter wait_ flag is either 0 or 0 FF. If it is set to 0 FF, the function blocks
and will not return until the requested mode is set. If it is set to 0, the function returns as
a nonblocking call.
The mode can be one of the following:
CAN_MODE_NORMAL Normal mode of operation
CAN_MODE_SLEEP Sleep mode of operation
CAN_MODE_LOOP Loop-back mode of operation
www.newnespress.com
500 Chapter 9
9.10.2 CANGetOperationMode
The CANGetOperationMode function returns the current CAN operation mode. The
function prototype is:
char CANGetOperationMode(void)
9.10.3 CANInitialize
The CANInitialize function initializes the CAN module. All mask registers are cleared
to 0 to allow all messages. Upon execution of this function, the normal mode is set. The
function prototype is:
void CANInitialize(char SJW, char BRP, char PHSEG1, char PHSEG2,
char PROPEG, char CAN_CONFIG_FLAGS)
where
SJW is the synchronization jump width
BRP is the baud rate prescaler
PHSEG1 is the Phase_Seg1 timing parameter
PHSEG2 is the Phase_Seg2 timing parameter
PROPSEG is the Prop_Seg
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 501
9.10.4 CANSetBaudRate
The CANSetBaudRate function is used to set the CAN bus baud rate. The function
prototype is:
void CANSetBaudRate(char SJW, char BRP, char PHSEG1, char PHSEG2,
char PROPSEG, char CAN_CONFIG_FLAGS)
9.10.5 CANSetMask
The CANSetMask function sets the mask for filtering messages. The function
prototype is:
www.newnespress.com
502 Chapter 9
9.10.6 CANSetFilter
The CANSetFilter function sets filter values. The function prototype is:
void CANSetFilter(char CAN_FILTER, long value, char
CAN_CONFIG_FLAGS)
9.10.7 CANRead
The CANRead function is used to read messages from the CAN bus. If no message is
available, 0 is returned. The function prototype is:
char CANRead(long *id, char *data, char *datalen, char
*CAN_RX_MSG_FLAGS)
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 503
9.10.8 CANWrite
The CANWrite function is used to send a message to the CAN bus. A zero is returned
if message can not be queued (buffer full). The function prototype is:
char CANWrite(long id, char *data, char datalen, char
CAN_TX_MSG_FLAGS)
id is the CAN message identifier. Only 11 or 29 bits may be used depending on message
type (standard or extended). data is an array of bytes up to 8 where the data to be sent is
stored. datalen is the length of the data (1 to 8).
CAN_TX_MSG_FLAGS can be one of the following:
CAN_TX_PRIORITY_0 Transmit priority 0
CAN_TX_PRIORITY_1 Transmit priority 1
www.newnespress.com
504 Chapter 9
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 505
PIC18F PIC18F
LM35 258 258 LCD
Temperature
sensor MCP2551 MCP2551
The project’s circuit diagram is given in Figure 9.16. Two CAN nodes are
connected together using a two-meter twisted pair cable, terminated with a 120-ohm
resistor at each end.
www.newnespress.com
506 Chapter 9
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 507
The COLLECTOR processor reads the temperature, formats it, and sends to the
DISPLAY processor over the CAN bus
The DISPLAY processor reads the temperature from the CAN bus and then
displays it on the LCD
This process is repeated every second
DISPLAY Program
Figure 9.17 shows the program listing of the DISPLAY program, called DISPLAY.C.
At the beginning of the program PORTC pins are configured as outputs, RB3 is
configured as input (CANRX), and RB2 is configured as output (CANTX). In this
project the CAN bus bit rate is selected as 100Kb/s. With a microcontroller clock
frequency of 8MHz, the Baud Rate Calculator program (see Figure 9.14) is used to
calculate the timing parameters as:
SJW ¼ 1
BRP ¼ 1
Phase_Seg1 ¼ 6
Phase_Seg2 ¼ 7
Prop_Seg ¼ 6
The mikroC CAN bus function CANInitialize is used to initialize the CAN module. The
timing parameters and the initialization flag are specified as arguments in this function.
The initialization flag is made up from the bitwise AND of:
init_flag ¼ CAN_CONFIG_SAMPLE_THRICE &
CAN_CONFIG_PHSEG2_PRG_ON &
CAN_CONFIG_STD_MSG &
CAN_CONFIG_DBL_BUFFER_ON &
CAN_CONFIG_VALID_XTD_MSG &
CAN_CONFIG_LINE_FILTER_OFF;
Where sampling the bus three times is specified, the standard identifier is specified,
double buffering is turned on, and the line filter is turned off.
Then the operation mode is set to CONFIG and the filter masks and filter values are specified.
Both mask 1 and mask 2 are set to all 1’s (1 is a shorthand way of writing hexadecimal
FFFFFFFF, i.e., setting all mask bits to 1’s) so that all filter bits match up with incoming data.
www.newnespress.com
508 Chapter 9
/∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗
CAN BUS EXAMPLE - NODE: DISPLAY
===============================
This is the DISPLAY node of the CAN bus example. In this project a PIC18F258
type microcontroller is used. An MCP2551 type CAN bus transceiver is used to
connect the microcontroller to the CAN bus. The microcontroller is operated from
an 8MHz crystal with an external reset button.
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.
Microcontroller LCD
RC0 D4
RC1 D5
RC2 D6
RC3 D7
RC4 RS
RC5 EN
void main()
{
unsigned char temperature, data[8];
unsigned short init_flag, send_flag, dt, len, read_flag;
char SJW, BRP, Phase_Seg1, Phase_Seg2, Prop_Seg, txt[4];
long id, mask;
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 509
read_flag = 0;
//
// Initialize CAN module
//
CANInitialize(SJW, BRP, Phase_Seg1, Phase_Seg2, Prop_Seg, init_flag);
//
// Set CAN CONFIG mode
//
CANSetOperationMode(CAN_MODE_CONFIG, 0xFF);
mask = -1;
//
// Set all MASK1 bits to 1's
//
CANSetMask(CAN_MASK_B1, mask, CAN_CONFIG_XTD_MSG);
//
// Set all MASK2 bits to 1's
//
CANSetMask(CAN_MASK_B2, mask, CAN_CONFIG_XTD_MSG);
//
// Set id of filter B2_F3 to 3
//
CANSetFilter(CAN_FILTER_B2_F3,3,CAN_CONFIG_XTD_MSG);
//
// Set CAN module to NORMAL mode
//
CANSetOperationMode(CAN_MODE_NORMAL, 0xFF);
www.newnespress.com
510 Chapter 9
//
// Configure LCD
//
Lcd_Config(&PORTC,4,5,0,3,2,1,0); // LCD is connected to PORTC
Lcd_Cmd(LCD_CLEAR); // Clear LCD
Lcd_Out(1,1,"CAN BUS"); // Display heading on LCD
Delay_ms(1000); // Wait for 2 seconds
//
// Program loop. Read the temperature from Node:COLLECTOR and display
// on the LCD continuously
//
for(;;) // Endless loop
{
Lcd_Cmd(LCD_CLEAR); // Clear LCD
Lcd_Out(1,1,"Temp = "); // Display "Temp = "
//
// Send a message to Node:COLLECTOR and ask for data
//
data[0] = 'T'; // Data to be sent
id = 500; // Identifier
CANWrite(id, data, 1, send_flag); // send 'T'
//
// Get temperature from node:COLLECT
//
dt = 0;
while(!dt)dt = CANRead(&id, data, &len, &read_flag);
if(id == 3)
{
temperature = data[0];
ByteToStr(temperature,txt); // Convert to string
Lcd_Out(1,8,txt); // Output to LCD
Delay_ms(1000); // Wait 1 second
}
}
Filter 3 for buffer 2 is set to value 3 so that identifiers having values 3 are accepted by
the receive buffer.
The operation mode is then set to NORMAL. The program then configures the LCD
and displays the message “CAN BUS” for one second on the LCD.
The main program loop executes continuously and starts with a for statement. Inside
this loop the LCD is cleared and text “TEMP ¼” is displayed on the LCD. Then
character “T” is sent over the bus with the identifier equal to 500 (the COLLECTOR
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 511
/∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗
CAN BUS EXAMPLE - NODE: COLLECTOR
=================================
This is the COLLECTOR node of the CAN bus example. In this project a
PIC18F258 type microcontroller is used. An MCP2551 type CAN bus transceiver
is used to connect the microcontroller to the CAN bus. The microcontroller is
operated from an 8MHz crystal with an external reset button.
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.
void main()
{
unsigned char temperature, data[8];
unsigned short init_flag, send_flag, dt, len, read_flag;
char SJW, BRP, Phase_Seg1, Phase_Seg2, Prop_Seg, txt[4];
unsigned int temp;
unsigned long mV;
long id, mask;
www.newnespress.com
512 Chapter 9
//
// CAN BUS Timing Parameters
//
SJW = 1;
BRP = 1;
Phase_Seg1 = 6;
Phase_Seg2 = 7;
BRP = 1;
Prop_Seg = 6;
read_flag = 0;
//
// Initialise CAN module
//
CANInitialize(SJW, BRP, Phase_Seg1, Phase_Seg2, Prop_Seg, init_flag);
//
// Set CAN CONFIG mode
//
CANSetOperationMode(CAN_MODE_CONFIG, 0xFF);
mask = -1;
//
// Set all MASK1 bits to 1's
//
CANSetMask(CAN_MASK_B1, mask, CAN_CONFIG_XTD_MSG);
//
// Set all MASK2 bits to 1's
//
CANSetMask(CAN_MASK_B2, mask, CAN_CONFIG_XTD_MSG);
//
// Set id of filter B1_F1 to 3
//
CANSetFilter(CAN_FILTER_B2_F3,500,CAN_CONFIG_XTD_MSG);
//
// Set CAN module to NORMAL mode
//
CANSetOperationMode(CAN_MODE_NORMAL, 0xFF);
//
www.newnespress.com
Advanced PIC18 Projects—CAN Bus Projects 513
DO FOREVER DO FOREVER
Send character “T” with identifier 500 Read a character
Read temperature with identifier 3 IF character is “T”
Convert temperature to string Read temperature
Display temperature on LCD Convert to digital
Wait 1 second Convert to ºC
ENDDO Send with identifier 3
ENDIF
ENDDO
www.newnespress.com
514 Chapter 9
node filter is set to accept identifier 500). This is a request to the COLLECTOR
node to send the temperature reading. The program then reads the temperature from
the CAN bus, converts it to a string in array txt, and displays it on the LCD. This
process repeats after a one-second delay.
COLLECTOR Program
Figure 9.18 shows the program listing of the COLLECTOR program, called
COLLECTOR.C. The initial part of this program is the same as the DISPLAY
program. The receive filter is set to 500 so that messages with identifier 500 are
accepted by the program.
Inside the program loop, the program waits until it receives a request to send the
temperature. Here the request is identified by the reception of character “T”. Once a
valid request is received, the temperature is read and converted into C (stored in
variable temperature) and then sent to the CAN bus as a byte with an identifier value
equal to 3. This process repeats forever.
Figure 9.19 summarizes the operation of both nodes.
www.newnespress.com