Thursday, February 09, 2006

Chapter 6: Serial Communication Modules

Chapter 6: Serial Communication Modules

EUSART

The Enhanced Universal Synchronous Asynchronous Receiver Transmitter (EUSART) module is a serial I/O communication peripheral. It is also known as Serial Communications Interface (SCI). It contains all clock generators, shift registers and data buffers necessary to perform an input or output serial data transfer independently of the device program execution. As its name states, apart from the usage of clock for synchronization, this module can also establish asynchronous connection, which makes it irreplaceable in some applications.
Serial Communication Usage
For example, in the event that it is difficult or impossible to provide special channels for clock and data transfer (for example, radio remote control or infrared), the EUSART module presents itself as a convenient solution.
Fig. 6-1 Remote Control and Plane
The EUSART system integrated into the PIC16F887 microcontroller has the following features:
  • Full-duplex asynchronous transmit and receive;
  • Programmable 8- or 9-bit character length;
  • Address detection in 9-bit mode;
  • Input buffer overrun error detection; and
  • Half-duplex communication in synchronous mode (master or slave).

EUSART Asynchronous Mode

The EUSART transmits and receives data using standard non-return-to-zero (NRZ) format. As seen in figure 6-2 below, this mode does not use clock signal, while the data format being transferred is very simple:
EUSART Asynchronous Mode
Fig. 6-2 EUSART Asynchronous Mode
Briefly, each data is transferred in the following way:
  • In idle state, data line has high logic level (1);
  • Each data transmission starts with START bit which is always a zero (0);
  • Each data is 8- or 9-bit wide (LSB bit is first transferred); and
  • Each data transmission ends with STOP bit which always has logic level which is always a one (1).

EUSART Asynchronous Transmitter

EUSART Asynchronous Transmitter
Fig. 6-3 EUSART Asynchronous Transmitter
In order to enable data transmission via EUSART module, it is necessary to configure it to operate as a transmitter. In other words, it is necessary to define the state of the following bits:
TXEN = 1 - EUSART transmitter is enabled by setting this bit of the TXSTA register;
SYNC = 0 - EUSART is configured to operate in asynchronous mode by clearing this bit of the TXSTA register; and
SPEN = 1 - By setting this bit of the RCSTA register, EUSART is enabled and the TX/CK pin is automatically configured as output. If this bit is simultaneously used for some analog function, it must be disabled by clearing the corresponding bit of the ANSEL register.
The central part of the EUSART transmitter is the shift register TSR which is not directly accessible by the user. In order to start transmission, the module must be enabled by setting the TXEN bit of the TXSTA register. Data to be sent should be written to the TXREG register, which will cause the following sequence of events:
  • Byte will be immediately transferred to the shift register TSR;
  • TXREG register remains empty, which is indicated by setting flag bit TXIF of the PIR1 register. If the TXIE bit of the PIE1 register is set, an interrupt will be generated. Besides, the flag is set regardless of whether an interrupt is enabled or not. Also, it cannot be cleared by software, but by writing new data to the TXREG register;
  • Control electronics "pushes" data toward the TX pin in rhythm with internal clock: START bit (0) ... data ... STOP bit (1);
  • When the last bit leaves the TSR register, the TRMT bit of the TXSTA regis ter is automatically set; and
  • If the TXREG register has received a new character data in the meantime, the whole procedure is repeated immediately after the STOP bit of the previous character has been transmitted.
Sending 9-bit data is enabled by setting the TX9 bit of the TXSTA register. The TX9D bit of the TXSTA register is the ninth and Most Significant data bit. When transferring 9-bit data, the TX9D data bit must be written before writing the 8 least significant bits into the TXREG register. All nine bits of data will be transferred to the TSR shift register immediately after the TXREG write is complete.

EUSART Asynchronous Receiver

EUSART Asynchronous Receiver
Fig. 6-4 EUSART Asynchronous Receiver
Similar to the activation of EUSART transmitter, in order to enable the receiver it is necessary to define the following bits:
CREN = 1 - EUSART receiver is enabled by setting this bit of the RCSTA register;
SYNC = 0 - EUSART is configured to operate in asynchronous mode by clearing this bit stored in the TXSTA register; and
SPEN = 1 - By setting this bit of the RCSTA register, EUSART is enabled and the RX/DT pin is automatically configured as input. If this bit is simultaneously used for some analog function, it must be disabled by clearing the corresponding bit of the ANSEL register.
When this first and necessary step is accomplished and START bit is detected, data is transferred to the shift register RSR through the RX pin. When the STOP bit has been received, the following occurs:
  • Data is automatically transferred to the RCREG register (if empty);
  • The flag bit RCIF is set and an interrupt, if enabled by the RCIE bit of the PIE1 register, occurs. Similar to transmitter, the flag bit is cleared by software only, i.e. by reading the RCREG register. Bear in mind that this is a two character FIFO memory (first-in, first-out) which allows reception of two characters simultaneously;
  • If the RCREG register is occupied (contains two bytes) and the shift register detects new STOP bit, the overflow bit OERR will be set. In this case, a new coming data is lost, and the OEER bit must be cleared by software. It is done by clearing and resetting the CREN bit.
    Note: it is not possible to receive new data as far as the OERR bit is set;
  • If the STOP bit is zero (0), the FERR bit of the RCSTAregister detecting receive error will be set; and
  • To receive 9-bit data it is necessary to set the RX9 bit of the RCSTA register.

Receive Error Detection

There are two types of errors which the microcontroller can automatically detect. The first one is called Framing error and occurs when the receiver does not detect the STOP bit at the expected time. Such error is indicated via the FERR bit of the RCSTA register. If this bit is set, it means that the last received data may be incorrect. It is important to know several things:
  • A Framing error does not generate an interrupt by itself;
  • If this bit is set, the last received data has an error;
  • A framing error (bit set) does not prevent reception of new data;
  • The FERR bit is cleared by reading received data, which means that check must be done before data reading; and
  • The FERR bit cannot be cleared by software. If needed, it can be cleared by clearing the SPEN bit of the RCSTA register. It will simultaneously cause reset of the whole EUSART system.
Another type of error is called Overrun Error. The receive FIFO can hold two characters. An overrun error will be generated if the third character is received. Simply, there is no space for another one byte and an error is unavoidable! When this happens the OERR bit of the RCSTA register is set. The consequences are the following:
  • Data already stored in the FIFO registers (two bytes) can be normally read;
  • No additional data will be received until the OERR bit is cleared; and
  • This bit is not directly accessed. To clear it, it is necessary to clear the CREN bit of the RCSTA register or to reset the whole EUSART system by clearing the SPEN bit of the RCSTA register.

Receiving 9-bit Data

In addition to receiving standard 8-bit data, the EUSART system supports 9-bit data reception. On the transmit side, the ninth bit is "attached" to the original byte just before the STOP bit. On the receive side, when the RX9 bit of the RCSTA register is set, the ninth data bit will be automatically written to the RX9D bit of the same register. When this byte is received, one should take care of how to read its bits- the RX9D data bit must be read before reading the 8 least significant bits of the RCREG register. Otherwise, the ninth data bit will be automatically cleared.
Receiving 9-bit Data
Fig. 6-5 Receiving 9-bit Data

Address Detection

When the ADDEN bit of the RCSTAregister is set, the EUSART module is able to receive only 9-bit data, whereas all 8-bit data will be ignored. Although it seems like a restriction, such modes enable serial communication between several microcontrollers. The principle of operation is simple. The master device sends 9-bit data which represents the address of one microcontroller. All slave microcontrollers sharing the same transmission line, receive this data. Of course, each of them must have the ADDEN bit set because it enables address detection.
Address Detection
Upon receiving this data each slave checks if that address matches its own. Software, in which address match occurs, must disable address detection by clearing its ADDEN bit. The master device keeps on sending 8-bit data. All data passing through the transmission line will be received by "recognized" EUSART module only. Upon receiving the last byte, the slave device should set the ADDEN bit in order to enable new address detection.
Sending Data
Fig. 6-7 Sending Data

TXSTA Register

TXSTA Register
Fig.6-8 TXSTA Register
CSRC - Clock Source Select bit - determines clock source. It is used only in synchronous mode.
  • 1 - Master mode. Clock is generated internally from Baud Rate Generator; and
  • 0 - Slave mode. Clock is generated from external source.
TX9 - 9-bit Transmit Enable bit
  • 1 - 9-bit data transmission via EUSART system; and
  • 0 - 8-bit data transmission via EUSART system.
TXEN - Transmit Enable bit
  • 1 - Transmission enabled; and
  • 0 - Transmission disabled.
SYNC - EUSART Mode Select bit
  • 1 - EUSART operates in synchronous mode; and
  • 0 - EUSART operates in asynchronous mode.
SENDB - Send Break Character bit is only used in asynchronous mode and only in case it is required to observe LIN bus standard.
  • 1 - Sending Break character is enabled; and
  • 0 - Break character transmission is completed.
BRGH - High Baud Rate Select bit determines baud rate in asynchronous mode. It does not affect EUSART in synchronous mode.
  • 1 - EUSART operates at high speed; and
  • 0 - EUSART operates at low speed.
TRMT - Transmit Shift Register Status bit
  • 1 - TSR register is empty; and
  • 0 - TSR register is full.
