09.1 UART – Part 1 – Setup
9.1 UART – Part 1
As many of you may know (or may not know, depending on whether you are an über nerd), UART stands for Universal Asynchronous Receiver Transmitter. It is a way to transmit data from one device to another. The 9 pin serial port that are still standard on most computers is an example of a UART. The serial port on your computer uses a standard known as RS-232, which is a special UART that sends out its messages at specific voltages, and not at TTL levels.

In case you don’t have a background on transmission theory, I’ll touch on some aspects of the UART below. If you do know a thing or two, well you can just skip to the programming. But just keep in mind that reading the section below might help in understanding the programming section.
Asynchronous Transmission
The reason this type of communications is called asynchronous is because a clock signal is NOT required. This may be a little weird when you think about it. For example, how will both parties know when to sample the data? How will the timing be established? How does the transmitter establish the moment to send the next bit and etc.? It is actually quite simple how they managed to engineer the solution to these problems: both the transmitter and the receiver agree to the communication speed, or baud rate, ahead of time. However, this is also where most of the headache comes from when dealing with microcontrollers. Whenever absolute time is involved, headache ensues.
Definitions
A transmitter is the party sending the message (duh…). A receiver is the party receiving the message. It sounds stupid right now, but when you have a computer and a microcontroller both sending and receiving, it gets confusing, trust me.
The baud rate is the number of bits that can be sent in one second. This is NOT the same as the amount of data that can be sent. Due to overhead data such as transmission start/stop bits, and parity bits, the data rate is always less than the maximum transmission rate. Most of the time, you need to send 11 bits to be able to receiver one byte of data.
The parity bit is a bit used to check the integrity of the data. Usually it counts the number of ones (or zeros it’s the same thing), and indicates whether the number is even or odd. This ensures that if there is an error in ONE bit, the receiver will be able to detect it. However if two errors exist, then you’re screwed. Of course the probability of having two errors is exponentially high (Ptotal = P1error^2). The parity bit is strictly optional. I usually don’t bother with it.
Details, Details
I won’t get into bit banging action of the UART transmission since that is well documented. However, I will say that the UART on the PIC24 is implemented on TTL levels, and NOT on RS-232 levels. To talk to a computer, you will need to use a transmission level changed such as the MAX200 series from Maxim Integrated Products. Personally I like to use the MAX208. It’s got 4 full duplex lines on there, but I usually use only one. However for mobile applications it tends to hog quite a bit of power.
Overall, the system works like this (one way transmission): A wire connects from the transmission output pin of the transmitter to the reception input pin of the receiver. The ground must also be equalized, so another wire must connect the GND levels of each device. Once the wires are established and the baud rate is determined on BOTH parties, the transmission can begin.
The transmission looks like the following:

Each section of the grid represents one time unit equal to the inverse of the baud rate. For example, if we were at 2400 bps, then each section of the grid in the above picture represents 1sec/2400 = 416.7 usec. I will designate this time unit as one baud period (baud period = 1/baud rate).
The transmission line is always pulled up to the TTL high level when not in use. When a transmission begins, the transmitter must first pull the line down to a zero, for one baud period. Then it sends the data, with the least significant bit (lsb) of the byte first. Next the transmitter sends the parity, and lastly, pulls the line back to a high, the stop bit, to indicate that the transmission has ended. Another transmission cannot begin until at least the end of the stop bit. Depending on the type of transmission agreed up, the stop bit can be one, or several baud units long. Most of the time, I want my transmissions as fast as possible, so usually set one stop bit.
Since both the transmitter and the receiver know the speed the transmission is going take place, the best possible time to sample the data is at half baud unit intervals.

