How to make a software UART?
Submitted By: Jan Waclawek FAQ Last Modified: 09/21/06
- Software UARTs (also known as "bit-banged UART") are generally tricky to write, can go wrong easily, and even if they work properly they consume a lot of instruction cycles (most put all other processing to a complete halt when operating). Generally, it is not recommended to use them - lots of sweat, avoid that, when the next upgrade happen timing problems will most likely pop up.
- use a derivative with more internal UARTs (check out the Chips list on this site, or maybe the Keil chip list)
- attach a small "slave" '51 via SPI or I2C and use its UART (as a bonus, the slave micro can handle checksumming, retransmit (if required) and such. Also, it may, by buffering, be able to make the master transmit and receive "when convenient" rather than "when needed")
- attach an external UART chip, either the 16Cx5y variety (similar to those used in PC, many sources) or any other enhanced type; most of them attached via parallel bus, but there are also SPI/I2C interfaced types available too (by NXP and Maxim). Most of these come with FIFO (and other enhanced features); therefore it is often much more convenient to use them even than the internal UART.
- periodic timer interrupt at a rate 4-32x higher than the baudrate
- + fullduplex, even multichannel could be possible
- + does not require dedicated pin
- + under certain conditions can run from the same timer1 as the HW UART
- - permanently occupies significant % of processor time
- receiver triggered by an edge-triggered external interrupt (special alternative: a counter set to roll over on the first edge); then sampled using timer timed at baudrate (first sample at 1/2 baudrate for startbit).
- + low software overhead
- - dedicated (extint) pin needed for Rx
- - fullduplex requires 2 timers
- only receiver or only transmitter by performing the sampling in a loop in main program
- + simple
- - only 1 direction
- - uses up 100% of processor time
- - virtually excludes using other interrupts simultaneously
Alternatives are:
However, if you are sure you can/have to make a software UART, there are several options how to do so:
Examples:
http://www.atmel.com/dyn/resources/prod_documents/doc3ab877f2ec329.pdf
http://www.semiconductors.philips.com/acrobat/applicationnotes/AN446.pdf http://www.standardics.nxp.com/support/documents/microcontrollers/pdf/an446.pdf
Transmitter simply using timer at baudrate.
An implementation using PCA found in some 8051 derivatives:
http://www.intel.com/design/mcs51/applnots/270531.htm
An implementation from Dunfield: ftp://ftp.dunfield.com/ddsutils.zip
-----------
Contributions and corrections by Erik Malund
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.