TX9D - Ninth bit of Transmit Data can be used as address or parity bit.

RCSTA Register

RCSTA Register
Fig.6-9 RCSTA Register
SPEN - Serial Port Enable bit
  • 1 - Serial port enabled. RX/DT and TX/CK pins are automatically configured as input and output respectively; and
  • 0 - Serial port disabled.
RX9 - 9-bit Receive Enable bit
  • 1 - Receiving 9-bit data via EUSART system; and
  • 0 - Receiving 8-bit data via EUSART system.
SREN - Single ReceiveEnable bit is used only in synchronous mode when the microcontroller operates as master.
  • 1 - Single receive enabled; and
  • 0 - Single receive disable.
CREN - Continuous Receive Enable bit acts differently depending on EUSART mode.
Asynchronous mode:
  • 1 - Receiver enabled; and
  • 0 - Receiver disabled.
Synchronous mode:
  • 1 - Enables continuous receive until the CREN bit is cleared; and
  • 0 - Disables continuous receive.
ADDEN - Address Detect Enable bit is only used in address detect mode.
  • 1 - Enables address detection on 9-bit data receive; and
  • 0 - Disables address detection. The ninth bit can be used as parity bit.
FERR - Framing Error bit
  • 1 - On receive, Framing Error is detected; and
  • 0 - No framing error.
OERR - Overrun Error bit.
  • 1 - On receive, Overrun Error is detected; and
  • 0 - No overrun error.
RX9D - Ninth bit of Received Data can be used as address or parity bit.

EUSART Baud Rate Generator (BRG)

If you carefully look at the asynchronous EUSART receiver or transmitter diagram, you will see, in both cases, that clock signal from the local timer BRG is used for synchronization. The same clock source is also used in synchronous mode.
This timer consists of two 8-bit registers comprising one 16-bit register.
EUSART Baud Rate Generator (BRG)
Fig. 6-10 EUSART Baud Rate Generator (BRG)
A number written to these two registers determines the baud rate. Besides, both the BRGH bit of the TXSTA register and the BRGH16 bit of the BAUDCTL register affect clock frequency.
The formula used to determine Baud Rate is given in the table below.
Bits BRG / EUSART Mode Baud Rate Formula
SYNC BRG1G BRGH
0 0 0 8-bit / asynchronous Fosc / [64 (n + 1)]
0 0 1 8-bit / asynchronous Fosc / [16 (n + 1)]
0 1 0 16-bit / asynchronous Fosc / [16 (n + 1)]
0 1 1 16-bit / asynchronous Fosc / [4 (n + 1)]
1 0 X 8-bit / asynchronous Fosc / [4 (n + 1)]
1 1 X 16-bit / asynchronous Fosc / [4 (n + 1)]
Table 6-1 Baud Rate
The following tables contain values that should be written to the 16-bit register SPBRG and assigned to the SYNC, BRGH and BRGH16 bits in order to obtain some of the standard baud rates.
The formulas used to determine the Baud Rate are:
Formulas used to determine the Baud Rate
Table 1
Table 2
Table 3
Table 4
Table 5
Table 6
Table 7
Table 8
Table 6-2 Determining Baud Rate

BAUDCTL Register

BAUDCTL Register
Fig. 6-11 BAUDCTL Register
ABDOVF - Auto-Baud Detect Overflow bit is only used in asynchronous mode during baud rate detection.
  • 1 - Auto-baud timer overflowed; and
  • 0 - Auto-baud timer did not overflow.
RCIDL - Receive Idle Flag bit is only used in asynchronous mode.
  • 1 - Receiver is idle; and
  • 0 - START bit has been received and receiving is in progress.
SCKP - Synchronous Clock Polarity Select bit acts differently depending on EUSART mode.
Asynchronous mode:
  • 1 - Transmit inverted data to the RC6/TX/CK pin; and
  • 0 - Transmit non-inverted data to the same pin.
Synchronous mode:
  • 1 - Synchronization on rising edge of the clock; and
  • 0 - Synchronization on falling edge of the clock.
WUE Wake-up Enable bit
  • 1 - Receiver waits for a falling edge on the RC7/RX/DT pin to start waking up the microcontroller from sleep mode; and
  • 0 - Receiver operates normally.
ABDEN - Auto-Baud Detect Enable bit is used in asynchronous mode only.
  • 1 - Auto-baud detect mode is enabled. Bit is automatically cleared on baud rate detect; and
  • 0 - Auto-baud detect mode is disabled.

In Short:

Sending data via asynchronous EUSART communication:
  1. The desired baud rate should be set by using bits BRGH (TXSTA register) and BRG16 (BAUDCTL register) and registers SPBRGH and SPBRG;
  2. The SYNC bit (TXSTA register) should be cleared and the SPEN bit should be set (RCSTA register) in order to enable serial port;
  3. On 9-bit data transmission, the TX9 bit of the TXSTA register should be set;
  4. Data transmission is enabled by setting bit TXEN of the TXSTA register. Bit TXIF of the PIR1 register is automatically set;
  5. If needed the bit TXEN causes an interrupt, the GIE and PEIE bits of the INTCON register should be set;
  6. On 9-bit data transmission, value of the ninth bit should be written to the TX9D bit of the TXSTA register; and
  7. Transmission starts by writing 8-bit data to the TXREG register.
Receiving data via asynchronous EUSART communication:
  1. Baud Rate should be set by using bits BRGH (TXSTA register) and BRG16 (BAUDCTL register) and registers SPBRGH and SPBRG;
  2. The SYNC bit (TXSTA register) should be cleared and the SPEN bit should be set (RCSTA register) in order to enable serial port;
  3. If it is necessary the data receive causes an interrupt, both the RCIE bit of the PIE1 register and bits GIE and PEIE of the INTCON register should be set;
  4. On 9-bit data receive, the RX9 bit of the RCSTA register should be set;
  5. Data receive should be enabled by setting the CREN bit of the RCSTA register;
  6. The RCSTA register should be read to get information on possible errors which have occurred during transmission. On 9-bit data receive, the ninth bit will be stored in this register; and
  7. Received 8-bit data stored in the RCREG register should be read.
Setting Address Detection Mode:
  1. Baud Rate should be set by using bits BRGH (TXSTA register) and BRG16 (BAUDCTL register) and registers SPBRGH and SPBRG;
  2. The SYNC bit (TXSTA register) should be cleared and the SPEN bit should be set (RCSTA register) in order to enable serial port;
  3. If it is necessary the data receive causes an interrupt, the RCIE bit of the PIE1 bit as well as bits GIE and PEIE of the INTCON register should be set;
  4. The RX9 bit of the RCSTA register should be set;
  5. The ADDEN of the RCSTA register should be set, which enables a data to be interpreted as address;
  6. Data receive is enabled by setting the CREN bit of the RCSTA register;
  7. Immediately upon 9-bit data is received, the RCIF bit of the PIR1 register will be automatically set. If enabled, an interrupt occurs;
  8. The RCSTA register should be read in order to get information on possible errors which have occurred during transmission. The ninth bit RX9D is always set; and
  9. Received 8-bits stored in the RCREG register should be read. It should be checked whether the combination of these bits matches the predefined address. If the match occurs, it is necessary to clear the ADDEN bit of the RCSTA register, which enables further 8-bit data receive.

Master Synchronous Serial Port Module

MSSP module (Master Synchronous Serial Port) is a very useful, but at the same time one of the most complex circuit within the microcontroller. It enables high speed communication between a microcontroller and other peripherals or microcontroller devices by using few input/output lines (maximum two or three). Therefore, it is commonly used to connect the microcontroller to LCD displays, A/D converters, serial EEPROMs, shift registers etc. The main feature of this type of communication is that it is synchronous and suitable for use in systems with a single master and one or more slaves. A master device contains the necessary circuitry for baud rate generation and supplies the clock for all devices in the system. Slave devices may in that way eliminate the internal clock generation circuitry. The MSSP module can operate in one of two modes:
  • SPI mode (Serial Peripheral Interface)
  • I²C mode (Inter-Integrated Circuit)
As seen in figure 6-12 below, one MSSP module represents only a half of the hardware needed to establish serial communication, while another half is stored in the device the data is exchanged with. Even though the modules on both ends of the line are the same, their modes are essentially different depending on whether they operate as a Master or a Slave:
If the microcontroller to be programmed controls another device or circuit (peripherals), it should operate as a master device. A module defined as such will generate clock when needed, i.e. only when data receive and transmit is required by the software. It depends on the master whether the connection will be established or not. Otherwise, if the microcontroller to be programmed is a part of some peripheral which belongs to some more complex device (for example PC), then it should operate as a slave device. As such, it always has to wait for request for data transfer from master device.
Master Synchronous Serial Port Module
Fig.6-12 MSSP Module

SPI Mode

The SPI mode allows 8 bits of data to be transmitted and received simultaneously using 3 input/output lines:
  • SDO - Serial Data Out - transmit line;
  • SDI - Serial Data In - receive line; and
  • SCK - Serial Clock - synchronization line.
