Frequently Asked Questions

How do I get getc() to timeout after a specified time?

GETC will always wait for the character to become available. The trick is to not call getc() until a character is ready. This can be determined with kbhit().

The following is an example of how to time out of waiting for an RS232 character.

Note that without a hardware UART the delay_us should be less than a tenth of a bit time (10 us at 9600 baud). With hardware you can make it up to 10 times the bit time. (1000 us at 9600 baud). Use two counters if you need a timeout value larger than 65535.

short timeout_error;

char timed_getc() { 
   long timeout;
   
   timeout_error=FALSE; 
   timeout=0; 
   
   while(!kbhit()&&(++timeout<50000)) // 1/2 second 
      delay_us(10); 

   if(kbhit()) 
      return(getc()); 
   else { 
      timeout_error=TRUE; 
      return(0); 
   } 
}

C-Aware IDE Demo
Embedded C Learners Kit
C Workshop Compiler