Disable Timer within Timer ISR

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

Disable Timer within Timer ISR

Postby blengerich » Mon Feb 27, 2023 4:57 pm

Is it possible to disable a timer within the timer ISR itself? The example code below works for Arduino Uno and Mega, but not for ESP32. The timer interrupt continues to occur, even after disabling it. The disable command doesn't seem to register within the ISR. To get this to work for ESP32, I set a flag in the ISR, and then check that flag in the main code, and disable the timer when I see that the flag is set. I would like to disable the timer, without having to continuously checking the status of a flag.

  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. }
This code works...
  1. hw_timer_t * timer = NULL;
  2. int counter = 10;
  3. boolean timer_off_flag = false;
  4.  
  5. void setup() {
  6.   Serial.begin(115200);
  7.    
  8.   timer = timerBegin(2, 80, true);
  9.   timerAttachInterrupt(timer, &onTimer, true);
  10.   timerAlarmWrite(timer, 500000, true);  // Interrupt occurs every 500ms
  11.   timerAlarmEnable(timer);
  12. }
  13.  
  14. void loop() {
  15.   Serial.println(counter);
  16.  
  17.   if (timer_off_flag == true) {
  18.     timerAlarmDisable(timer);
  19.     timer_off_flag = false;
  20.   }
  21.   delay(100);
  22. }
  23.  
  24. void onTimer() {
  25.   if (counter == 0) {
  26.     timer_off_flag = true;
  27.   } else {
  28.     counter = counter - 1;
  29.   }
  30. }

Who is online

Users browsing this forum: Bing [Bot] and 65 guests