In addition to these three lines, if the microcontroller exchanges data with several peripheral devices, the forth line (SS) may be also used. Refer to figure 6-13 below.
SS - Slave Select - is additional pin used for specific device selection. It is active only in case the microcontroller is in slave mode, i.e. when the external - master device requires data exchange.
When operating in SPI mode, MSSP module uses in total of 4 registers:
  • SSPSTAT status register;
  • SSPCON control register;
  • SSPBUF buffer register; and
  • SSPSR shift register (not directly available)
The first three registers are writable/readable and can be changed at any moment, while the forth register, since not available, is used for converting data into "serial" format.
Selected peripheral device to accomplish SPI communication with
Fig. 6-13 SPI Mode
As seen in figure 6-14, the central part of the SPI module consists of two registers connected to pins for receive, transmit and synchronization.
Shift register (SSPRS) is directly connected to the microcontroller pins and used for data transmission in serial format. The SSPRS register has its input and output and shifts the data in and out of device. In other words, each bit appearing on input (receive line) simultaneously shifts another bit toward output (transmit line).
The SSPBUF register (Buffer) is a part of memory used to temporarily hold the data written to the SSPRS until the received data is ready. Upon receiving all 8 bits of data, that byte is moved to the SSPBUF register. This double buffering of the received data (SSPBUF) allows the next byte to start reception before reading the data that was just received. Any write to the SSPBUF register during transmission/reception of data will be ignored. Since having been the most accessed, this register is considered the most important from the programmers’ point of view.
Namely, if mode settings are neglected, data transfer via SPI actually means to write and read data from this register, while another "acrobatics" such as moving registers are automatically performed by hardware.
Data transfer via SPI
Fig. 6-14 SPI Mode

In short:

Prior to initializing the SPI, it is necessary to specify several options:
  • Master mode (SCK pin is the clock output);
  • Slave mode (SCK pin is the clock input);
  • Data input phase- middle or end of data output time (SMP bit);
  • Clock edge (CKE bit);
  • Baud Rate (only in Master mode); and
  • Slave select mode (Slave mode only).
Step 1.
Step 1.
Data to transmit should be written to the buffer register SSPBUF. Immediately after that, if the SPI module operates in master mode, the microcontroller will automatically perform the following steps 2, 3 and 4. If the SPI module operates as Slave, the microcontroller will not perform these steps until the SCK pin detects clock signal.
Fig. 6-15 Step 1
Step 2.
Step 2.
This data is now moved to the SSPSR register and the SSPBUF register is not cleared.
Fig. 6-16 Step 2
Step 3.
Step 3.
Synchronized with clock signal, this data is shifted to the output pin (MSB bit first) while the register is simultaneously being filled with bits through input pin. In Master mode, the microcontroller itself generates clock, while the Slave mode uses external clock (pin SCK).
Fig. 6-17 Step 3
Step 4.
Step 4.
The SSPSR register is full once the 8 bits of data have been received. It is indicated by setting the BF and SSPIF bits. The received data (that byte) is automatically moved from the SSPSR register to the SSPBUF register. Since data transfer via serial communication is performed automatically, the rest of the program is normally executed while data transfer is in progress. In that case, the function of the SSPIF bit is to generate interrupt when one byte transmission is completed.
Fig. 6-18 Step 4
Step 5.
Step 5.
At last, the data stored in the SSPBUF register is ready for use and moved to any register available.
Fig. 6-19 Step 5

I²C mode

I²C mode (Inter IC Bus) is especially suitable when the microcontroller and integrated circuit, which the microcontroller should exchange data with, are within the same device. It is commonly about another microcontrollers or specialized, cheap integrated circuits belonging to the new generation of so called "smart peripheral components" (memories, temperature sensors, real-time clocks etc.)
Similar to serial communication in SPI mode, data transfer in I²C mode is synchronous and bidirectional. This time only two pins are used for data transfer. These are the SDA (Serial Data) and SCL (Serial Clock) pins. The user must configure these pins as inputs or outputs through the TRISC bits.
Perhaps it is not directly visible. By observing particular rules (protocols), this mode enables up to 122 different components to be simultaneously connected in a simple way by using only two valuable I/O pins. Briefly, everything works as follows: Clock necessary to synchronize the operation of both devices is always generated by the master device (microcontroller) and its frequency directly affects baud rate. There are protocols allowing maximum 3,4 MHz clock frequency (so called high-speed I²C bus), but the clock frequency of the most frequently used protocol is limited to 100 KHz. There is no limit in case of minimal frequency.
When master and slave components are synchronized by the clock, every data exchange is always initialized by master. Once the MSSP module has been enabled, it waits for a Start condition to occur. First the master device sends the START bit (logic zero) through the SDA pin, then the 7-bit address of the selected slave device, and finally, the bit which requires data write (0) or read (1) to that device. Accordingly, following the start condition, the eight bits are shifted into the SSPSR register. All slave devices share the same transmission line and all will simultaneously receive the first byte, but only one of them has the address to match.
I²C mode
Fig. 6-20 Master and Slave Configuration
Once the first byte has been sent (only 8-bit data are transmitted), master goes into receive mode and waits for acknowledgment from the receive device that address match has occurred. If the slave device sends acknowledge data bit (1), data transfer will be continued until the master device (microcontroller) sends the Stop bit.
This is the simplest explanation of how two components communicate. If needed, this microcontroller is able to control more complicated situations when 1024 different components, shared by several different master devices, are connected. Such devices are rarely used in practice and there is no need to discuss them at greater length.
How two components communicate
Fig. 6-21 Data Transfer
Figure below shows the block diagram of the MSSP module in I²C mode.
Block diagram of the MSSP module in I²C mode
Fig. 6-22 MSSP Block Diagram in I²C Mode
The MSSP module uses six registers for I²C operation. Some of them are shown in figure above:
  • SSPCON;
  • SSPCON2;
  • SSPSTAT;
  • SSPBUF;
  • SSPSR; and
  • SSPADD.

SSPSTAT Register

SSPSTAT Register
Fig. 6-23 SSPSTAT Register
SMP Sample bit
SPI master mode - This bit determines input data phase.
  • 1 - Logic state is read at end of data output time; and
  • 0 - Logic state is read in the middle of data output time.
SPI slave mode This bit must be cleared when SPI is used in Slave mode.
I²C mode (master or slave)
  • 1 - Slew rate control disabled for standard speed mode (100kHz); and
  • 0 - Slew rate control enabled for high speed mode (400kHz).
CKE - Clock Edge Select bit selects synchronization mode.
CKP = 0:
  • 1 - Data is transmitted on rising edge of clock pulse (0 - 1); and
  • 0 - Data is transmitted on falling edge of clock pulse (1 - 0).
CKP = 1:
  • 1 - Data is transmitted on falling edge of clock pulse (1 - 0); and
  • 0 - Data is transmitted on rising edge of clock pulse (0 - 1).
D/A - Data/Address bit is used in I²C mode only.
  • 1 - Indicates that the last byte received or transmitted was data; and
  • 0 - Indicates that the last byte received or transmitted was address.
P - Stop bit is used in I²C mode only.
  • 1 - STOP bit was detected last; and
  • 0 - STOP bit was not detected last.
S - Start bit is used in I²C mode only.
  • 1 - START bit was detected last; and
  • 0 - START bit was not detected last.
R/W - Read Write bit is used in I²C mode only. This bit holds the R/W bit information following the last address match. This bit is only valid from the address match to the next Start bit, Stop bit or not ACK bit.
In I²C slave mode
  • 1 - Data read; and
  • 0 - Data write.
In I²C master mode
  • 1 - Transmit is in progress; and
  • 0 - Transmit is not in progress.
UA - Update Address bit is used in 10-bit I²C mode only.
  • 1 - Indicates that it is necessary to update the address in the SSPADD register; and
  • 0 - Address in the SSPADD register is correct and does not need to be updated.
BF Buffer Full Status bit
During data receive (in SPI and I²C modes)
  • 1 - Receive complete. The SSPBUF register is full; and
  • 0 - Receive not complete. The SSPBUF register is empty.
During data transmit (in I²C mode only)
  • 1 - Data transmit in progress (does not include the bits ACK and STOP); and
  • 0 - Data transmit complete (does not include the bits ACK and STOP).

SSPCON Register

SSPCON Register
Fig. 6-24 SSPCON Register
WCOL Write Collision Detect bit
  • 1 - Collision detected. A write to the SSPBUF register was attempted while the I²C conditions were not valid for a transmission to start; and
  • 0 - No collision.
SSPOV Receive Overflow Indicator bit
  • 1 - A new byte is received while the SSPSR register still holds the previous data. Since there is no space for new data receive, one of these two bytes must be cleared. In this case, data in SSPSR is lost; and
  • 0 - Serial data is correctly received.
SSPEN - Synchronous Serial Port Enable bit determines the microcontroller pins function and initializes MSSP module:
In SPI mode
  • 1 - Enables MSSP module and configures pins SCK, SDO, SDI and SS as the source of the serial port pins; and
  • 0 - Disables MSSP module and configures these pins as I/O port pins.
In I²C mode
  • 1 - Enables MSSP module and configures pins SDA and SCL as the source of the serial port pins; and
  • 0 - Disables MSSP module and configures these pins as I/O port pins.
CKP - Clock Polarity Select bit is not used in I²C master mode.
In SPI mode
  • 1 - Idle state for clock is a high level; and
  • 0 - Idle state for clock is a low level.
