Page 1 of 1

Timers and interrupts not working as expected

Posted: Fri Jan 12, 2024 7:34 pm
by Mattgo
Hello, I'm facing some unexpected behavior regarding timers and interrupts. I'm hoping to get some insights or suggestions.

My intention is to use the timerWrite(timer, 50); function to set the timer counter to 50, then have it count up to 100, trigger an interrupt, and reset to zero because of the auto-reload feature. However, the behavior I'm observing is different. Once I set timerWrite(timer, 50);, the timer is counting only between 50 and 100 and does not reset to zero. It only resets to zero if I explicitly call timerWrite(timer, 0);.

Here is code for reference:

Code: Select all

hw_timer_t * timer = NULL;

void IRAM_ATTR onTimer()
{
bool state = digitalRead(5);
digitalWrite(5, !state);
}

void setup() {
  pinMode(5, OUTPUT);
  Serial.begin(115200);
  
  timer = timerBegin(0, 80, true); // Timer 0, prescaler 80, count up
  timerAttachInterrupt(timer, &onTimer, true);
  timerAlarmWrite(timer, 100, true);
  timerAlarmEnable(timer);
  timerWrite(timer, 50);
}

void loop() {
}

Re: Timers and interrupts not working as expected

Posted: Sat Jan 13, 2024 6:06 pm
by lbernstone
While it is weird, I think it is correct. Call timerRestart in your alarm function, or have a separate one shot timer that then starts the normal cycle for better precision.

Re: Timers and interrupts not working as expected

Posted: Sun Jan 14, 2024 9:53 am
by Mattgo
I found this while rewriting library from AVR to ESP32. Once I figured out what the problem is I sorted it by calling timerWrite(timer, 0).
It is just make no sense to me because timerWrite is supposed to change just actual value of counter. If I would change the setup permanently I will call timerAlarmWrite and change alarm value. For AVR it is working as expected. This seems like bug or poorly documented feature

Image

Re: Timers and interrupts not working as expected

Posted: Wed Jan 17, 2024 12:26 pm
by lbernstone
If you believe this does not match the Arduino standard, then open an issue at https://github.com/espressif/arduino-esp32/issues