I am running an ESP32 Timer interrupt where I want the timer interval to change between two values every time the interrupt-routine is called. Hence, when toggle0 = true I want one interval and when toggle0 = false I want a different one.
I tried setting the interval in the interrupt routine like below. But this causes a crash everytime the routine is called.
Any suggestions on how to accomplish this in a good way?
I am using the lib ESP32TimerInterrupt by Khoi Hoang.
#define _TIMERINTERRUPT_LOGLEVEL_ 4
#include "ESP32TimerInterrupt.h"
#define TRK_PIN_OUTPUT 19
#define TRK_OnTime 10
#define TRK_OffTime 1000
// Init ESP32 timer 0
#define TIMER0_INTERVAL_MS 1000
ESP32Timer ITimer0(0);
// Interrupt routine
bool IRAM_ATTR TimerHandler0(void *timerNo)
{
static bool toggle0 = false;
digitalWrite(TRK_PIN_OUTPUT, toggle0);
// Set time to next flip according to current toggle0-state
ITimer0.setInterval((toggle0 ? TRK_OnTime : TRK_OffTime) * 1000, TimerHandler0);
toggle0 = !toggle0;
return true;
}
void setup()
{
// Interval in microsecs
ITimer0.attachInterruptInterval(TIMER0_INTERVAL_MS * 1000, TimerHandler0);
}
void loop()
{
delay(10);
}
as an addition: interrupts should run through as fast as possible
inside timer interrupt routines you should never do serial printing.
switching an IO-pin HIGH to indicate that the isr is called can be used or setting a boolean-flag-variable that is then checked outside the ISR.
serial printing even on 115200 baud or higher consumes too much time.
Possibly Timer0, Timer1 are used by the core, etc.
Try Timer2 to see OK there. I'm trying here many hours and still OK
If the problem persists, because of the way you're using ISR (the setInterval() function is not designed to be used inside ISR + aggressive timer 10ms), I suggest you rewrite the code to use the correct way
Raise a flag inside ISR
Check the flag frequently, every e.g. 0.5ms, then call setInterval() if flag raised. Certainly, you'll loose a little bit accuracy this way
or
Rewrite the code not using setInterval() inside ISR, but program the registers directly.