Artificial UART (SOFT UART)

Photo of author

By Jackson Taylor

Home » Programming » Artificial UART (SOFT UART)

As an Amazon Associate we earn from qualifying purchases.

A software UART (often written soft UART) is a serial port built in code instead of hardware. The microcontroller switches an ordinary I/O pin high and low at exactly the right moments to send a byte, and reads another pin at the right moments to receive one. The technique is also called bit-banging.

This article shows how it works with a PIC16F877A example in HI-TECH C, running at 16 MHz and 9600 baud. The same ideas apply to any other microcontroller, you only change the pin names and the delay routine.

Why use a software UART?

Most microcontrollers have a hardware UART module that handles timing for you. A software version is useful when:

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video
  • the chip has no UART peripheral, or it is already in use;
  • you need a second or third serial port;
  • the board is already wired and the TX or RX line sits on a pin the hardware UART cannot use.

If your chip has a free hardware UART, use it. It does not tie up the CPU and it keeps its timing while the program does other work. For the hardware route, see our PIC16F877A hardware UART guide, which uses the built-in module.

How a UART frame is built

A UART sends one byte at a time inside a small frame. The common 8N1 format (8 data bits, no parity, 1 stop bit) looks like this:

  1. The line idles high (logic 1) when nothing is being sent.
  2. A start bit pulls the line low (logic 0) for one bit time.
  3. Eight data bits follow, least significant bit (LSB) first.
  4. A stop bit returns the line high for one bit time.

There is no clock wire. Both sides agree on the baud rate in advance, and the receiver uses the falling edge of the start bit to line up its timing.

Baud rate and bit time

Every bit lasts 1 / baud rate seconds:

  • 9600 baud: 1 / 9600 is about 104 microseconds per bit.
  • 19200 baud: 1 / 19200 is about 52 microseconds per bit.
See also
PIC16F877A-HITECH C-Digital Output & Input

In the examples below the delay is set to 102 µs instead of 104 µs. Each instruction between the delays also takes a little time, so a slightly shorter delay keeps the real bit length close to the target. Treat 102 as a starting point and check it with a logic analyzer, an oscilloscope or a simulator. The right value depends on your compiler, clock and code.

Transmission

The first example sends the character 2. Its ASCII code is 0x32, which is 00110010 in binary. Because the LSB goes first, the line carries: start bit 0, then 0, 1, 0, 0, 1, 1, 0, 0, then stop bit 1. Pin RA0 is the transmit pin.

// Sending '2' (ASCII 0x32 = 00110010) at 9600 baud on RA0
// Bit time = 1/baud rate = 1/9600 = 104 microseconds
// The delay is kept slightly below that (102 us) to allow for instruction time
// For 19200 baud the bit time is about 52 microseconds
#include<pic.h>
#define _XTAL_FREQ 16000000
void main()
{
TRISA=0;
PORTA=0xff;        //Idle line (high)
__delay_us(102);
PORTA=0;           //Start bit
__delay_us(102);
PORTA=0;           //0th bit (LSB)
__delay_us(102);
PORTA=0xff;        //1st bit
__delay_us(102);
PORTA=0;           //2nd bit
__delay_us(102);
PORTA=0;           //3rd bit
__delay_us(102);
PORTA=0xff;        //4th bit
__delay_us(102);
PORTA=0xff;        //5th bit
__delay_us(102);
PORTA=0;           //6th bit
__delay_us(102);
PORTA=0;           //7th bit (MSB)
__delay_us(102);
while(1)
{
PORTA=0xff;        //Stop bit, then idle
}
}

Only RA0 matters here. Writing 0xff or 0 to the whole port simply drives RA0 high or low.

A reusable transmit function

Writing every bit by hand does not scale, so the next step is a function that sends any byte. It pulls the start bit low, shifts out each bit with a mask, and finishes with the stop bit. Put it in a header file and include it wherever you need serial output.

//SOFT-UART header file for pin RA0 (Transmission)
#include<pic.h>
#define _XTAL_FREQ 16000000
void uartsinglewrite (short int);   //any 8-bit data type works, because we work at bit level

