When setting the baud rate on the S51 UART, anemia there are four modes. Two of these modes divide the clock rate by either 16 or 32 and use that to set the baud rate, here while the other two modes are triggered based on Timer1 overflow. Most places recommend that you set Timer1 into mode 2: 8 bit timer with auto reload. In this mode, hospital you set TH1 to some value (>255) which will cause it to verflow every (CLOCK RATE)/([192 or 384]*(desired baud rate)). This can work well if you have a crystal that matches a baud rate pretty well, but that is not allways the case. If you have a crystal that does not give a desired baud rate, or you want to automatically detect the baud rate (as is done in PAULMON2) fancier timing may be needed. The benefit of mode 2 for Timer1 is that it breaks up the 16-bit timer into high and low bytes, TH1 and TL1 respectivly. TL1 is used for the timer, and every time it overflows, it is set to the value of TH1 and the timer is restarted. By using the timer in 13-bit or 16-bit modes, we can have better timing control than with the 8-bit mode. The downside is that the timer does not auto reload so we need to use an interrupt handler (for IE1) to manually reload the value. Don’t forget to take into account the time it takes to execute instructions involved in handling the interrupt and returning in your calculations. With this in hand, you can have a wider choice of crystals for a certain baud rate. Don’t worry about getting very close to it, that is, dont worry about getting higher resolution than provided by your clock source, as it wont do you any good.
A particularly elegant way is demonstrated by Paul Stroffregen in PAULMON. PAULMON waits for a CR character to be sent to determine the effective baud rate. It uses a timer to measure bit transmission times as it matches the bit pattern for the CR and then sets the baud rate based on those calculations. The source code is available so it provides a nice example. (This document notes that as much as a 2.5% communication clock mismatch is tolerated.)
( doc4316.pdf ) ( doc2487.pdf )