FreeRTOS Software Timers: Non-Blocking Delays and Periodic Callbacks
Software timers let you schedule functions to run once or periodically without blocking tasks or using delay().
Key idea:
Software timers run in a dedicated timer service task. They use a callback function that executes when the timer expires. They are not hardware timers — they run in software.
One-Shot Timer
#include <Arduino_FreeRTOS.h>
#include <timers.h>
TimerHandle_t xTimer;
void timerCallback(TimerHandle_t xTimer) {
Serial.println("One-shot timer expired!");
}
void setup() {
Serial.begin(115200);
// Create one-shot timer (5 second delay)
xTimer = xTimerCreate(
"OneShot", // Name
pdMS_TO_TICKS(5000), // Period (5000ms)
pdFALSE, // Auto-reload: false = one-shot
NULL, // Timer ID
timerCallback // Callback function
);
if (xTimer != NULL) {
xTimerStart(xTimer, 0);
}
vTaskStartScheduler();
}
void loop() {}Auto-Reload Timer (Periodic)
TimerHandle_t xPeriodicTimer;
void periodicCallback(TimerHandle_t xTimer) {
Serial.println("Periodic callback!");
}
void setup() {
Serial.begin(115200);
// Create auto-reload timer (1 second period)
xPeriodicTimer = xTimerCreate(
"Periodic",
pdMS_TO_TICKS(1000),
pdTRUE, // Auto-reload: true = periodic
NULL,
periodicCallback
);
xTimerStart(xPeriodicTimer, 0);
vTaskStartScheduler();
}Timer with ID (Multiple Timers)
TimerHandle_t timers[2];
void timerCallback(TimerHandle_t xTimer) {
int id = (int)pvTimerGetTimerID(xTimer);
Serial.print("Timer ");
Serial.print(id);
Serial.println(" fired");
}
void setup() {
Serial.begin(115200);
// Create two timers with different IDs
timers[0] = xTimerCreate("Timer1", pdMS_TO_TICKS(1000), pdTRUE, (void*)1, timerCallback);
timers[1] = xTimerCreate("Timer2", pdMS_TO_TICKS(2000), pdTRUE, (void*)2, timerCallback);
xTimerStart(timers[0], 0);
xTimerStart(timers[1], 0);
vTaskStartScheduler();
}Timer Control Functions
// Stop a timer
xTimerStop(xTimer, 0);
// Reset a timer (restart period)
xTimerReset(xTimer, 0);
// Change period
xTimerChangePeriod(xTimer, pdMS_TO_TICKS(500), 0);
// Delete timer
xTimerDelete(xTimer, 0);
// Check if timer is active
if (xTimerIsTimerActive(xTimer) != pdFALSE) {
// Timer is running
}Key Takeaways
xTimerCreate()creates a software timer- One-shot timers fire once; auto-reload timers fire periodically
xTimerStart()starts the timer- Timer callbacks run in the timer service task — keep them fast and non-blocking
- Use
pdMS_TO_TICKS()to convert milliseconds to ticks - Timer ID allows one callback to handle multiple timers
Resources
- FreeRTOS Software Timers: https://www.freertos.org/Software-Timers.html
- Video: FreeRTOS Timers Tutorial - https://www.youtube.com/watch?v=3Tl7AXpL1fU
- FreeRTOS Timer API: https://www.freertos.org/Timer-API-Functions.html