In I²C slave mode
  • 1 - Enables clock; and
  • 0 - Holds clock low. Used to provide more time for data stabilization.
SSPM3-SSPM0 - Synchronous Serial Port Mode Select bits. SSP mode is determined by combining these bits:
SSPM3 SSPM2 SSPM1 SSPM0 Mode
0 0 0 0 SPI master mode, clock = Fosc/4
0 0 0 1 SPI master mode, clock = Fosc/16
0 0 1 0 SPI master mode, clock = Fosc/64
0 0 1 1 SPI master mode, clock = (output TMR)/2
0 1 0 0 SPI slave mode, SS pin control enabled
0 1 0 1 SPI slave mode, SS pin control disabled, SS can be used as I/O pin
0 1 1 0 I²C slave mode, 7-bit address used
0 1 1 1 I²C slave mode, 10-bit address used
1 0 0 0 I²C master mode, clock = Fosc / [4(SSPAD+1)]
1 0 0 1 Mask used in I²C slave mode
1 0 1 0 Not used
1 0 1 1 I²C controlled master mode
1 1 0 0 Not used
1 1 0 1 Not used
1 1 1 0 I²C slave mode, 7-bit address used,START and STOP bits enable interrupt
1 1 1 1 I²C slave mode, 10-bit address used,START and STOP bits enable interrupt
Table 6-3 Synchronous Serial Port Mode Select Bits

SSPCON2 Register

SSPCON2 Register
Fig. 6-25 SSPCON2 Register
GCEN - General Call Enable bit
In I²C slave mode only
  • 1 - Enables interrupt when a general call address (0000h) is received in the SSPSR; and
  • 0 - General call address disabled.
ACKSTAT - Acknowledge Status bit
In I²C Master Transmit mode only
  • 1 - Acknowledge was not received from slave; and
  • 0 - Acknowledge was received from slave.
ACKDT - Acknowledge data bit
In I²C Master Receive mode only
  • 1 - Not Acknowledge; and
  • 0 - Acknowledge.
ACKEN - Acknowledge condition Enable bit
In I²C Master Receive mode
  • 1 - Initiate acknowledge condition on SDA and SCL pins and transmit ACKDT data bit. It is automatically cleared by hardware; and
  • 0 - Acknowledge condition is not initiated.
RCEN - Receive Enable bit
In I²C Master mode only
  • 1 - Enables data receive in I²C mode; and
  • 0 - Receive disabled.
PEN - STOP condition Enable bit
In I²C Master mode only
  • 1 - Initiates STOP condition on pins SDA and SCL. Afterwards, this bit is automatically cleared by hardware; and
  • 0 - STOP condition is not initiated.
RSEN - Repeated START Condition Enabled bit
In I²C master mode only
  • 1 - Initiates START condition on pins SDA and SCL. Afterwards, this bit is automatically cleared by hardware; and
  • 0 - Repeated START condition is not initiated.
SEN - START Condition Enabled/Stretch Enabled bit
In I²C Master mode only
  • 1 - Initiate START condition on pins SDA and SCL. Afterwards, this bit is automatically cleared by hardware; and
  • 0 - START condition is not initiated.

I²C in Master Mode

The most common case is when the microcontroller operates as a master and the peripheral component as a slave. This is why this book covers just this mode. It is also considered that the address consists of 7 bits and device contains only one microcontroller (one master device).
In order to enable MSSP module in this mode, it is necessary to do the following:
Set baud rate (SSPADD register), turn off slew rate control (by setting the SMP bit of the SSPSTAT register) and select master mode (SSPCON register). After the preparation has been finished and module has been enabled (SSPCON register: SSPEN bit), one should wait for internal electronics to signal that everything is ready for data transmission, i.e. the SSPIF bit of the PIR1 register is set.
This bit should be cleared by software and after that, the microcontroller is ready to start "communication" with peripherals.
SSPCON2 Register
Fig. 6-27 I²C in Master Mode

Data Transmission in I²C Master Mode

Each clock condition on the SDA pin starts with logic zero (0) which appears upon setting the SEN bit of the SSPCON2 register. Even enabled, the microcontroller has to wait a certain time before it starts communication. It is the so called "Start condition" during which internal preparations and checks are performed. If all conditions are met, the SSPIF bit of the PIR1 is set and data transfer starts as soon as the SSPBUF register is loaded.
Data Transmission in I²C Master Mode
Since maximum 112 integrated circuits may simultaneously share the same transmission line, the first data byte must contain address which matches only one slave device. Each component has its own address listed in the proper data sheet. The eighth bit of the first data byte specifies direction of data transmission, the microcontroller is to send or receive data. In this case, it is all about data receive and the eighth bit therefore is logic zero (0).
Fig. 6-28 Data Transmission in I²C Master Mode
Waiting for the acknowledge data bit
When address match occurs, the microcontroller has to wait for the acknowledge data bit. The slave device acknowledges address match by clearing the ASKSTAT bit of the SSPCON2 register. If the match properly occurred, all bytes representing data are transmitted in the same way.
Data transmission ends by setting the SEN bit of the SSPCON2 register. The so called STOP condition occurs, which enables the SDA pin to receive pulse condition: Start - Address - Acknowledge - Data - Acknowledge ....Data - Acknowledge - Stop!
Fig.6-29 Data Transmission in I²C Master Mode

Data Reception in I²C Master Mode

Preparations for data reception are similar to those for data transmission, with exception that the last bit of the first sent byte (containing address) is logic one (1). It specifies that master expects to receive data from addressed slave device. With regard to the microcontroller, the following events occur:
After internal preparations are finished and START bit is set, slave device starts sending one byte at a time. These bytes are stored in the serial register SSPSR. Each data is, after receiving the last eighth bit, loaded to the SSPBUF register from where it can be read. By reading this register, the acknowledge bit is automatically sent, which means that master device is ready to receive new data.
At the end, similar to data transmission, data reception ends by setting the STOP bit:
Data Reception in I²C Master Mode
Fig. 6-30 Data Reception in I²C Master Mode
Start - Address - Acknowledge - Data - Acknowledge .... Data - Acknowledge - Stop!
In this pulse condition, the acknowledge bit is sent to slave device.

Baud Rate Generator

In order to synchronize data transmission, all events taking place on the SDA pin must be synchronized with the clock generated in master device. This clock is generated by a simple oscillator whose frequency depends on the microcontroller’s main oscillator frequency, value written to the SSPADD register and the current SPI mode.
The clock frequency of the mode described in this book depends on selected quartz crystal and the SPADD register. The formula used to calculate it is shown in figure below.
Baud Rate Generator
Fig. 6-31 Baud Rate Generator

Useful notes ...

When the microcontroller communicates with peripheral components, it may happen that data transfer fails for some reason. In that case, it is recommended to check the status of some bits which can clarify the problem. In practice, the state of these bits is checked by executing a short subroutine after each byte transmission and reception (just in case).
WCOL (SPCON,7) - If you try to write a new data to the SSPBUF register while another data transmit/receive is in progress, the WCOL bit will be set and the contents of the SSPBUF register remains unchanged. Write does not occur. After this, the WCOL bit must be cleared in software.
BF (SSPSTAT,0) - In transmit mode, this bit is set when the CPU writes to the SSPBUF register and remains set until the byte in serial format is shifted from the SSPSR register. In receive mode, this bit is set when data or address is loaded to the SSPBUF register. It is cleared when the SSPBUF register is read.
SSPOV (SSPCON,6) - In receive mode, this bit is set when a new byte is received by the SSPSR register via serial communication, whereas the previously received data has not been read from the SSPBUF register yet.
SDA and SCL Pins - When SPP module is enabled, these pins turns into Open Drain outputs. It means that these pins must be connected to the resistors which, at the other end, are connected to positive power supply.
SDA and SCL Pins
Fig. 6-32 Open Drain Output Resistors

In Short:

In order to establish serial communication in I²C mode, the following should be done:

Setting Module and Sending Address:

  • Value to determine baud rate should be written to the SSPADD register;
  • SlewRate control should be turned off by setting the SMP bit of the SSPSTAT register;
  • In order to select Master mode, binary value 1000 should be written to the SSPM3-SSPM0 bits of the SSPCON1 register;
  • The SEN bit of the SSPCON2 register should be set (START condition);
  • The SSPIF bit is automatically set at the end of START condition when the module is ready to operate. It should be cleared;
  • Slave address should be written to the SSPBUF register; and
  • When the byte is sent, the SSPIF bit (interrupt) is automatically set when the acknowledge bit has been received from the Slave device.

Data Transmit:

  • Data is to be send should be written to the SSPBUF register;
  • When the byte is sent, the SSPIF bit (interrupt) is automatically set upon the acknowledge bit has been received from Slave device; and
  • In order to inform the Slave device that transmit is complete, STOP condition should be initiated by setting the PEN bit of the SSPCON register.

Data Receive:

  • In order to enable receive the RSEN bit of the SSPCON2 register should be set;
  • The SSPIF bit signals data receive. When data is read from the SSPBUF register, the ACKEN bit of the SSPCON2 register should be set in order to enable sending acknowledge bit; and
  • In order to inform Slave device that transmit is complete, the STOP condition should be initiated by setting the PEN bit of the SSPCON register.