Obviously if the there is a timing difference between the two parties, there’s going to be some problems with the transmission. If the sampling of the data coming in is will not be timed correctly and the data received will be incorrect. It is imperative that the timing on both ends is calculated precisely so that the sampling of the incoming data is timed at exactly in the middle of the bit transitions.
UART on the PIC24
So how much of this stuff we have to take into account when implementing it into a PIC? Not much at all. There are UART modules on the PIC24 that takes care of the timing and translations for you. All you need to know is how to program them.
On the PIC24F series of controllers, there are usually 2 modules, aptly named UART1 and UART2. On the H series, most of them have only one module. There are no major bugs with the UART, but there are some issues with advanced features. These bugs are documented in the Silicon Errata in the documentations page of each of the PIC processors. You can access them through Microchip’s website.
The modules are controlled by several registers. They are the UxBRG, the UxMODE, and the UxSTA. The UxBRG is a register that contains a clock divisor, which is used to establish the baud rate of the incoming and outgoing message. The UxMODE is the main control register for the module. This register controls turning the module on and off. Lastly UxSTA is the status register, which you can probe for current conditions of the module.
The last thing you really need to know is that there is a data buffer for both transmission and reception. For the transmission buffer, you can load up for 4 bytes of data, and the module will send them, one at a time, when possible, with the correct timing. On the receiving end, the buffer is always 4 bytes in size, so you’ll have to start emptying your buffer before the 5th byte is loaded or you’ll start losing received data.
Timing
The hardest part is establishing the timing. If you need a refresher on oscillators and timers, check out the sections in the tutorial. You will need to figure out your instruction clock frequency (Fcy) before proceeding. Once you figure out your Fcy, you need to update a register called to the UxBRG register, which determines the baud rate of your UART module. In addition to calculating the UxBRG value, there is an additional setting that allows for the UART to be set in high speed mode, or standard speed mode. There is usually no need for the high speed mode in most applications, so I will not touch on the subject in this tutorial. The speed mode is determined by the BRGH bit, located in the UxMODE register. Since I almost always use standard speed, it is usually set to zero.
According to the datasheet, the UxBRG value is calculated using the following equation, with BRGH = 0 (standard speed).

As an example, let’s say I have an input CLKI running at 10MHz, with no PPL, and no peripheral clock divide CLKDIV = 0×0000. I want to communicate with another device at 19200 bps. Then:
Fcy = Focs/2 = 5 MHz.
BRGx = 5*10^6/(16*19200) – 1 = 15.276
Since the register UxBRG only takes integers, we’ll have to settle for 15. It doesn’t really matter though. The value of 15 only means that we’ll be off by a little bit with our timing, but not enough to consistently get an error.
Turning it on and other Configurations
Once we have established the baud rate, next we look at how to turn the UART module on.

It is quite simple, just set that bit to one. All the other settings are rarely used, so leave them all at zero for now. Do look them over just once however, since these settings are sometimes application specific. For most of my applications, I have not had to use them.
I will not include a copy of the UxSTA register description in the tutorial since you’ll have to read it anyways. But I will go over some of the settings. The UxSTA.UTXISEL<1:0> bits control how an interrupt is handled during transmission. In most cases, I set the value to 0b10. I want my interrupts to tell me that the transmission is completed, and that my buffer is empty. I usually like to transmit one byte at a time. Next I want to control how the PIC will notify me, when a byte has been received. This is controlled by the UxSTA.URXISEL<1:0> bits. I usually process a value as soon as it is received so I leave bits set to 0b00: interrupt when ANY character is received. The only other setting I have to worry about is the UxSTA.TXEN bit, which turns the transmission on and off.
During transmissions and receptions, there are some other registers I need to be aware of. I need to know how many slots are left in my transmission buffer, and wait for an empty spot before sending my next byte. This is indicated by the UxSTA.UTXBF bit. I also need to know how many values I have received in my reception buffer so that I empty them out to allow for subsequent transmissions. This is indicated by my UART receive interrupt. Since I have set the value UxSTA.URXISEL<1:0> to interrupt every time a byte is received, my UART receive interrupt FLAG, IFS0.U1RXIF, will be a 1 when I receive a byte. You can find out which interrupt flags correspond to which function on the interrupt table, located in the interrupt controller section of the datasheet. Also if you need to know what interrupts do, please go to the interrupt section of the tutorial.

