Global variables within an interrupt handler

Hi New to forum and first post… but here goes…

I am using the ESP32 Pico Kit and wanted to create a watchdog timer. Based on lib example I modified this code to see if I could access variables within an interrupt handler…

The timer triggers the interrupt at the correct time (so I have effectively a watchdog) but from within the interrupt handler I don’t seem to be able to print out the msDuration global volatile variable that I was using to measure verify the timings of the code… (see below)

#include “esp_system.h”

const int wdtTimeout = 5000; //time in ms to trigger the watchdog
hw_timer_t *timer = NULL;

volatile long loopTime = 0;
volatile int msDuration = 0;

void IRAM_ATTR resetModule() {
ets_printf(“Inside interrupt handler → reboot with after a duration of %d (should be about 5000!)\n”, msDuration);
esp_restart();
}

void setup() {
Serial.begin(115200);
Serial.println();
Serial.println(“running setup”);

timer = timerBegin(0, 80, true); //timer 0, div 80
timerAttachInterrupt(timer, &resetModule, true); //attach callback
timerAlarmWrite(timer, wdtTimeout * 1000, false); //set time in us
timerAlarmEnable(timer); //enable interrupt
}

void loop() {
Serial.println(“running main loop”);

timerWrite(timer, 0); //reset timer (feed watchdog)
long loopTime = millis();
long msDuration = 0;

for (int i=0;i<15;i++)
{
msDuration = millis() - loopTime;
Serial.printf(“loop time is = %d on loop number %d\n”, msDuration, i);
delay(1000); //simulate work
}
}

and the output from a run is below…

running setup
running main loop
loop time is = 0 on loop number 0
loop time is = 1001 on loop number 1
loop time is = 2001 on loop number 2
loop time is = 3001 on loop number 3
loop time is = 4001 on loop number 4
Inside interrupt handler → reboot with after a duration of 0 (should be about 5000!)
ets Jun 8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)

why does the ets_printf get msduration as 0 ?? (see bold and underlined output above)?

Any suggestions or help much apprecated.

Thanks.

Inside an interrupt handler, interrupts are off. Printing things to the serial monitor uses interrupts and should be avoided. Inside the interrupt handler, you should just set a flag and then test/act on that flag in your main loop().

You have a local msDuration in loop(). Remove it.

Thanks both really appreciated you comments and help… and as for me declaring a local msDuration in loop() - Doh!!!