Disable Timer within Timer ISR

blengerich
Posts: 2
Joined: Sat Feb 25, 2023 9:12 pm

Disable Timer within Timer ISR

Postby blengerich » Sat Feb 25, 2023 10:06 pm

Is it possible to disable a timer within the timer ISR itself? I want to disable the timer interrupt when a certain condition is met, which can be determined within the timer ISR itself. I wrote an example program which works for Arduino Uno and Mega, but not for ESP32. In the code below, the timer interrupt continues to occur, even though I disable it. To get it to work for the ESP32, I set a flag in the interrupt routine when I want to disable The main code checks this flag, and disables the timer if the flag is set. Is there a more efficient way of doing this?
  1. hw_timer_t * timer = NULL;
  2. int counter = 10;
  3.  
  4. void setup() {
  5.   Serial.begin(115200);
  6.    
  7.   timer = timerBegin(2, 80, true);
  8.   timerAttachInterrupt(timer, &onTimer, true);
  9.   timerAlarmWrite(timer, 500000, true);  // Interrupt occurs every 500ms
  10.   timerAlarmEnable(timer);
  11. }
  12.  
  13. void loop() {
  14.   Serial.println(counter);
  15.   delay(100);
  16. }
  17.  
  18. void onTimer() {
  19.   if (counter == 0) {
  20.     timerAlarmDisable(timer);
  21.   } else {
  22.     counter = counter - 1;
  23.   }
  24. }

Who is online

Users browsing this forum: No registered users and 60 guests