Timeout implementation

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

Timeout implementation

Postby Suky_mtch » Fri Jan 31, 2020 9:18 pm

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: 14457
Joined: Wed May 27, 2009 8:48 am
Location: Salerno, Italy
Has thanked: 1076 times
Been thanked: 922 times
Contact:

Re: Timeout implementation

Postby Giovanni » Fri Jan 31, 2020 9:32 pm

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

Postby Suky_mtch » Mon Feb 03, 2020 5:26 pm

Hi,

thanks. I implemented the following using the function set:

Code: Select all

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

}


Regards!


Return to “ChibiOS/RT”

Who is online

Users browsing this forum: No registered users and 33 guests