Wednesday, February 08, 2006

Chapter 5: CCP Modules

Chapter 5: CCP Modules

The abbreviation CCP stands for Capture/Compare/PWM.
The CCP module is a peripheral which allows the user to time and control different events.
Capture Mode, allows timing for the duration of an event. This circuit gives insight into the current state of a register which constantly changes its value. In this case, it is the timer TMR1 register.
Compare Mode compares values contained in two registers at some point. One of them is the timer TMR1 register. This circuit also allows the user to trigger an external event when a predetermined amount of time has expired.
PWM - Pulse Width Modulation can generate signals of varying frequency and duty cycle.
The PIC16F887 microcontroller has two such modules - CCP1 and CCP2.
Both of them are identical in normal mode, with the exception of the Enhanced PWM features available on CCP1 only. This is why this chapter describes the CCP1 module in detail. Concerning CCP2, only the features distinguishing it from CCP1 will be covered.
Complicated? All this is only a simplified explanation on their operation. Everything is much more complicated in practice because these modules can operate in many different modes. Try to analyze their operation on the basis of the tables describing bit functions. If you use any CCP module, first select the mode you need, analyze the appropriate figure and then start changing bits of the registers or else...

CCP1 Module

A central part of this circuit is a 16-bit register CCPR1, which consists of the CCPR1L and CCPR1H registers. It is used for capturing or comparing with binary number stored in the timer register TMR1 (TMR1H and TMR1L).
CCP1 Module
Fig. 5-1 CCP1 Module
In Compare mode, if enabled by software, the timer TMR1 reset may occur on match. Besides, the CCP1 module can generate PWM signals of varying frequency and duty cycle.
Bits of the CCP1CON register controls the CCP1 module.

CCP1 in Capture mode

In this mode, the timer register TMR1 (consisting of TMR1H and TMR1L) is copied to the CCP1 register (consisting of CCPR1H and CCPR1L) in the following situations:
  • Every falling edge (1 » 0) on the RC2/CCP1 pin;
  • Every rising edge (0 » 1) on the RC2/CCP1 pin;
  • Every 4th rising edge (0 » 1) on the RC2/CCP1 pin; and
  • Every 16th rising edge (0 » 1) on the RC2/CCP1 pin.
The combination of the four bits (CCP1M3 - CCP1M0) of the control register determines which of these events will trigger 16-bit data transfer. In addition, the following conditions must be met:
  • RC2/CCP1 pin must be configured as input; and
  • TMR1 module must operate as timer or synchronous counter.
CCP1 in Capture mode
Fig. 5-2 CCP1 in Capture mode
The flag bit CCP1IF is set when a capture is made. If it happens and if the CCP1IE bit of the PIE register is set, then an interrupt occurs.
When the Capture mode is changed, an undesirable capture interrupts may be generated. In order to avoid that, both a bit enabling CCP1IE interrupt and flag bit CCP1IF should be cleared prior to any change occuring in the control register.
Undesirable interrupt may be also generated by switching from one capture prescaler to another. To avoid this, the CCP1 module should be temporarily switched off before changing the prescaler.
The following program sequence is recommended:
BANKESEL CCP1CON CLRF     CCP1CON     ;CONTROL REGISTER IS CLEARED                      ;CCP1 MODULE IS OFF MOVLW    XX          ;NEW PRESCALER MODE IS SELECTED MOVWF    CCP1CON     ;NEW VALUE IS LOADED TO THE CONTROL REGISTER                      ;CCP1 MODULE IS SIMULTANEOUSLY SWITCHED ON

CCP1 in Compare mode

In this mode, the value in the CCP1 register is constantly compared to the value in the timer register TMR1. When a match occurs, the output pin RC2/CCP1 logic state may be changed, which depends on the state of bits in the control register (CCP1M3 - CCP1M0). The flag-bit CCP1IF will be simultaneously set.
CCP1 in Compare mode
Fig. 5-3 CCP1 in Compare mode
To setup CCP1 module to operate in this mode, two conditions must be met:
  • Pin RC2/CCP1 must be configured as output; and
  • Timer TMR1 must be synchronized with internal clock.

CCP1 in PWM mode

Signals of varying frequency and duty cycle have a wide application in automation. A typical example is a power control circuit whose simple operation is shown in figure 5-4 below. If a logic zero (0) represents switch-off and logic one (1) represents switchon, the power that the load consumes will be directly proportional to the pulse duration. This ratio is often called Duty Cycle.
CCP1 in PWM mode
Fig. 5-4 CCP1 in PWM mode
Another example, common in practice, is the usage of PWM signals in the circuit for generating signals of arbitrary waveforms, for example, sinusoidal waveform. See figure 5-5 below:
CCP1 in PWM mode with filtration
Fig. 5-5 CCP1 in PWM mode with filtration
Devices which operate in this way are often used in practice as switching regulators which control the operation of motors (speed, acceleration, deceleration etc.).
PWM module
Fig. 5-6 PWM module
The figure above shows the block diagram of the CCP1 module setup in PWM mode. In order to generate a pulse of arbitrary form on its output pin, it is necessary to determine only two values- pulse frequency and duration.
PWM Mode
Fig.5-7 PWM Mode

PWM Period

The output pulse period (T) is specified by the PR2 register of the timer TMR2. The PWM period can be calculated using the following equation:
PWM Period(T) = (PR2 +1) * 4Tosc * TMR2 Prescale Value
If the PWM Period (T) is known then, it is easy to determine the signal frequency F because these two values are related by equation F=1/T.

PWM Duty Cycle

The PWM duty cycle is specified by using in total of 10 bits: eight MSbs found in the CCPR1L register and two additional LSbs found in the CCP1CON register (DC1B1 and DC1B0). The result is 10-bit number contained in the formula:
Pulse Width = (CCPR1L,DC1B1,DC1B0) * Tosc * TMR2 Prescale Value
The following table shows how to generate PWM signals of varying frequency if the microcontroller uses 20 MHz quartz-crystal (Tosc=50nS).
Frequency [KHz] 1.22 4.88 19.53 78.12 156.3 208.3
TMR2 Prescaler 16 4 1 1 1 1
PR2 Register FFh FFh FFh 3Fh 1Fh 17h
Table 5-1 PWM Duty Cycle
At last, two notes:
  • Output pin will be constantly set in case the pulse width is by negligence determined to be larger than PWM period; and
  • In this application, the timer TMR2 Postscaler cannot be used for generating longer PWM periods.

PWM Resolution

PWM signal is nothing more than the pulse sequence with varying duty cycle. For one specified frequency (number of pulses per second), there is a limited number of duty cycle combinations. This number is called resolution measured by bits. For example, a 10-bit resolution will result in 1024 discrete duty cycles, whereas an 8-bit resolution will result in 256 discrete duty cycles etc. In relation to this microcontroller, the resolution is specified by the PR2 register. The maximal value is obtained by writing number FFh.
PWM frequencies and resolutions ( Fosc = 20MHz):
PWM Frequency 1.22kHz 4.88kHz 19.53kHz 78.12kHz 156.3kHz 208.3kHz
Timer Prescale 16 4 1 1 1 1
PR2 Value FFh FFh FFh 3Fh 1Fh 17h
Maximum Resolution 10 10 10 8 7 6
Table 5-2 PWM Frequencies and Resolutions
PWM frequencies and resolutions ( Fosc = 8MHz):
PWM Frequency 1.22kHz 4.90kHz 19.61kHz 76.92kHz 153.85kHz 200.0kHz
Timer Prescale 16 4 1 1 1 1
PR2 Value 65h 65h 65h 19h 0Ch 09h
Maximum Resolution 8 8 8 6 5 5
Table 5-3 PWM Frequencies and Resolutions

CCP1CON Register

CCP1CON Register
Fig. 5-8 CCP1CON Register
P1M1, P1M0 - PWM Output Configuration bits - In all modes, excepting PWM, the P1A pin is Capture/Compare module input. P1B, P1C and P1D pins act as input/output port D pins. In PWM mode, these bits affect the CCP1 module as shown in the table 5-4 below:
P1M1 P1M0 Mode
0 0 PWM with single output
Pin P1A outputs modulated signal.
Pins P1B, P1C and P1D are port D input/output
0 1 Full Bridge - Forward configuration
Pin P1D outputs modulated signal
Pin P1A is active
Pins P1B and P1C are inactive
1 0 Half Bridge configuration
Pins P1A and P1B output modulated signal
PinsP1C and P1D are port D input/output
1 1 Full Bridge - Reverse configuration
Pin P1B outputs modulated signal
Pin P1C is active
Pins P1A and P1D are inactive
Table 5-4 CCP1CON Register
DC1B1, DC1B0 - PWM Duty Cycle Least Significant bits - are only used in PWM mode in which they represent two least significant bits of a 10-bit number. This number determines PWM signal’s duty cycle. The rest of bits (8 in total) are stored in the CCPR1L register.
CCP1M3 - CCP1M0 - CCP1 Mode Select bits determine the mode of the CCP1 module.
CCP1M3 CCP1M2 CCP1M1 CCP1M0 Mode
0 0 0 0 Module is disabled (reset)
0 0 0 1 Unused
0 0 1 0 Compare mode
CCP1IF bit is set on match
0 0 1 1 Unused
0 1 0 0 Capture mode
Every falling edge on the CCP1 pin
0 1 0 1 Capture mode
Every rising edge on the CCP1 pin
0 1 1 0 Capture mode
Every 4th rising edge on the CCP1 pin
0 1 1 1 Capture mode
Every 16th rising edge on the CCP1 pin
1 0 0 0 Compare mode
Output and CCP1IF bit are set on match
1 0 0 1 Compare mode
Output is cleared and CCP1IF bit is set on match
1 0 1 0 Compare mode
Interrupt request arrives and bit CCP1IF is set on match
1 0 1 1 Compare mode
Bit CCP1IF is set and timers 1 or 2 registers are cleared
1 1 0 0 PWM mode
Pins P1A and P1C are active-high
Pins P1B and P1D are active-high
1 1 0 1 PWM mode
Pins P1A and P1C are active-high
Pins P1B and P1D are active-low
1 1 1 0 PWM mode
Pins P1A and P1C are active-low
Pins P1B and P1D are active-high
1 1 1 1 PWM mode
Pins P1A and P1C are active-low
Pins P1B and P1D are active-low
Table 5-5 Modes of Operations

