Question

So I have old code I am looking at, that I am supposed to update for a new micro controller. In the old code there is a function to flush the USART in case there is junk on it from the start up. The code is bellow:

#define RXC 7 

#define RX_COMPLETE (1<<RXC)    

void UART1_FLUSH(void){
    unsigned char dummy;   
    while ( UCSR1A & RX_COMPLETE ) dummy = UDR1;
}

Now from what I understand the while loop will keep going as long as there is something to read from the USART from register UDR1 that is why it is being stored in dummy since we do not need it. Now what I need help being explained to me is why the while loop works the way that it does?

Was it helpful?

Solution

Looking for UCSRnA in http://upcommons.upc.edu/pfc/bitstream/2099.1/10997/4/Annex3.pdf that code simply waits until bit 7 ("RXCn: USART Receive Complete") in USCR1A is off.

That document says about bit 7 This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty.

(1<<RXC) is the numerical value of bit 7. A bitwise AND (the &) between it and the value read from UCSR1A results in 0 (if the bit is off) or (1<<RXC) (if the bit is on). Since (1<<7) is 128 and that is not zero, the loop will be entered when the bit is set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top