WebbotLib AVR library
WebbotLib It just does it
  C++ documentation  C documentation

uartsw.h

Simulates a UART in software.
Exactly the same functions are available as for a hardware UART so refer to uart.h for the list of methods. This means we can interchange between hardware and software UARTs with very few code changes - just your initialisation code.
Each software UART requires a 16 bit Timer with two compare channels. If you want the uart to receive incoming data then the IO pin used for 'receive' must be the input capture pin associated with the timer. See the tables in the sys/*.h for your board. If in doubt use timer number 1. The output pin, for the 'transmit wire', can be any available IO pin.
If you want to add buffers to the receive and/or transmit then you must create these buffers yourself. Here's an example for the ATMega168 that uses timer 1 (input capture is always on B0) and transmits on D1 and has an 80 byte buffer on both the receive and transmit:
#include "sys/atmega168.h"
#include "uartsw.h"
 
// Make receive buffer space
unsigned char rxArr[80];
 
// Create the receive buffer
cBuffer rxBuf = MAKE_BUFFER(rxArr);
 
// Make transmit buffer space
unsigned char txArr[80];
 
// Create the transmit buffer
cBuffer txBuf = MAKE_BUFFER(txArr);
 
// Create the software uart
SW_UART swUART = MAKE_SW_UART_BUFFERED( &rxBuf, &txBuf, 1, B0, D1, FALSE, null,null,null);
 
// Create a 'define' in case we change its name
#define URT &swUART
 
// This routine is called once only and allows you to do any initialisation
// Dont use any 'clock' functions here - use 'delay' functions instead
void appInitHardware(void){
    // Initialise the UART to 4800 baud
    uartInit(URT, (BAUD_RATE)4800);
}
 
TICK_COUNT appInitSoftware(TICK_COUNT loopStart){
    return 0;
}
 
// This routine is called repeatedly - its your main loop
TICK_COUNT appControl(LOOP_COUNT loopCount, TICK_COUNT loopStart){
    // Do stuff with the UART
    return 0;
}
Note that you can pass 'null' for the receive pin (if your UART has no input) or 'null' for the transmit pin (if your UART has no output).
N.B. Emulating a UART in software is quite resource intensive. Don't expect to achieve a high baud rate as a result! You may be able to achieve say 9600 or 19200 baud with a 16MHz processor depending upon what else you are expecting the processor to do. So, if in doubt, then use a software uart at the lowest expected baud rate of the receiving device.

Valid XHTML 1.0 Transitional