Multi-Tasking and Real-Time Operating Systems

Nearly all microcontroller-based systems perform more than one activity. For example, a temperature monitoring system is made up of three tasks that normally repeat after a short delay, namely:

• Task 1 Reads the temperature

• Task 2 Formats the temperature

• Task 3 Displays the temperature

More complex systems may have many complex tasks. In a multi-tasking system, numerous tasks require CPU time, and since there is only one CPU, some form of organization and coordination is needed so each task has the CPU time it needs. In practice, each task takes a very brief amount of time, so it seems as if all the tasks are executing in parallel and simultaneously.

Almost all microcontroller-based systems work in real time. A real-time system is a time responsive system that can respond to its environment in the shortest possible time. Real time does not necessarily mean the microcontroller should operate at high speed. What is important in a real-time system is a fast response time, although high speed can help. For example, a real-time microcontroller-based system with various external switches is expected to respond immediately when a switch is activated or some other event occurs.

A real-time operating system (RTOS) is a piece of code (usually called the kernel) that controls task allocation when the microcontroller is operating in a multi-tasking

environment. RTOS decides, for instance, which task to run next, how to coordinate the task priorities, and how to pass data and messages among tasks.

This chapter explores the basic principles of multi-tasking embedded systems and gives examples of an RTOS used in simple projects. Multi-tasking code and RTOS are complex and wide topics, and this chapter describes the concepts pertaining to these tools only briefly. Interested readers should refer to the many books and papers available on operating systems, multi-tasking systems, and RTOS.

There are several commercially available RTOS systems for PIC microcontrollers.

At the time of writing, mikroC language did not provide a built-in RTOS. Two popular high-level RTOS systems for PIC microcontrollers are Salvo (www.pumpkin.com), which can be used from a Hi-Tech PIC C compiler, and the CCS (Customer Computer Services) built-in RTOS system. In this chapter, the example RTOS projects are based on the CCS (www.ccsinfo.com) compiler, one of the popular PIC C compilers developed for the PIC16 and PIC18 series of microcontrollers.

 

Advanced PIC18 Projects—CAN Bus Projects:mikroC CAN Functions

mikroC CAN Functions

The mikroC language provides two libraries for CAN bus applications: the library for PIC microcontrollers with built-in CAN modules and the library based on using a SPI

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

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 x FF. If it is set to 0 x 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

• CAN_MODE_LISTEN Listen-only mode of operation

• CAN_MODE_CONFIG Configuration mode of operation

CANGetOperationMode

The CANGetOperationMode function returns the current CAN operation mode. The function prototype is:

char CANGetOperationMode(void)

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:

Advanced PIC18 Projects—CAN Bus Projects -0210

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 received data is stored. datalen is the length of the received data (1 to 8).

CAN_RX_MSG_FLAGS can be one of the following:

Advanced PIC18 Projects—CAN Bus Projects -0211

Advanced PIC18 Projects—CAN Bus Projects -0212

 

Advanced PIC18 Projects—CAN Bus Projects:PIC Microcontroller CAN Interface

PIC Microcontroller CAN Interface

In general, any type of PIC microcontroller can be used in CAN bus–based projects, but some PIC microcontrollers (e.g., PIC18F258) have built-in CAN modules, which can simplify the design of CAN bus–based systems. Microcontrollers with no built-in CAN modules can also be used in CAN bus applications, but additional hardware and software are required, making the design costly and also more complex.

Figure 9.11 shows the block diagram of a PIC microcontroller–based CAN bus application, using a PIC16 or PIC12-type microcontroller (e.g., PIC16F84) with no

Advanced PIC18 Projects—CAN Bus Projects -0203

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.

Advanced PIC18 Projects—CAN Bus Projects -0204

 

Advanced PIC18 Projects—CAN Bus Projects:Nominal Bit Timing

Nominal Bit Timing

The CAN bus nominal bit rate is defined as the number of bits transmitted every second without resynchronization. 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

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:

Advanced PIC18 Projects—CAN Bus Projects -0202

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.

 

Advanced PIC18 Projects—CAN Bus Projects:Types of Errors

Types of Errors

The CAN bus identifies five types of errors:

• Bit error

• CRC error

• Form error

• ACK error