CCP2 Module

Excluding the different names of registers and bits, this module is a very good copy of the CCP1 module setup in normal mode (previously discussed). There is only one true difference between their modes when CCP2 operates in Compare mode.
That difference refers to the timer T1 reset signal. Namely, if A/D converter is enabled at the moment the values of the TMR1 and CCPR2 registers match, the timer T1 reset signal will automatically start A/D conversion.
CCP2 Module
Fig. 5-9 CCP2 Module
Similar to the pervious module, this circuit is under control of the bits of the control register. This time, it is the CCP2CON register.

CCP2CON Register

CCP2CON Register
Fig. 5-10 CCP2CON Register
DC2B1, DC2B0 - PWM Duty Cycle Least Significant bits - are only used in PWM mode representing two least significant bits of a 10-bit number. This number determines PWM signal’s duty cycle. The rest of bits (8 in total) are stored in the CCPR2L register.
CCP2M3 - CCP2M0 - CCP2 Mode Select bits select CCP2 mode.
CCP2M3 CCP2M2 CCP2M1 CCP2M0 Mode
0 0 0 0 Module is disabled (reset)
0 0 0 1 Unused
0 0 1 0 Unused
0 0 1 1 Unused
0 1 0 0 Capture mode
Every falling edge on the CCP2 pin
0 1 0 1 Capture mode
Every raising edge on the CCP2 pin
0 1 1 0 Capture mode
Every 4th rising edge on the CCP2 pin
0 1 1 1 Capture mode
Every 16th rising edge on the CCP2 pin
1 0 0 0 Compare mode
Output and CCP2IF bit are set on match
1 0 0 1 Compare mode
Output is cleared and CCP2IF bit is set on match
1 0 1 0 Compare mode
Interrupt is generated, CCP2IF bit is set and CCP2 pin is unaffected on match
1 0 1 1 Compare mode
CCP2IF bit is set, Timer 1 registers are cleared, A/D conversion is started if the A/D converter is on on match
1 1 x x PWM mode
Table 5-6 CCP2CON Register

In short: Setup CCP1 module for PWM operation

In order to setup the CCP module for PWM operation, the following steps should be taken:
  • Disable the CCP1 output pin. It should be configured as input;
  • Set the PWM period by loading the PR2 register;
  • Configure the CCP module for the PWM mode by combining bits of the CCP1CON register;
  • Set the PWM signal’s duty cycle by loading the CCPR1L register and using bits DC1B1 and DC1B0 of the CCP1CON register;
  • Configure and start timer TMR2:
    • Clear the TMR2IF interrupt flag bit of the PIR1 register;
    • Set the timer TMR2 prescale value by loading bits T2CKPS1 and T2CKPS0 of the T2CON register;
    • Start the timer TMR2 by setting the TMR2ON bit of the T2CON register;
  • Enable PWM output pins after one PWM cycle has been finished:
    • Wait for the timer TMR2 overflow (TMR2IF bit of the PIR1register is set); and
    • Configure the appropriate pin as output by clearing bit of the TRIS register.

CCP1 in Enhanced Mode

The enhanced mode is available on CCP1 only. Basically, this module does not differ from the one previously described and enhancement refers to transmission of PWM signal to the output pins. Why is it so important? Because the microcontrollers are more frequently used in control systems for electric motors. These devices are not described here, but if you ever have had a chance to work on development of similar devices, you will recognize elements which, until quite recently, have been used as external ones. Normally, all these elements are now integrated into the microcontroller and can operate in several different modes.

Single Output PWM Mode

This mode is enabled only in the event that the P1M1 and P1M0 bits of the CCP1CON register are cleared. In this case, there is only one PWM signal which can be simultaneously available on a maximum of four different output pins. Besides, the PWM signal may appear in basic or inverted waveform. Signal distribution is determined by the bits of the PSTRCON register, while it's polarity is determined by the CCP1M1 and CCP1M0 bits of the CCP1CON register.
When an inverted output is in use, the pins are low-active and pulses having the same waveform are always generated in pairs: on the P1A and P1C pins and P1B and P1D pins, respectively.
Single Output PWM Mode
Fig. 5-11 Single Output PWM Mode

Half-Bridge Mode

In this mode, the PWM signal is output on the P1A pin, while at the same time the complementary PWM signal is output on the P1B pin. Such pulses activate MOSFET drivers in Half-Bridge mode which enable/disable current flow through device.
Half-Bridge Mode
Fig. 5-12 Half-Bridge Mode
In relation to this circuit, it is very dangerous to switch on both MOSFET drivers simultaneously. The short circuit caused in that moment will be fatal. In order to avoid that, it is necessary to provide a short delay between switching drivers on and off. This delay is marked as "td" in figure 5-13 below. The problem is solved by using the PDC0-PDC6 bits of the PWM1CON register.
Period Diagram
Fig. 5-13 Half Bridge Mode
As shown in figure 5-14, the same mode can be used to activate MOSFET drivers in Full Bridge:
Activate MOSFET drivers
Fig. 5-14 Activate MOSFET drivers

Full-Bridge Mode

In Full-Bridge mode, all four pins are used as outputs. In practice, this mode is commonly used to run motors, which provides simple and complete control of speed and rotation direction. There are two such configurations: Full Bridge-Forward and Full Bridge-Reverse.
Full-Bridge Mode
Fig. 5-15 Full-Bridge Mode

Full Bridge - Forward Configuration

In Forward mode the following occurs:
  • Logic one (1) appears on the P1A pin (pin is high-active);
  • Pulse sequence appears on the P1D pin; and
  • Logic zero (0) appears on the P1B and P1C pins (pins are low-active).
Figure below shows the state of the P1A-P1D pins during one full PWM cycle.
Forward Mode
Fig. 5-16 Forward Mode

Full Bridge - Reverse Configuration

The same occurs in Reverse mode, except of the pins functions:
  • Logic one (1) appears on the P1C pin (pin is active-high);
  • Pulse sequence appears on the P1B pin; and
  • Logic zero (0) appears on the P1A and P1D pins (pins are active-low).
Reverse Mode
Fig. 5-17 Reverse Mode

PWM1CON Register - STRC PWM Restart Enable bit

  • 1 - Upon auto-shutdown, the PWM module is automatically reset, while the ECCPASE bit of the ECCPAS register is cleared.
  • 0 - In order to restart PWM module upon auto-shutdown, the ECCPASE bit must be cleared in software.
PDC6 - PDC0 - PWM Delay Count bits. 7-digit binary number determines the number of instruction cycles (4*Tosc) added as time delay during the activation of PWM output pins.
PWM1CON Register
Fig. 5-18 PWM1CON Register

PSTRCON Register

STRSYNC - Steering Sync bit determines the moment of PWM pulse steering:
  • 1 - Steering occurs upon the PSTRCON has been changed, but only if a PWM waveform is completed; and
  • 0 - Steering occurs upon the PSTRCON register has been changed. The PWM signal on output pin is immediately changed with no regard to whether the previous cycle is completed or not. This operation is useful when it is needed to immediately remove a PWM signal from the pin.
STRD - Steering Enable bit D determines the P1D pin function.
  • 1 - P1D pin has the PWM waveform with polarity controlled by the CCP1M0 and CCP1M1 bits; and
  • 0 - Pin is configured as general Port D input/output.
STRC Steering Enable bit C determines the P1C pin function.
  • 1 - P1C pin has the PWM waveform with polarity controlled by the CCP1M0 and CCP1M1 bits; and
  • 0 - Pin is configured as general port D input/output.
STRB - Steering Enable bit B determines the P1B pin function.
  • 1 - P1B pin has the PWM waveform with polarity controlled by the CCP1M0 and CCP1M1 bits; and
  • 0 - Pin is configured as general port D input/output.
STRA - Steering Enable bit A determines the P1A pin function.
  • 1 - P1D pin has the PWM waveform with polarity controlled by the CCP1M0 and CCP1M1 bits; and
  • 0 - Pin is configured as general port Ainput/output.

ECCPAS Register

