#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/timers.h"
#include "esp_log.h"
#define TAG "xtimer_example"
// Counter to track the number of timer callbacks
static int callback_count = 0;
static const int stop_after_count = 4;
// Callback function
void timer_callback(TimerHandle_t xTimer) {
callback_count++;
ESP_LOGI(TAG, "Timer expired! Callback count: %d", callback_count);
// Stop the timer after 4 callbacks
if (callback_count >= stop_after_count) {
if (xTimerStop(xTimer, 0) != pdPASS) {
ESP_LOGE(TAG, "Timer stop failed!");
} else {
ESP_LOGI(TAG, "Timer stopped after %d callbacks", stop_after_count);
}
}
}
// Function to be executed in the timer daemon task context
void pendingFunction(void *pvParameter1, uint32_t ulParameter2) {
ESP_LOGI(TAG, "Pending function called with param1: %p, param2: %d", pvParameter1, ulParameter2);
}
void app_main() {
// Create a software timer
TimerHandle_t xTimer = xTimerCreate(
"Timer", // Timer name
pdMS_TO_TICKS(1000), // Timer period in ticks (milliseconds to ticks)
pdTRUE, // Auto-reload flag
(void *) 0, // Timer ID
timer_callback // Callback function
);
if (xTimer == NULL) {
ESP_LOGE(TAG, "Timer creation failed!");
return;
}
// Start the timer
if (xTimerStart(xTimer, 0) != pdPASS) {
ESP_LOGE(TAG, "Timer start failed!");
}
// Change the timer period to 2000 ticks (assuming 1 tick = 1 millisecond)
if (xTimerChangePeriod(xTimer, pdMS_TO_TICKS(2000), 0) != pdPASS) {
ESP_LOGE(TAG, "Timer change period failed!");
}
// Get the timer period
TickType_t period = xTimerGetPeriod(xTimer);
ESP_LOGI(TAG, "Timer period: %d ticks", period);
// Get the timer expiry time
TickType_t expiryTime = xTimerGetExpiryTime(xTimer);
ESP_LOGI(TAG, "Timer expiry time: %d ticks", expiryTime);
// Set and get the timer ID
void *newTimerID = (void *)111;
vTimerSetTimerID(xTimer, newTimerID);
void *timerID = pvTimerGetTimerID(xTimer);
ESP_LOGI(TAG, "Timer ID: %p", timerID);
// Call a function in the timer daemon task context
if (xTimerPendFunctionCall(pendingFunction, (void *)0xFFF, 111, 0) != pdPASS) {
ESP_LOGE(TAG, "Pending function call failed!");
}
// Get the timer daemon task handle
TaskHandle_t timerDaemonTaskHandle = xTimerGetTimerDaemonTaskHandle();
ESP_LOGI(TAG, "Timer daemon task handle: %p", timerDaemonTaskHandle);
}