Page 1 of 1

Two instances of HardwareTimer problem

Posted: Sat Feb 01, 2020 11:41 pm
by zokipoki
I have a simple sketch with two HardwareTimer instances.

Code: Select all

TIM_TypeDef *trInstance = TIM4;
HardwareTimer *trtimer = new HardwareTimer(trInstance);

TIM_TypeDef *stInstance = TIM1;
HardwareTimer *stimer_t = new HardwareTimer(stInstance);


void setup() {
  Serial.begin (115200);
  delay(2000);
  Serial.println("welcome");
  trtimer->setMode(1, TIMER_OUTPUT_COMPARE);
  trtimer->attachInterrupt(1, timer1Interrupt);
  trtimer->setOverflow(10 * 1000000, MICROSEC_FORMAT);
  trtimer->resume();
  
  stimer_t->setMode(2, TIMER_OUTPUT_COMPARE);
  stimer_t->attachInterrupt(2, timer2Interrupt);
  stimer_t->setOverflow(30, HERTZ_FORMAT);
  stimer_t->resume();

}

void timer1Interrupt(HardwareTimer*) {
  Serial.println("timer begin process");
  delay(4000); //simulate
  Serial.println("timer end process");
}

void timer2Interrupt(HardwareTimer*) {
  Serial.println("process should not stop because of timer1");  
}

void loop() {
//  Serial.println("loop begin process");
//  delay(4000); //simulate
//  Serial.println("loop end process");
}
My problem is that timer1Interrupt blocks execution of timer2Interrupt and in my case that is unacceptable.
They are acting like timer1Interrupt and timer2Interrupt are executing in same thread.
If i move the code from timer1Interrupt to loop everything works as it should.
What am i doing wrong?

Re: Two instances of HardwareTimer problem

Posted: Mon Feb 03, 2020 8:37 am
by ABOSTM
Code in callback is executed in interruption context.
So yes, when timer1Interrupt() executes it will block more than 4 seconds(due to your delay).
So during this time it prevent timer2Interrupt() from running.
Generally, callback should be very short, delay and print are not recommended.

Re: Two instances of HardwareTimer problem

Posted: Mon Feb 03, 2020 9:46 pm
by fredbox
See http://gammon.com.au/interrupts section "Hints for writing ISRs".