Programming
Now you are ready to do some programming. I usually put all my UART functions in a separate file so that I can reuse them for multiple projects. They are separated into the header file “uart1.h”, and the main UART file, “uart1.c”. The header file only contains the prototypes for the functions.
This is what they look like:
“uart1.h”
/*
Engscope
UART
April 16, 2008
Author: JL
*/
//prototypes
//Initiation
extern void UART1Init(int BAUDRATEREG1);
//UART transmit function
extern void UART1PutChar(char Ch);
//UART receive function
extern char UART1GetChar();
“uart1.c”
/*
Engscope
UART
April 16, 2008
Author: JL
*/
#include “system.h” //see tutorial below!
#include “uart1.h”
//Initiation function, parameter BAUDRATEREG1 determines baud speed
void UART1Init(int BAUDRATEREG1)
{
//Set up registers
U1BRG = BAUDRATEREG1; //set baud speed
U1MODE = 0x8000; //turn on module
U1STA = 0x8400; //set interrupts
//reset RX interrupt flag
IFS0bits.U1RXIF = 0;
}
//UART transmit function, parameter Ch is the character to send
void UART1PutChar(char Ch)
{
//transmit ONLY if TX buffer is empty
while(U1STAbits.UTXBF == 1);
U1TXREG = Ch;
}
//UART receive function, returns the value received.
char UART1GetChar()
{
char Temp;
//wait for buffer to fill up, wait for interrupt
while(IFS0bits.U1RXIF == 0);
Temp = U1RXREG;
//reset interrupt
IFS0bits.U1RXIF = 0;
//return my received byte
return Temp;
}
The program is pretty self explanatory, so I won’t go into detail in explaining them. I think I comment enough so that most monkeys can put the pieces together. However, I do want to explain the “include” directive. First and foremost, you’ll need to include the uart header file. However the curious line:
#include "system.h" //see tutorial below!
needs some explanation. As I have mentioned before, I use these files on different projects, and on different types of PICs. HOWEVER, each PIC needs to have its own specific definition file. For example, if I want to use my UART file with a PIC24FJ64GA002, I will need to write the line:
#include "p24FJ64GA002.h"
However, if on another project, I want to use the PIC24HJ12GP202, I will need to delete the previous line, and add the line:
#include "p24HJ12GP201.h"
This is because you cannot have multiple definitions. I want to add an #include directive once, and ONLY once, but I have to select the correct file according to the PIC processor that I am currently using. For this purpose, I use the “#if defined” directive to figure out which processor I am currently using. The system.h file does just this. I use the “#if defined” directive to figure out which processor I have set up in my MPLAB IDE, and include the definition files accordingly. This is what my system.h file looks like:
/*
Engscope
Author: JL
July 16, 2007
System file, include all headers
*/
#if defined(__PIC24FJ64GA002__)
#include "p24FJ64GA002.h"
#include "pic_i2c.h"
#include "LCD.h"
#elif defined(__PIC24FJ32GA002__)
#include "p24FJ32GA002.h"
#include "pic_i2c.h"
#include "LCD.h"
#elif defined(__PIC24HJ32GP204__)
#include "p24HJ32GP204.h"
#include "pic24H_i2c.h"
#include "LCDLite.h"
#include "encoder.h"
#elif defined(__dsPIC30F3012__)
#include "p30f3012.h"
#endif
#include "accel.h"
#include "adc.h"
#include "uart1.h"
I have shortened the file quite a bit, because it is only here to demonstrate the procedure. In this manner, I never have to change my include directives since I have a case statement that automatically includes the correct file.
Part 2 will deal with how to actually use these files.
Table of Contents
Previous – Timers
Next – UART – Part 2 – Usage

