Timeout implementation

Discussions and support about ChibiOS/RT, the free embedded RTOS.
Post Reply
Suky_mtch
Posts: 5
Joined: Wed Jan 29, 2020 9:55 pm

Timeout implementation

Post by Suky_mtch »

Hi,

A general query on how to implement a timeout in chibios correctly.
I currently do the following, for example:

Code: Select all

static THD_WORKING_AREA(wa_thread, 128);
static THD_FUNCTION(Tasks, arg) {
   systime_t timeout;
   (void)arg;

   while(TRUE){
      chThdSleepMilliseconds(10);
      if(GetArray(&buffer[0], 1) == 1){
         if(buffer[0] == 0x55){
            timeout = chVTGetSystemTimeX() + TIME_S2I(5);
         }
      }
      // .....
      if(chVTGetSystemTimeX() > timeout){
         chMBPostTimeout(&mailbox, code, TIME_IMMEDIATE);
      }
   }
}


But it occurs to me that in this way when the counter (chVTGetSystemTimeX()) reach its maximum and then restart from zero it can generate an error. What would be the correct way to implement it?

Regards!
User avatar
Giovanni
Site Admin
Posts: 14891
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 996 times

Re: Timeout implementation

Post by Giovanni »

Hi,

Use this:

Code: Select all


/**
 * @brief   Checks if the specified time is within the specified time range.
 * @note    When start==end then the function returns always false because the
 *          time window has zero size.
 *
 * @param[in] time      the time to be verified
 * @param[in] start     the start of the time window (inclusive)
 * @param[in] end       the end of the time window (non inclusive)
 * @retval true         current time within the specified time window.
 * @retval false        current time not within the specified time window.
 *
 * @xclass
 */
static inline bool chTimeIsInRangeX(systime_t time,
                                    systime_t start,
                                    systime_t end) {

  return (bool)((systime_t)((systime_t)time - (systime_t)start) <
                (systime_t)((systime_t)end - (systime_t)start));
}


Start and end are your interval, "time" is the current time.

Code: Select all

systime_t start = chVTGetSystemTimeX();
systime_t end = chTimeAddX(start, TIME_S2I(5));
while (chTimeIsInRangeX(chVTGetSystemTimeX(), start, end)) {
  /* Your code */
}
/* Timeout */


Time wrapping is not a problem, it is designed to work that way.

Giovanni
Suky_mtch
Posts: 5
Joined: Wed Jan 29, 2020 9:55 pm

Re: Timeout implementation

Post by Suky_mtch »

Hi,

thanks. I implemented the following using the function set:

Code: Select all

timestamp = chVTGetSystemTimeX();
// ...
if(chVTTimeElapsedSinceX(timestamp) > TIME_S2I(5)){

}


Regards!
Post Reply