Atmega168 breaking out of ISR I wrote a code to handle an ISR triggered by UART input. I'm looking for 2 characters or more. I can handle extra characters and garbage values, but problem arises when I get less than 2 chars, specially when an empty string is sent to the atmel. The UART_receive() on the atmel gets stuck at: while ( !(UCSR0A &amp; (1&lt;&lt;RXC0)) );

Is there any way I can break out of this? The code is posted below:

unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
{
unsigned char i = 0;

if (size == 0) return 0;            // return 0 if no space

while (i &lt; size - 1) {              // check space is available (including additional null char at end)
    unsigned char c;
    while ( !(UCSR0A &amp; (1&lt;&lt;RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
    c = UDR0;
    if (c == '\0') break;           // break on NULL character
    x[i] = c;                       // write into the supplied buffer
    i++;
}
x[i] = 0;                           // ensure string is null terminated

return i + 1;                       // return number of characters written
}


The actual ISR in question is posted below. It reads the value, sets a flag, and exits as soon as possible.

ISR(USART_RX_vect)
{
    len = USART_Receive_string(uart_string,4); //makes space for 2 character and "\0" 
    UART_flag = 1;
} 


The the buffer is set up in main()

unsigned char uart_string[20];
As a fundamental principle of design you should not be expecting to receive multiple characters in the ISR.

The interrupt fires when a character has been received, so that is all your program should count on finding.  You can if you really want to poll the UART when you are done reading the first character and see if another has arrived, but there would generally not be time for that to have happened and you definitely should not be waiting for it in the ISR.  Rather, if the ultimate consuming code needs multiple characters, then that should hold off executing dependent code until multiple invocations of the ISR have resulted in the collection of the needed number of characters.

Things can get a little more complicated on parts with multi-stage UART FIFOs, but that is not the case here.