void uartsinglewrite (short int a)
{
TRISA=0;
PORTA=0;               //Start bit
__delay_us(102);
PORTA=a&1;             //0th bit (LSB)
__delay_us(102);
PORTA=(a&2)>>1;       //1st bit
__delay_us(102);
PORTA=(a&4)>>2;       //2nd bit
__delay_us(102);
PORTA=(a&8)>>3;       //3rd bit
__delay_us(102);
PORTA=(a&16)>>4;      //4th bit
__delay_us(102);
PORTA=(a&32)>>5;      //5th bit
__delay_us(102);
PORTA=(a&64)>>6;      //6th bit
__delay_us(102);
PORTA=(a&128)>>7;     //7th bit (MSB)
__delay_us(102);
PORTA=1;               //Stop bit
__delay_us(102);       //Hold the stop bit for a full bit time
}

The last delay matters. Without it the stop bit would be cut short whenever you call the function twice in a row, and the receiver could miss the start of the next byte. Once this works, you can shorten the repeated lines with a for loop that shifts the byte one bit at a time.

See also
WHILE LOOP IN PYTHON

Reception

Receiving is harder than sending, because the timing is set by the other device. The receiver waits for the line to fall, which marks the start bit, and then reads each bit near its middle where the signal is most stable.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

The program below reads RA0 and shows the received byte on PORTB, for example on eight LEDs. Setting ADCON1 to 0x07 makes the PORTA pins digital, which is needed for RA0 to read as a normal input.

//Baud rate is 9600
//Received data is shown on PORTB
#include<pic.h>
#define _XTAL_FREQ 16000000
void main()
{
unsigned char value, i;
ADCON1=0x07;          //set PORTA as digital pins
TRISA=0xff;           //RA0 is the receive pin (input)
TRISB=0;              //PORTB is output
PORTB=0;
while(1)
{
if(RA0==0)            //falling edge: possible start bit
{
__delay_us(52);       //move to the middle of the start bit
if(RA0==0)            //still low, so it is a real start bit
{
value=0;
for(i=0;i<8;i++)
{
__delay_us(102);      //move to the middle of the next bit
if(RA0) value |= (1<<i);   //LSB arrives first
}
__delay_us(102);      //middle of the stop bit
PORTB=value;          //show the received byte
}
}
}
}

The half-bit delay is the important part. A receiver that waits a full bit time after the falling edge ends up sampling right where one bit changes into the next, which makes errors likely. Waiting half a bit first, then one bit per sample, reads each bit in its centre.

Limits and practical tips

  • The CPU is busy. While a byte is being sent or received, the processor does nothing else.
  • Interrupts disturb timing. An interrupt in the middle of a byte stretches a bit and corrupts the data. Disable interrupts during the byte, or keep interrupt routines very short.
  • Speed is limited. Low rates such as 9600 baud are comfortable. Higher rates leave little room for instruction overhead, especially on slow clocks.
  • Use a stable clock. A crystal is safer than an internal RC oscillator, because the bit timing depends on it.
  • Mind the voltage levels. A PIC pin gives 0 V and 5 V logic, not RS-232 levels. To talk to a PC, use a USB-to-serial adapter or a level converter such as a MAX232.
  • Add checks if needed. The examples have no parity, buffering or framing-error detection.
See also
ADDING FUZZY LOGIC FILE .FLS IN MATLAB- SIMULINK

Testing your code

Check the timing before you trust it on real hardware. A logic analyzer or oscilloscope shows the real bit width and lets you adjust the delay. You can also simulate it in Proteus with a virtual terminal. Our 8051 article has an 8051 UART example, and the Proteus-based Arduino UART and LCD simulation shows how received serial data can be displayed on a screen. If you use the mikroC compiler instead of HI-TECH C, see the mikroC UART example, which uses the built-in UART library.

FAQ

What is the difference between a hardware UART and a software UART?

A hardware UART is a peripheral inside the chip that generates and samples the bits by itself. A software UART does the same job with code and delays on a normal I/O pin, so it uses CPU time and is more sensitive to timing errors.

Can a software UART run at any baud rate?

In theory yes, but in practice it depends on the clock speed and how fast your code can run between delays. Standard rates such as 9600 baud are easy to reach, while high rates are unreliable because instruction time becomes a large part of each bit.

Why does my received data look wrong?

The usual causes are a baud rate mismatch, sampling at the edge of a bit instead of its middle, interrupts disturbing the delays, or a missing common ground between the two devices. Check the bit width with a scope or logic analyzer first.

Does a software UART need a stop bit?

Yes. The stop bit returns the line to idle and gives the receiver time to get ready for the next start bit. Hold it for a full bit time, especially when sending several bytes in a row.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works