[En-Nut-Discussion] How to write character filter with timeout?

Nathan Moore nategoose at gmail.com
Thu Aug 20 23:58:17 CEST 2009

I'm not sure I understand what you want, but I think you might want:
int wait_for_my_favorite_char(FILE * f, uint32_t max_time_to_wait, char
favorite_char) {
         int fn = _fileno(f);
         uint32_t start = NutGetMillis();
         uint32_t end = start + max_time_to_wait;
         uint32_t restore_to;
         _ioctl(fn, UART_GETREADTIMEOUT, &restore_to);
         _ioctl(fn,  UART_SETREADTIMEOUT, &max_time_to_wait);
         for (;;) {
               char c;
               int rc;
               uint32_t delta_time, now;
               rc = _read(fn, &c, 1); // you could use a getc type function
here and do error handling differently
               if (rc <0) {
                     _ioctl(fn, UART_SETREADTIMEOUT, &restore_to);
                     return -1;  // there was an error so read no further
               if (rc == 1) {
                      if (c == favorite_char) {
                              _ioctl(fn, UART_SETREADTIMEOUT, &restore_to);
                              return 1;  // I decided that 1 means we found
what we were looking for within the amount of time specified
               now = NutGetMillis();
               if (now >= end) {
                    _ioctl(fn, UART_SETREADTIMEOUT, &restore_to);
                    return 0; // I decided that 0 means that we ran out of
time before we found what we were looking for
               delta_time = end - now;
               _ioctl(fn, UART_SETREADTIMEOUT, &delta_time);

You should note that it discards all characters that it may read while

More information about the En-Nut-Discussion mailing list