ECCPAS Register
Fig. 5-19 ECCPAS Register
ECCPASE - ECCP Auto-Shutdown Event Status bit indicates whether shut-down of CCP module has occurred (Shutdown state):
  • 1 - CCP module is in Shutdown state; and
  • 0 - CCP module operates normally.
ECCPAS2 - ECCPAS0 - ECCP Auto-Shutdown Source Select bits select auto shutdown source:
ECCPAS2 ECCPAS1 ECCPAS0 Shuthown state source
0 0 0 Shutdown state disabled
0 0 1 Comparator C1 output change
0 1 0 Comparator C2 output change
0 1 1 Comparator C1 or C2 output change
1 0 0 Logic zero (0) on INT pin
1 0 1 Logic zero (0) on INT pin or comparator C1 output change
1 1 0 Logic zero (0) on INT pin or comparator C2 output change
1 1 1 Logic zero (0) on INT pin or comparator C1 or C2 output change
Table 5-7 ECCPAS Register
PSSAC1, PSSAC0 - Pins P1A, P1C Shutdown State Control bits define logic state on output pins P1A and P1C when CCP module is in shutdown state.
PSSAC1 PSSAC0 Pins logic state
0 0 0
0 1 1
1 X High impedance (Tri-state)
Table 5-8 A&C Logic States
PSSBD1, PSSBD0 - Pins P1B, P1D Shutdown State Control bits define logic state on output pins P1B and P1D when CCP module is in shutdown state.
PSSBD1 PSSBD0 Pins logic state
0 0 0
0 1 1
1 X High impedance (Tri-state)
Table 5-9 B&D Logic States

Tuesday, February 07, 2006

Chapter 4: Timers

Chapter 4: Timers

The timers of the PIC16F887 microcontroller can be briefly described in only one sentence. There are three completely independent timers/counters marked as TMR0, TMR1 and TMR2. But it’s not as simple as that.

Timer TMR0

The timer TMR0 has a wide range of applications in practice. Very few programs don't use it in some way. It is very convenient and easy to use for writing programs or subroutines for generating pulses of arbitrary duration, time measurement or counting external pulses (events) with almost no limitations.
The timer TMR0 module is an 8-bit timer/counter with the following features:
  • 8-bit timer/counter;
  • 8-bit prescaler (shared with Watchdog timer);
  • Programmable internal or external clock source;
  • Interrupt on overflow; and
  • Programmable external clock edge selection.
Figure 4-1 below represents the timer TMR0 schematic with all bits which determine its operation. These bits are stored in the OPTION_REG Register.
Timer TMR0
Fig. 4-1 Timer TMR0

OPTION_REG Register

OPTION_REG Register
Fig. 4-2 OPTION_REG Register
  • RBPU - PORTB Pull-up enable bit
    • 1 - PORTB pull-up resistors are disabled; and
    • 0 - PORTB pins can be connected to pull-up resistors.
  • INTEDG - Interrupt Edge Select bit
    • 1 - Interrupt on rising edge of INT pin (0-1); and
    • 0 - Interrupt on falling edge of INT pin (1-0).
  • T0CS - TMR0 Clock Select bit
    • 1 - Pulses are brought to TMR0 timer/counter input through the RA4 pin; and
    • 0 - Internal cycle clock (Fosc/4).
  • T0SE - TMR0 Source Edge Select bit
    • 1 - Increment on high-to-low transition on TMR0 pin; and
    • 0 - Increment on low-to-high transition on TMR0 pin.
  • PSA - Prescaler Assignment bit
    • 1 - Prescaler is assigned to the WDT; and
    • 0 - Prescaler is assigned to the TMR0 timer/counter.
  • PS2, PS1, PS0 - Prescaler Rate Select bit
    • Prescaler rate is adjusted by combining these bits
      As seen in the table 4-1, the same combination of bits gives different prescaler rate for
      the timer/counter and watch-dog timer respectively.
PS2 PS1 PS0 TMR0 WDT
0 0 0 1:2 1:1
0 0 1 1:4 1:2
0 1 0 1:8 1:4
0 1 1 1:16 1:8
1 0 0 1:32 1:16
1 0 1 1:64 1:32
1 1 0 1:128 1:64
1 1 1 1:256 1:128
Table 4-1 Prescaler Rate
The function of the PSA bit is shown in the two figures below:
The function of the PSA bit 0
Fig. 4-3 The function of the PSA bit 0
The function of the PSA bit 1
Fig. 4-4 The function of the PSA bit 1
As seen, the logic state of the PSA bit determines whether the prescaler is to be assigned to the timer/counter or watch-dog timer.
Additionally it is also worth mentioning:
  • When the prescaler is assigned to the timer/counter, any write to the TMR0 register will clear the prescaler;
  • When the prescaler is assigned to watch-dog timer, a CLRWDT instruction will clear both the prescaler and WDT;
  • Writing to the TMR0 register used as a timer, will not cause the pulse counting to start immediately, but with two instruction cycles delay. Accordingly, it is necessary to adjust the value written to the TMR0 register;
  • When the microcontroller is setup in sleep mode, the oscillator is turned off. Overflow cannot occur since there are no pulses to count. This is why the TMR0 overflow interrupt cannot wake up the processor from Sleep mode;
  • When used as an external clock counter without prescaler, a minimal pulse length or a pause between two pulses must be 2 Tosc + 20 nS. Tosc is the oscillator signal period;
  • When used as an external clock counter with prescaler, a minimal pulse length or a pause between two pulses is 10nS;
  • The 8-bit prescaler register is not available to the user, which means that it cannot be directly read or written to;
  • When changing the prescaler assignment from TMR0 to the watch-dog timer, the following instruction sequence must be executed in order to avoid reset:
BANKSEL TMR0 CLRWDT                 ;CLEAR WDT CLRF    TMR0           ;CLEAR TMR0 AND PRESCALER BANKSEL OPTION_REG BSF     OPTION_REG,PSA ;PRESCALER IS ASSIGNED TO THE WDT CLRWDT                 ;CLEAR WDT MOVLW   b’11111000’    ;SELECT BITS PS2,PS1,PS0 AND CLEAR ANDWF   OPTION_REG,W   ;THEM BY INSTRUCTION “LOGICAL AND” IORLW   b’00000101’    ;BITS PS2, PS1, AND PS0 SET MOVWF   OPTION_REG     ;PRESCALER RATE TO 1:32
  • Likewise, when changing the prescaler assignment from the WDT to the TMR0, the following instruction sequence must be executed:
BANKSEL TMR0 CLRWDT                 ;CLEAR WDT AND PRESCALER BANKSEL OPTION_REG MOVLW   b’11110000’    ;SELECT ONLY BITS PSA,PS2,PS1,PS0 ANDWF   OPTION_REG,W   ;CLEAR THEM AFTERWARDS BY INSTRUCTION                        ;“LOGICAL AND” IORLW   b’00000011’    ;PRESCALER RATE IS 1:16 MOVWF   OPTION_REG
In order to use TMR0 properly, it is necessary:
To select mode:
  • Timer mode is selected by the T0CS bit of the OPTION_REG register, (T0CS: 0=timer, 1=counter);
  • When used, the prescaler should be assigned to the timer/counter by clearing the PSA bit of the OPTION_REG register. The prescaler rate is set by using the PS2-PS0 bits of the same register; and
  • When using interrupt, the GIE and TMR0IE bits of the INTCON register should be set.
To measure time:
  • Reset the TMR0 register or write some well-known value to it;
  • Elapsed time (in microseconds when using quartz 4MHz) is measured by reading the TMR0 register; and
  • The flag bit TMR0IF of the INTCON register is automatically set every time the TMR0 register overflows. If enabled, an interrupt occurs.
To count pulses:
  • The polarity of pulses are to be counted is selected on the RA4 pin are selected by the TOSE bit of the OPTION register (T0SE: 0=positive, 1=negative pulses); and
  • Number of pulses may be read from the TMR0 register. The prescaler and interrupt are used in the same manner as in timer mode.

Timer TMR1

Timer TMR1 module is a 16-bit timer/counter, which means that it consists of two registers (TMR1L and TMR1H). It can count up 65.535 pulses in a single cycle, i.e. before the counting starts from zero.
Timer TMR1
Fig. 4-5 Timer TMR1
Similar to the timer TMR0, these registers can be read or written to at any moment. In case an overflow occurs, an interrupt is generated.
The timer TMR1 module may operate in one of two basic modes- as a timer or a counter. However, unlike the timer TMR0, each of these modules has additional functions.
Parts of the T1CON register are in control of the operation of the timer TMR1.
Timer TMR1 Overview
Fig. 4-6 Timer TMR1 Overview

Timer TMR1 Prescaler

Timer TMR1 has a completely separate prescaler which allows 1, 2, 4 or 8 divisions of the clock input. The prescaler is not directly readable or writable. However, the prescaler counter is automatically cleared upon write to the TMR1H or TMR1L register.

Timer TMR1 Oscillator

