How do I set the serial port baud rate?
Submitted By: Craig Steiner FAQ Last Modified: 07/09/06
- The baud rate of the serial port is normally based on the overflow rate of a timer (usually timer 1 or timer 2). Normally, timer 1 is set to timer mode 2 (8-bit auto-reload) with MOV TMOD,#20h. The baud rate is determined by placing a value in TH1 which is the reload value. TL1 counts up and when it overflows, it is reset to the value in TH1. The baud rate is calculated based on the frequency at which TL1 overflows. More precisely:
Baud Rate = Timer Overflow Rate / 32
Thus if the timer overflows 307,200 times per second, a baud rate of 9600 will result since 307,200/32 = 9600.
The trick is calculating the value TH1 that will generate the proper overflow rate. A standard 8052 at 11.0592MHZ will cause the timer to be clocked at 921.6Khz (11,059,200 / 12 oscillator cycles per clock cycle = 921,600). If the timer is being clocked at 921,600/second and we need an overflow rate of 307,200/second, we simply divide the 921,600 by 307,200 and get a result of 3. This means timer 1 must overflow every 3 clock cycles. Thus we set TH1 to -3.
NOTE: -3 is really FDh. Thus TH1 and TL1 should be initialized to -3 (FDh). TL1 will then count up FEh, FFh, and the third cycle occurs as TL1 overflows from FFh back to the reload value of FDh.
The formula for calculating the baud rate (above) can be rearranged to calculate the correct value for TH1 in a "plug-and-play" manner:
TH1 = Oscillator speed / Clocks per Oscillator Cycle / 32 / Desired Baud Rate
In our example above, the oscillator speed was 11,059,200. Each clock cycle is made up of 12 oscillator cycles and our desired baud rate was 9600. Thus:
TH1 = 11059200 / 12 / 32 / 9600 = 3 --or-- Baud Rate1 = Oscillator speed / Clocks per Oscillator Cycle / 32 / TH1
Also keep in mind that you can set the SMOD bit (PCON.7) to double the baud rate. Thus in the example above, a TH1 value of 1 would result in a baud rate of 28,800. However, if you set SMOD, you will achieve a baud rate of 57,600.
Add Information to this FAQ: If you have additional information or alternative solutions to this question, you may add to this FAQ by clicking here.