• Stuffing error

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.

 

Advanced PIC18 Projects—CAN Bus Projects:Overload Frame And Bit Stuffing

Overload Frame

The overload frame is used by the receiving unit to indicate that it is not yet ready to receive frames. This frame consists of an overload flag and an overload delimiter. The overload flag consists of 6 dominant bits and has the same structure as the active error flag of the error frame. The overload delimiter consists of 8 recessive bits and has the same structure as the error delimiter of the error frame.

Bit Stuffing

The CAN bus makes use of bit stuffing, a technique to periodically synchronize transmit-receive operations to prevent timing errors between receive nodes. After 5 consecutive bits with the same level, one bit of inverted data is added to the sequence. If, during sending of a data frame or remote frame, the same level occurs in 5 consecutive bits anywhere from the start of frame to the CRC sequence, an inverted bit is inserted in the next (i.e., the sixth) bit. If, during receiving of a data frame or remote frame, the same level occurs in 5 consecutive bits anywhere from the start of frame to CRC sequence, the next (sixth) bit is deleted from the received frame. If the deleted sixth bit is at the same level as the fifth bit, an error (stuffing error) is detected.

 

Advanced PIC18 Projects—CAN Bus Projects:Remote Frame

Remote Frame

The remote frame is used by the receiving unit to request transmission of a message from the transmitting unit. It consists of six fields (see Figure 9.10): start of frame, arbitration field, control field, CRC field, ACK field, and end of frame field. A remote frame is the same as a data frame except that it lacks a data field.

Advanced PIC18 Projects—CAN Bus Projects -0201

Error frames are generated and transmitted by the CAN hardware and are used to indicate when an error has occurred during transmission. An error frame consists of an error flag and an error delimiter. There are two types of error flags: active, which consists of 6 dominant bits, and passive, which consists of 6 recessive bits. The error delimiter consists of 8 recessive bits.

 

Advanced PIC18 Projects—CAN Bus Projects:Data Frame

Data Frame

The data frame is in two formats: standard (having an 11-bit ID) and extended (having a 29-bit ID). The data frame is used by the transmitting device to send data to the receiving device, and the data frame is the most important frame handled by the user.

Figure 9.7 shows the data frame’s structure. A standard data frame starts with the start of frame (SOF) bit, which is followed by an 11-bit identifier and the remote

transmission request (RTR) bit. The identifier and the RTR form the 12-bit arbitration field. 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. The data field is followed by the

Advanced PIC18 Projects—CAN Bus Projects -0197

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).

Advanced PIC18 Projects—CAN Bus Projects -0198

Start of Frame (SOF)

The start of frame field indicates the beginning of a data frame and is common to both standard and extended formats.

Arbitration Field

Arbitration is used to resolve bus conflicts that occur when several devices at once start sending messages on the bus. The arbitration field indicates the priority

of a frame, and it is different in the standard and extended formats. In the standard format there are 11 bits, and up to 2032 IDs can be set. The extended format

ID consists of 11 base IDs plus 18 extended IDs. Up to 2032 x 218 discrete IDs can be set.

During the arbitration phase, each transmitting device transmits its identifier and compares it with the level on the bus. If the levels are equal, the device continues to transmit. If the device detects a dominant level on the bus while it is trying to transmit a recessive level, it quits transmitting and becomes a receiving device.

After arbitration only one transmitter is left on the bus, and this transmitter continues to send its control field, data field, and other data.

The process of arbitration is illustrated in Figure 9.9 by an example consisting of three nodes having identifiers:

Advanced PIC18 Projects—CAN Bus Projects -0199

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.

Control Field

The control field is 6 bits wide, consisting of 2 reserved bits and 4 data length code (DLC) bits, and indicates the number of data bytes in the message being transmitted. This field is coded as shown in Table 9.1, where up to 8 transmit bytes can be coded with 6 bits.

Advanced PIC18 Projects—CAN Bus Projects -0200

Data Field

The data field carries the actual content of the message. The data size can vary from 0 to 8 bytes. The data is transmitted with the MSB first.

CRC Field

The CRC field, consisting of a 15-bit CRC sequence and a 1-bit CRC delimiter, is used to check the frame for a transmission error. The CRC calculation includes the start of frame, arbitration field, control field, and data field. The calculated CRC and the received CRC sequence are compared, and if they do not match, an error

