Reading/writing timer in interrupt

brentbrownnz
Posts: 1
Joined: Wed Aug 21, 2019 5:48 am

Reading/writing timer in interrupt

Postby brentbrownnz » Thu Aug 22, 2019 9:17 am

Is there a trick to accessing timers from within an interrupt? I have configured 2 x timer interrupts, and they are running great. Next I want to read the value of a timer... but if I un-comment the line containing timerRead() it crashes with "Guru Meditation Error: Core 1 panic'ed (LoadProhibited)". Code about as simple as I can make it so I'll post the whole thing here. Just getting started with ESP32 but experienced with various other micros, no idea what I'm doing wrong here. Thanks~!
  1. #include <Arduino.h>
  2.  
  3. #define LED 4
  4. #define DELAYPERIOD 100
  5.  
  6. hw_timer_t * timer0 = NULL;
  7. hw_timer_t * timer1 = NULL;
  8. portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
  9.  
  10. void IRAM_ATTR onTimer0(){                       // 90us timer interrupt
  11.   static uint64_t foo;
  12.  // foo = timerRead(timer1);
  13. }
  14.  
  15. void IRAM_ATTR onTimer1(){                       // 2400us timer interrupt
  16.  
  17. }
  18.  
  19. void setup() {
  20.   pinMode(LED, OUTPUT);
  21.  
  22.   timer0 = timerBegin(0, 80, true);              // Timer0 config: (timer0, prescaler = 12.5ns*80 = 1us, count up)
  23.   timerAttachInterrupt(timer0, &onTimer0, true); // Timer0 interrupt: (pointer, IRQ function, edge trigger)
  24.   timerAlarmWrite(timer0, 90, true);             // Timer0 alarm: (pointer, 90 x 1us = 90us, auto reload)
  25.   timerAlarmEnable(timer0);                      // Timer0 start
  26.  
  27.   timer1 = timerBegin(1, 1280, true);            // Timer1 config: (timer1, prescaler = 12.5ns*1280 = 16us, count up)
  28.   timerAttachInterrupt(timer1, &onTimer1, true); // Timer1 interrupt: (pointer, IRQ function, edge trigger)
  29.   timerAlarmWrite(timer1, 150, true);            // Timer1 alarm: (pointer, 150 x 16us = 2.4ms, auto reload)
  30.   timerAlarmEnable(timer1);                      // Timer1 start
  31. }
  32.  
  33. void loop() {
  34.   digitalWrite(LED, 1);
  35.   delay(DELAYPERIOD);
  36.   digitalWrite(LED, 0);
  37.   delay(DELAYPERIOD);
  38. }

kevscott
Posts: 3
Joined: Fri Oct 09, 2020 9:56 pm

Re: Reading/writing timer in interrupt

Postby kevscott » Sat Jan 29, 2022 9:25 pm

In setup(), you initialise timer0 then start it running. What this will do is call up the onTimer0 ISR. At this point you have still to initialise timer1 as the code in setup() for that has still to be executed.

As a result of that the timer1 structure is still set to the NULLs that you initialised them to at power on and the exception is correctly thrown. If you move the timerAlarmEnable(timer0) call to after the timerAlarmEnable(timer1) call it will work fine.

Who is online

Users browsing this forum: No registered users and 84 guests