Timers and interrupts not working as expected

Mattgo
Posts: 5
Joined: Tue May 16, 2023 7:04 pm

Timers and interrupts not working as expected

Postby Mattgo » Fri Jan 12, 2024 7:34 pm

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() {
}

lbernstone
Posts: 829
Joined: Mon Jul 22, 2019 3:20 pm

Re: Timers and interrupts not working as expected

Postby lbernstone » Sat Jan 13, 2024 6:06 pm

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.

Mattgo
Posts: 5
Joined: Tue May 16, 2023 7:04 pm

Re: Timers and interrupts not working as expected

Postby Mattgo » Sun Jan 14, 2024 9:53 am

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
Attachments
esp.png
esp.png (193.59 KiB) Viewed 46169 times

lbernstone
Posts: 829
Joined: Mon Jul 22, 2019 3:20 pm

Re: Timers and interrupts not working as expected

Postby lbernstone » Wed Jan 17, 2024 12:26 pm

If you believe this does not match the Arduino standard, then open an issue at https://github.com/espressif/arduino-esp32/issues

Who is online

Users browsing this forum: No registered users and 89 guests