Entries (RSS)
Hi! Your tutorials looks like some of the best in the web!!
I have a question:
I’m using a PIC24HJ256GP206, with all the SPI module used. I need also 1 USART module, for 1 FTDI2232D ic. As I see from datasheets, my PIC has the same pin for SPI1 module and UART1 module (pin 34 is SDI1\U1RX\RF2, and pin 35 is SDO1\U1TX\RF3), so I would like to know if I can use both UART2 and SPI1 module…
Thank You for your help!
Simone
They are shared pins, so you’d have to open and close the modules if you want to use them both. Of course, you’ll also need a transmission switch that switches between the traces (since they are from the same physical pin). This can easily be done with a multiplexer since UART and SPI signals are uni-directional. It is possible, but they are some limitations to its use. Since SPI has a Slave Select signal, this signal can be used to detect when to turn on the SPI modules and when to turn off the UART module. In this manner, you will be able to use both modules, with shared pins, but only one at a time (ie, both modules can run during the course of the program execution, but only one module is used at a time).
-J
Thank you for the reply…
I saw how can I use the USART1 module and SPI1…but I think it is more complicated than to use the USART2 module.
I have some problems doing that, and I don’t know if I can use the UART2 module, without enabling the UART1 module. In this way I think I could use Both SPI1, SPI2 and the UART2 module…without enable/disable problems, but can my PIC use UART2 and NOT UART1?
Thanks
hello…
ur PIC24 Tutorials are awesome…
i’m very new with pic24(started using PIC24 on 20th sep.’09).
ur tutorials are helping me….
I’m having Exp.16 board which has PIC24FJ128GA010.
so wht changes should i ve to do in system.h to use in my project.
rgd,
ambarish
I think you need a fundamental understanding of the C language, not so much what to do with Microchip’s set of of microcontrollers. You’ll probably need to read up on compiler directives and usages.
Good luck,
-J
Hi,
Your tutorials are really helpful. Thank you very much.
I am working with the PIC24FJ128GA010 microcontroller with the Explorer 16 development board. I wanted to use the UART2 in the microcontroller to communicate with my PC through RS232. I have tried out codes to achieve the same.
My problem : The communication seems to be faulty when there is a slight percentage error in the baud rate calculation (BRGx). Even an error such as 0.16 % is totally failing the communication. Could you kindly tell me what might be the cause of the problem in my case.
The above problem occured when I made use of hardware flow control. When I removed it, the error is seen to be tolerated.
I would think it is not the BRGx that is causing the problem, and something like the flow control. UART requires the error to be < T/(11*2) for communications with parity and < T/(10*2) for communications without parity. You can usually easily get away with 2 percent and not be a problem.
Whenever there is a problem, you should always conosult the programmer’s guide. They usually have some more hints than the datasheets. In addition, the status registers for the UART controls will probably have a conflict somewhere. Be wary of those registers.
Good luck.
Hi.
I are using a PIC 24FJ256GB10 and have a small problem in that if the UART1 RX pin is held low (by an external device) while the PIC is powered up, the PIC appears not to come out of reset. It seems to be in some weird mode. The USB side doesn’t work under these conditions either.
Is there some feature that I haven’t read about?
You’ll need to be a bit more specific. When you said “is powered up”, do you mean “while powering up” or “while powered up”? If you meant while powered up, my guess is that the configuration of the microcontroller is wrong (wrong oscillator, POR, watchdog etc..). However, if I assume that what you mean is that the symptoms appear only during power up, then I think it’s probably something to do with your code or the watchdog timer is kicking in. Also, you need to include more details. Is the UART1 RX pins activated (ie, is the UART module turned on/off when this happens?). Are your other functions working? Is the error consistently reproducible, or is it intermittent? These are all clues as to what the problem might be.
When I experience strange behavior, I try to turn off all the advanced features one at a time (or turn them all off, then turn them back on one at a time) and see if behavior comes back. This way I can figure out which of the features might be the culprit. In your case however, there might be many factors. For example, an interrupt routing might not be exiting correctly (from a corrupted mutex operation perhaps?), or something along those lines. Lastly I don’t see a PIC24FJ256GB10 on MC’s website.
-J
Hi
I am using Pic24f16ka102.
And I tried to impement the UArt as you have explained, but my Tx function works fine and whatever I send in the U1Txreg it gets on the pin and I can see it on the oscilloscope.But my Rx is not working I can see the data going on the Rx pin but
my code does not come out of the while loop.
Please let me know if I am missing on something.
What does it say on the UxSTA register? Also, you can try implementing it using interrupts. Actually that is one way you can verify if everything is working. When a byte is received in the UART receive buffer, if your interrupts are set up properly, it will execute your ISR. If it exits the ISR properly, then everything is working, my code is probably to blame. However, if you are not tripping an interrupt, something is definitely wrong in your circuit. Tell me how it goes.
-J
hai i am new to pic24 , your tutorial is very helpful i have a question……, shouldnt we enable IES0bits.U1RXIE it to 1 to enable interrupt flag, it is done for timers……, sorry if i am wrong i am new to microcontroller programming
its IEC0:U1RXIE, sorry for the spelling mistake,…
This is optional. You have the option of handling your events in an interrupt if it is high priority, or in your main loop if it is low priority. It is up to you to decide how to handle the events that are sense by your microcontroller. Typically if your application only has one or two specific task, you can probably just put your event handling in the main loop. When the applications get complicated, you’ll need an interrupt to “queue” the event, then handle it when processing power is available (IE you still would not handle the full event in the interrupt because you want to keep your interrupt short and simple, which will make your system more responsive).
-J