RC0/T1OSO and RC1/T1OSI pins are used to register pulses coming from peripheral electronics, but they also have an additional function. As seen in figure 4-7, they are simultaneously configured as both input (pin RC1) and output (pin RC0) of the additional LP quartz oscillator (low power).
This additional circuit is primarily designed for operating at low frequencies (up to 200 KHz), more precisely, for using the 32,768 KHz quartz crystal. Such crystals are used in quartz watches because it is easy to obtain one-second-long pulses by simply dividing this frequency.
Since this oscillator does not depend on internal clocking, it can operate even in sleep mode. It is enabled by setting the T1OSCEN control bit of the T1CON register. The user must provide a software time delay (a few milliseconds) to ensure proper oscillator start-up.
Timer TMR1 Oscillator
Table below shows the recommended values of capacitors to suit the quartz oscillator. These values do not have to be exact. However, the general rule is: the higher the capacitor's capacity the higher the stability, which, at the same time, prolongs the time needed for the oscillator stability.
Oscillator Frequency C1 C2
LP
32 kHz 33 pF 33 pF
100 kHz 15 pF 15 pF
200 kHz 15 pF 15 pF
Fig. 4-7 Timer TMR1 Oscillator

Timer TMR1 Gate

Timer 1 gate source is software configurable to be the T1G pin or the output of comparator C2. This gate allows the timer to directly time external events using the logic state on the T1G pin or analog events using the comparator C2 output. Refer to figure 4-7 above. In order to time a signals duration it is sufficient to enable such gate and count pulses having passed through it.

TMR1 in timer mode

In order to select this mode, it is necessary to clear the TMR1CS bit. After this, the 16-bit register will be incremented on every pulse coming from the internal oscillator. If the 4MHz quartz crystal is in use, it will be incremented every microsecond.
In this mode, the T1SYNC bit does not affect the timer because it counts internal clock pulses. Since the whole electronics uses these pulses, there is no need for synchronization.
TMR1 in timer mode
Fig. 4-8 TMR1 in timer mode
The microcontroller’s clock oscillator does not run during sleep mode so the timer register overflow cannot cause any interrupt.

Timer TMR1 Oscillator

The power consumption of the microcontroller is reduced to the lowest level in Sleep mode. The point is to stop the oscillator. Anyway, it is easy to set the timer in this mode- by writing a SLEEP instruction to the program. A problem occurs when it is necessary to wake up the microcontroller because only an interrupt can do that. Since the microcontroller “sleeps”, an interrupt must be triggered by external electronics. It can all get incredibly complicated if it is necessary the ‘wake up’ occurs at regular time intervals...
Timer TMR1 Oscillator
Fig. 4-9 Timer TMR1 Oscillator
In order to solve this problem, a completely independent Low Power quartz oscillator, able to operate in sleep mode, is built into the PIC16F887 microcontroller. Simply, what previously has been a separate circuit, it is now built into the microcontroller and assigned to the timer TMR1. The oscillator is enabled by setting the T1OSCEN bit of the T1CON register. After that, the TMR1CS bit of the same register then is used to determine that the timer TMR1 uses pulse sequences from that oscillator.
  • The signal from this quartz oscillator is synchronized with the microcontroller clock by clearing the T1SYNC bit. In that case, the timer cannot operate in sleep mode. You wonder why? Because the circuit for synchronization uses the clock of microcontroller!; and
  • The TMR1 register overflow interrupt may be enabled. Such interrupts will occur in sleep mode as well.

TMR1 in counter mode

Timer TMR1 starts to operate as a counter by setting the TMR1CS bit. It means that the timer TMR1 is incremented on the rising edge of the external clock input T1CKI. If control bit T1SYNC of the T1CON register is cleared, the external clock inputs will be synchronized on their way to the TMR1 register. In other words, the timer TMR1 is synchronized to the microcontroller system clock and called a synchronous counter.
When the microcontroller ,operating in this way, is set in sleep mode, the TMR1H and TMR1L timer registers are not incremented even though clock pulses appear on the input pins. Simply, since the microcontroller system clock does not run in this mode, there are no clock inputs to use for synchronization. However, the prescaler will continue to run if there are clock pulses on the pins since it is just a simple frequency divider.
Counter Mode
Fig. 4-11 Counter Mode
Counter Pulses
This counter registers a logic one (1) on input pins. It is important to understand that at least one falling edge must be registered prior to the first increment on rising edge. Refer to figure on the left. The arrows in figure 4-11 denote counter increments.

T1CON Register

T1CON Register
Fig. 4-12 T1CON Register
T1GINV - Timer1 Gate Invert bit acts as logic state inverter on the T1G pin gate or the comparator C2 output (C2OUT) gate. It enables the timer to mea sure time whilst the gate is high or low.
  • 1 - Timer 1 counts when the pin T1G or bit C2OUT gate is high (1); and
  • 0 - Timer 1 counts when the pin T1G or bit C2OUT gate is low (0).
TMR1GE - Timer1 Gate Enable bit determines whether the pin T1G or comparator C2 output (C2OUT) gate will be active or not. This bit is functional only in the event that the timer TMR1 is on (bit TMR1ON = 1). Otherwise, this bit is ignored.
  • 1 Timer TMR1 is on only if timer 1 gate is not active; and
  • 0 Gate does not affect the timer TMR1.
T1CKPS1, T1CKPS0 - Timer1 Input Clock Prescale Select bits determine the rate of the prescaler assigned to the timer TMR1.
T1CKPS1 T1CKPS0 Prescaler Rate
0 0 1:1
0 1 1:2
1 0 1:4
1 1 1:8
Table 4-2 Prescaler Rate
T1OSCEN - LP Oscillator Enable Control bit
  • 1 - LP oscillator is enabled for timer TMR1 clock (oscillator with low power consumption and frequency 32.768 kHz); and
  • 0 - LP oscillator is off.
T1SYNC - Timer1 External Clock Input Synchronization Control bit enables synchronization of the LP oscillator input or T1CKI pin input with the microcontroller internal clock. When counting pulses from the local clock source (bit TMR1CS = 0), this bit is ignored.
  • 1 - Do not synchronize external clock input; and
  • 0 - Synchronize external clock input.
TMR1CS - Timer TMR1 Clock Source Select bit
  • 1 - Counts pulses on the T1CKI pin (on the rising edge 0-1); and
  • 0 - Counts pulses of the internal clock of microcontroller.
TMR1ON - Timer1 On bit
  • 1 - Enables Timer TMR1; and
  • 0 - Stops Timer TMR1.
In order to use the timer TMR1 properly, it is necessary to perform the following:
  • Since it is not possible to turn off the prescaler, its rate should be adjusted by using bits T1CKPS1 and T1CKPS0 of the register T1CON (Refer to table 4-2);
  • The mode should be selected by the TMR1CS bit of the same register (TMR1CS: 0= the clock source is quartz oscillator, 1= the clock source is supplied externally);
  • By setting the T1OSCEN bit of the same register, the timer TMR1 is turned on and the TMR1H and TMR1L registers are incremented on every clock input. Counting stops by clearing this bit;
  • The prescaler is cleared by clearing or writing the counter registers; and
  • By filling both timer registers, the flag TMR1IF is set and counting starts from zero.

Timer TMR2

Timer TMR2 module is an 8-bit timer which operates in a very specific way.
Timer TMR2
Fig. 4-13 Timer TMR2
The pulses from the quartz oscillator first pass through the prescaler whose rate may be changed by combining the T2CKPS1 and T2CKPS0 bits. The output of the prescaler is then used to increment the TMR2 register starting from 00h. The values of TMR2 and PR2 are constantly compared and the TMR2 register keeps on being incremented until it matches the value in PR2. When a match occurs, the TMR2 register is automatically cleared to 00h. The timer TMR2 Postscaler is incremented and its output is used to generate an interrupt if it is enabled.
The TMR2 and PR2 registers are both fully readable and writable. Counting may be stopped by clearing the TMR2ON bit, which contributes to power saving.
As a special option, the moment of TMR2 reset may be also used to determine synchronous serial communication baud rate.
The timer TMR2 is controlled by several bits of the T2CON register.

T2CON Register

T2CON Register
Fig. 4-14 T2CON Register
TOUTPS3 - TOUTPS0 - Timer2 Output Postcaler Select bits are used to determine the postscaler rate according to the following table:
TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 Postscaler Rate
0 0 0 0 1:1
0 0 0 1 1:2
0 0 1 0 1:3
0 0 1 1 1:4
0 1 0 0 1:5
0 1 0 1 1:6
0 1 1 0 1:7
0 1 1 1 1:8
1 0 0 0 1:9
1 0 0 1 1:10
1 0 1 0 1:11
1 0 1 1 1:12
1 1 0 0 1:13
1 1 0 1 1:14
1 1 1 0 1:15
1 1 1 1 1:16
Table 4-3 Postscaler Rate
TMR2ON - Timer2 On bit turns the timer TMR2 on.
  • 1 - Timer T2 is on; and
  • 0 - Timer T2 is off.
T2CKPS1, T2CKPS0 - Timer2 Clock Prescale bits determine prescaler rate:
T2CKPS1 T2CKPS0 Prescaler Rate
0 0 1:1
0 1 1:4
1 x 1:16
Table 4-4 Prescaler Rate
When using the TMR2 timer, one should know several specific details that have to do with its registers:
  • Upon power-on, the PR2 register contains the value FFh;
  • Both prescaler and postscaler are cleared by writing to the TMR2 register;
  • Both prescaler and postscaler are cleared by writing to the T2CON register; and
  • On any reset, both prescaler and postscaler are cleared.