Does While statement stop interrupts

// This is a 'while' test. It appears that the while statement, locks out timer ISR
// If line 18 and line 19 is deleted, while loop freezes. If 18 or 19 is
// enabled, while loop runs ok.

#include <TimerOne.h>
int tick;
//------------------------------------------------------------------------------------------------------
void setup() {
Serial.begin(115200);
Timer1.initialize(2000);
Timer1.attachInterrupt(tick_time);
}
//-----------------------------------------------------------------------------------------------------------------
void loop() {
Serial.println("16 loop start");
while(tick < 20) { // tick = 20 should NEVER be printed !!
// interrupts(); // If this and next line are both deleted
Serial.print("19 tick=");Serial.println(tick); // 'While' loop does not run.
}
Serial.println("21 here after while loop completion");
tick = 0;
}
//------------------------------------------------------------------------------------------------------------------------
void tick_time() {
tick++;
}
//------------------------------------------------------------------------------------------------------------------------
I have used while loops successfully for years, but not with a timer ISR.

Hi @alveystreet ,

Welcome to the forum..
need to declare tick as volatile..

volatile int tick;

good luck.. ~q

What if you try

volatile int tick;

All variables no matter the type used both in interrupt service routines and regular code must be declared volatile.

You must also take extra care when you access multi-byte variables outside the interrupt code.

An int is such a variable.

So change the typeof tick to byte, or access it properly.

Many ppl solve this by grabbing a copy, viz:

  int myTick;
  noInterrupts();
  myTick = tick;
  interrupts();

then going on to use myTick instead of tick.

You must do that however you use tick, reading it or assigning to it or whatever. When you are not in the actual interrupt service routine.

a7

Thank you gentlemen. Problem sorted. HU! why didn't I think of this.

not just multi-byte. single byte too.

Yes. I have improved the language in my previous post. THX.

a7

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.