is assumed.

ACK Field

The ACK field indicates that the frame has been received normally. This field consists of 2 bits, one for ACK slot and one for ACK delimiter.

 

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.

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.

Advanced PIC18 Projects—CAN Bus Projects -0191

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

Advanced PIC18 Projects—CAN Bus Projects -0192

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 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

Advanced PIC18 Projects—CAN Bus Projects -0193

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.

Advanced PIC18 Projects—CAN Bus Projects -0194

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

Advanced PIC18 Projects—CAN Bus Projects -0195

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.

Advanced PIC18 Projects—CAN Bus Projects -0196

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.

 

Advanced PIC18 Projects—USB Bus Projects:USB-Based Ambient Pressure Display on the PC

PROJECT 8.3—USB-Based Ambient Pressure Display on the PC

In this project, an ambient atmospheric pressure sensor is connected to a PIC18F4550 microcontroller, and the measured pressure is sent and displayed on a PC every second using a USB link.

An MPX4115A-type pressure sensor is used in this project. This sensor generates an analog voltage proportional to the ambient pressure. The device is available in either a 6-pin or an 8-pin package.

The pin configuration of a 6-pin sensor is:

Advanced PIC18 Projects—USB Bus Projects-0180Advanced PIC18 Projects—USB Bus Projects-0181

Figure 8.35 shows the variation of the output voltage of MPX4115A sensor as the pressure varies. We are interested in the range of pressure between 800 and 1100 millibars.

Advanced PIC18 Projects—USB Bus Projects-0182

Advanced PIC18 Projects—USB Bus Projects-0183

The circuit diagram of the project is shown in Figure 8.37. The sensor output is connected to analog input AN0 of the microcontroller. As in Project 8.2, the USB connector is connected to port pins RC4 and RC5 and the microcontroller is operated from an 8MHz crystal.

The program on the PC is based on Visual Basic, as in the previous projects. A single form is used, as shown in Figure 8.38, to display the pressure in millibars every second.

The microcontroller program listing (named PRESSURE.C) of the project is given in Figure 8.39. At the beginning of the main program the PORTA pins are defined as analog inputs by clearing ADCON1 to 0 and setting port pins as inputs. Then the interrupt registers are set to their default power-on values. Timer interrupt TMR0 is set

Advanced PIC18 Projects—USB Bus Projects-0184

to generate an interrupt every 3.3ms to keep the USB bus alive. The USB port of the microcontroller is then enabled, and ADCON2 is initialized by setting the A/D clock frequency to Fosc/64.

An endless loop is formed using a for statement. Inside this loop the pressure sensor data is read into variable Vin and then converted into physical voltage in millivolts and stored in variable mV. The atmospheric pressure is then calculated using Equation (8.4) and stored in variable Pint as a long integer. The mikroC function LongToStr converts this integer into a string in array op. Any leading spaces are removed from this array, and the resulting pressure is stored in a character array called Pressure. The mikroC USB function Hid_Write is then called to send the pressure data to the USB bus as 4- character data. The program then waits for one second, and the above process is repeated forever.

An 8MHz crystal is used to provide clock pulses to the microcontroller. The microcontroller CPU clock and the USB module are operated at 48MHz, and

the clock and configuration register settings are as in the other projects in this chapter.

Advanced PIC18 Projects—USB Bus Projects-0185

Advanced PIC18 Projects—USB Bus Projects-0186

Advanced PIC18 Projects—USB Bus Projects-0187

The PC program, based on Visual Basic, is called PRESSURE. Subroutine OnRead receives the data arriving at the USB port of the PC and then displays it on the screen form. The program does not send any data to the USB bus. The program listing (except the global variable declarations) is given in Figure 8.40.

Figure 8.41 shows a typical output from the Visual Basic program, displaying the atmospheric pressure.

An installable version of the Visual Basic program is provided on the CDROM that comes with this book, in folder PRESSURE.

Advanced PIC18 Projects—USB Bus Projects-0188

Advanced PIC18 Projects—USB Bus Projects-0189

Advanced PIC18 Projects—USB Bus Projects-0190