UART / USART in PIC Microcontroller
UART = Universal Asynchronous Receiver/Transmitter
It is commonly referred as serial port
It is a peripheral for point-to-point communication between two devices as shown in Fig
5.5.1
Fig 5.5.1 Point-to-point communication between two devices
Communication occurs in serial, i.e. one bit at time
Two communication PINs: RX and TX
When no transmission, the line is set to Logical “1”
Then the software triggers the transmission of a byte (e.g. “C”, hexa code 43, binary 0100
0011)
First a Logical “0” is transmitted, called start bit
Then the byte is transmitted LSB first
One or two stop bits (Logical “1”) ends the transmission as shown in Fig 5.5.2
Fig 5.5.2 Transmission of a byte
PIC’s hardware USART, we need three registers: TXSTA, RCSTA and SPBRG. The
SPBRG is used to calculate the baud rate of the transmissions.
The TXSTA and RCSTA registers are shown below:
Fig 5.5.3 TXSTA register
Fig 5.5.4 RCSTA register
Bit TXEN (bit 5) on TXSTA enables or disables transmission, SYNC ( bit 4) sets asynchronous
or synchronous mode while BRGH (bit 2) sets high speed or low speed mode.
The formula used to compute for the baud rate is different in high speed or low speed mode:
Table 5.5.1 Baud rate calculation
Here, X is the contents of the register SPBRG. So, for example, a baud rate of 9600 using
a 4 MHz oscillator at high speed and asynchronous mode will have SPBRG = 25 as
shown:
TRMT (bit 1) is a flag that sets if the data has been sent.
SPEN (bit 7) of the RCSTA register enables RC6 and RC7 as serial port pins. This is the
bit you need to set to enable serial communication.
The data to be transmitted must be placed inside the TXREG register while the data
received is placed inside the RCREG register.
Example program for UART in PIC Microcontroller