C Serial I/O Software

Here is the simplest code I've found for doing "bit bang" (software only) serial communications in C:

#define BITFIX 1 //fudge to account for extra cycles between delays
#define BITTIME ((CPUHZ / BAUD) - BITFIX) // time needed to send bit
UARTTX_TRIS = 0;
UARTRX_TRIS = 1;

void send_serial_byte(unsigned char data) {
  unsigned char i;
  i=8;                   // 8 data bits to send
  UARTTX_IO = 1;         // send start bit
  DelayMs(BITTIME);
  while(i!=0) {          // send 8 serial bits, LSB first
    if (data & 0x01)
      UARTTX_IO = 1;
    else
      UARTTX_IO = 0;
    data >>= 1;          // rotate left to get next bit
    i--;
    DelayMs(BITTIME);
    }
  UARTTX_IO = 0;
  DelayMs(BITTIME);
  }


You have to play around with FIX until the timing works right. This compensates for the delay introduced by the instructions between the delays. If the processor is very fast, it will be 0 or 1. If it's slow, the value may increase and you may not be able to get it to work at all.

And you have to define or find:

There needs to be a delay routine you can call with millisecond precision. The receive routine in the same except it reads UARTRX_IO and shifts in a 0 or a 1 depending.