Page 1 of 1

Timeout implementation

Posted: Fri Jan 31, 2020 9:18 pm
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!

Re: Timeout implementation

Posted: Fri Jan 31, 2020 9:32 pm
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

Re: Timeout implementation

Posted: Mon Feb 03, 2020 5:26 pm
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!