// Settings
static const uint64_t timer_max_count = 1000000;
static const TickType_t task_delay = 1000 / portTICK_PERIOD_MS;
// Globals
static hw_timer_t *timer = NULL;
static volatile int isr_counter;
static portMUX_TYPE spinlock = portMUX_INITIALIZER_UNLOCKED;
//*****************************************************************************
// Interrupt Service Routines (ISRs)
// This function executes when timer reaches max (and resets)
void IRAM_ATTR onTimer() {
// ESP-IDF version of a critical section (in an ISR)
portENTER_CRITICAL_ISR(&spinlock);
isr_counter++;
portEXIT_CRITICAL_ISR(&spinlock);
}
//*****************************************************************************
// Tasks
// Wait for semaphore and print out ADC value when received
void printValues(void *parameters) {
// Loop forever
while (1) {
// Count down and print out counter value
while (isr_counter > 0) {
// Print value of counter
Serial.println(isr_counter);
// ESP-IDF version of a critical section (in a task)
portENTER_CRITICAL(&spinlock);
isr_counter--;
portEXIT_CRITICAL(&spinlock);
}
printf("--------- \n");
// Wait 2 seconds while ISR increments counter a few times
vTaskDelay(task_delay);
}
}
//*****************************************************************************
// Main (runs as its own task with priority 1 on core 1)
void setup() {
// Configure Serial
Serial.begin(115200);
// Start task to print out results
xTaskCreatePinnedToCore(printValues,
"Print values",
1024,
NULL,
1,
NULL,
1);
//https://docs.espressif.com/projects/arduino-esp32/en/latest/api/timer.html?highlight=timer
//hw_timer_t * timerBegin(uint32_t frequency); // Hz
timer = timerBegin(8000000);
//void timerAttachInterrupt(hw_timer_t * timer, void (*userFunc)(void));
timerAttachInterrupt(timer, &onTimer);
//void timerAlarm(hw_timer_t * timer, uint64_t alarm_value, bool autoreload, uint64_t reload_count);
timerAlarm(timer, timer_max_count, true, 0);
// Delete "setup and loop" task
vTaskDelete(NULL);
}
void loop() {
// Execution should never get here
delay(10);
}