Skip to main content

FreeRTOS Timer

FreeRTOS Timer

There are two main uses of timers: the first is to process after a certain time, and the second is to process periodically.

The GR-ROSE SDK can use the MsTimer library as cyclic processing, but this MsTimer uses the FreeRTOS timer.

The following is an example of a timer.


#include <Arduino.h>
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
 
TimerHandle_t xAutoReloadTimer, xOneShotTimer;
void oneShotTimerCallback(TimerHandle_t xTimer);
void autoReloadTimerCallback(TimerHandle_t xTimer);
 
void setup() {
  Serial.begin(9600);
  delay(3000); // for waiting to display a serial monitor
   
  xOneShotTimer    = xTimerCreate("OneShot", 1000, pdFALSE, 0, oneShotTimerCallback);
  xAutoReloadTimer = xTimerCreate("Reload" , 1000, pdTRUE , 0, autoReloadTimerCallback);
 
  if((xOneShotTimer != NULL) && (xAutoReloadTimer != NULL)){
    xTimerStart(xOneShotTimer, 0);
    xTimerStart(xAutoReloadTimer, 0);
  }
}
 
void loop() {
  static uint32_t old_time = millis();
  static bool flag = false;
  if((millis() - old_time) > 5000 && (flag == false)){ // after 5 seconds
    xTimerChangePeriod(xAutoReloadTimer, 100, 0);
    flag = true;
  }
}
 
void oneShotTimerCallback(TimerHandle_t xTimer){
  Serial.println("One-shot timer callback executing");
}
 
void autoReloadTimerCallback(TimerHandle_t xTimer){
  Serial.println("Auto-reload timer callback executing");
}

Output result:
One-shot timer callback executing
Auto-reload timer callback executing
Auto-reload timer callback executing
Auto-reload timer callback executing
Auto-reload timer callback executing

The above sample generates two timers. One is "xOneShotTimer" and the other is "xAutoReloadTimer". Each is generated by xTimerCreate (), but the processing is changed by the third argument.

Five seconds after the timer is generated, the cycle of "xAutoReloadTimer" is shortened using xTimerChangePeriod().