This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

UART Communication: Polling or Interrupt?

There are basically two ways to interface UART in 8051:
1) Receive by polling the RI register in the main() loop, Transmit by using printf finction. Advantage: it's easy. Disadvantage: it's tricky as the speed used to poll the RI register is not safe, in other words if the cpu is busy doing something else we might loose one or more characters depending on CPU and transmit speed. Furthermore printf() overhead eats a lot of ROM, on the other way formatting with printf is rather easy.
2) Transmit and receive using Interrupt: here we read RI and TI flags inside the UART ISR to know if the interrupt is for a transmitted or received frame, upon that we take or put another byte in the serial buffer SBUF0 until the transmission or receive is completed. Advantage: no character loss, the ISR will be able to send and receive all the frames. Disadvantages: is more complicated and despite my attempts I'm unable to use printf() to transmit, I need to send the characters one by one, additionally I cannot use the formatting service of printf().
I'm wondering if someone have a good idea to:
a) Receive using Interrupt
b) Transmit using printf()
to merge the benefits of both techniques?
Here my code:

// Global Variables
unsigned char idata readBuffer[ READ_BUFFER_SIZE ];      // UART receiver buffer
unsigned char code * writeBufferPtr;          // UART transmitter buffer pointer
volatile unsigned char readCount = 0;         // number of bytes in write buffer
volatile unsigned char writeCount = 0;        // number of bytes in write buffer
//

// UART ISR
void uartISR(void) interrupt 4 using 1
{
    uchar dummy;
                       // handle buffered RX
    if ( RI0 ) {
        RI0 = 0;
        if ( readCount < READ_BUFFER_SIZE )   // receive data while buffer allows
            readBuffer[ readCount++ ]= SBUF0;
        else                                  // when buffer is full, discard it
            dummy = SUBF0;
    }
                       // handle buffered TX, in my attempts the entire if(TI0) statement has been removed to allow printf() to transmit
    if ( TI0 ) {
        TI0 = 0;
        if ( writeCount ) {                   // send data as long as it remains
            SBUF0 = *writeBufferPtr++;
            --writeCount;
        }
    }
}

//Receive routine example in the main() loop
while ( readCount < EXPECTED_SISE );  // wait until a number of data is received
// Handle the data on readBuffer[] here
readCount = 0;                        // prepare for the next reception

//Transmit routine example in the main() loop
printf("Hello world!");

0