I am trying to make myself familiar with timers and interrupts. For this purpose I created this piece of code which doesn`t behave as expected sometimes. The ISR function blink() turns the timer on and off. The ISR of the timer callback() turns a LED ON and OFF. So in the end I can control if the LED blinks by a push button. In most of the cases this works fine. But sometimes the LED stays solid ON without blinking, which is as far as I understand this code not possible. Maybe some of you guys can explain this strange behaviour to me?
I'm not sure (you have to dive into TimerOne library) but I'm getting the feeling .stop() might not remove the timer interrupt flag. So if the interrupt fires before interrupts are disabled it is queued and executed after interrupts resume. Or even (but not 100% sure), if a specific interrupt is off but global interrupts on, it only means the ISR isn't called, not that the flag isn't set. Aka, the the flag is still set when an interrupt fires only no code is run. But once you turn on the interrupt and the flag is still set it will run the code.
But there are more then one library called TimerOne so which do you use?
Also, quick note, when entering a ISR, interrupts are disabled by default. No need to do it yourself
Thanks for the fast answer. Your explanation sounds understandable to me. The callback() function fires one more time and turns on the LED forever.
I tried your fix with the flag register but it didn`t change the situation at all. I also included your statement after Timer.stop() but nothing changed.
• Bit 0 – TOV1: Timer/Counter1, Overflow Flag
The setting of this flag is dependent of the WGM13:0 bits setting. In Normal and CTC modes, the TOV1 Flag is
set when the timer overflows. Refer to Table 16-4 on page 132 for the TOV1 Flag behavior when using another
WGM13:0 bit setting.
TOV1 is automatically cleared when the Timer/Counter1 Overflow Interrupt Vector is executed. Alternatively,
TOV1 can be cleared by writing a logic one to its bit location.
No problem, thanks for putting me into the right direction anyway.
As far as I am reading many people suggest to use a timer an poll the button state within its ISR.
Unfortunately I can`t find some arduino related examples for this method. Maybe someone who already used this method can post a code snipet of it here please?
zopffa:
so in fact I write Bit0 and Bit1 value = 1 to the register.
Is that what you mean?
Yes.
It may not hurt in this case, because all the bits belong to the same timer,
but it is inefficient (one read and the or are superfluous) and incorrect.
There are some other similar behaving bits, for example the PINx registers,
where writing a 1 to a bit toggles the output state, where it is more critical to get it right.