Comparing a variable during interrupt routine

Hi,
Im using a teensy4.0 to measure the time differences between digital interrupts on several pins:

i first attach my interrupts

attachInterrupt (digitalPinToInterrupt (risePin[0]), up_1, RISING);  // attach interrupt handler

and have a routine that is called when the interrupt is detected:

void up_1 ()
{
  rise[0][countUp_1] = ARM_DWT_CYCCNT;
  countUp_1 += 1;
  if (countUp_1 > 999) {
    detachInterrupt(digitalPinToInterrupt(risePin[0]));
    riseFin_1 = 1;
  }
}

this all works very well as long as i have countUp_1 comparing to a number, if i change it to a variable or a #define value that is started at the start of the progam it behaves strangely and messes up and gives me funny values. there is alot more to this code but this is the part i have found creates a failure.

is there a reason for this? can i not compare two variables in an interrupt routine?

any help on this would be awesome.

many thanks

Don’t post snippets (Snippets R Us!)

Are your variables volatile?

I haven't posted this in a while.

Let's try that inline...

Sweet.

I like the new forum software.

Two things.
First, a good rule of thumb is to do as little as possible in an interrupt. Set a flag and handle it in loop().
Second, your local variables probably should be static because every time you enter the interrupt, they get reinitialized.

hi, thanks for all the responses, also sorry for not posting the code; thought it could have been abit overkill. ill stick it on the end of this.

i intend to use 8 channels in the full version but just testing with 4 for ease at the moment (hence the 16 ISRs

@SteveMann im not sure what you mean by the variables being reinitialized each time? the countUp and countDown vars seem to work fine, since the data it transmits once the counters have reached the required value comes out poperly, i would expect if it resets to 0 each time the ISR runs it would only ever have one non zero value in each row of the array?

//define pins
const byte LED = 13;

const byte risePin[] = {0, 2, 4, 6, 8, 10, 12, 14, 16};
const byte fallPin[] = {1, 3, 5, 7, 9, 11, 13, 15, 17};

const byte numCh = 4;
//define logging arrays
unsigned long rise[8][1000];
unsigned long fall[8][1000];

//define counters
int countUp[] = {0, 0, 0, 0, 0, 0, 0, 0};
int countDown[] = {0, 0, 0, 0, 0, 0, 0, 0};
//define flags
byte riseFin[] = {0, 0, 0, 0, 0, 0, 0, 0};
byte fallFin[] = {0, 0, 0, 0, 0, 0, 0, 0};


// Interrupt Service Routine (ISR)
void up_1 ()
{
  rise[0][countUp[0]] = ARM_DWT_CYCCNT;
  countUp[0] += 1;
  if (countUp[0] > 999) {
    detachInterrupt(digitalPinToInterrupt(risePin[0]));
    riseFin[0] = 1;
  }
}
void down_1 ()
{
  fall[0][countDown[0]] = ARM_DWT_CYCCNT;
  countDown[0] += 1;
  if (countDown[0] > 999) {
    detachInterrupt(digitalPinToInterrupt(fallPin[0]));
    fallFin[0] = 1;
  }
}
void up_2 ()
{
  rise[1][countUp[1]] = ARM_DWT_CYCCNT;
  countUp[1] += 1;
  if (countUp[1] > 999) {
    detachInterrupt(digitalPinToInterrupt(risePin[1]));
    riseFin[1] = 1;
  }
}
void down_2 ()
{
  fall[1][countDown[1]] = ARM_DWT_CYCCNT;
  countDown[1] += 1;
  if (countDown[1] > 999) {
    detachInterrupt(digitalPinToInterrupt(fallPin[1]));
    fallFin[1] = 1;
  }
}
void up_3 ()
{
  rise[2][countUp[2]] = ARM_DWT_CYCCNT;
  countUp[2] += 1;
  if (countUp[2] > 999) {
    detachInterrupt(digitalPinToInterrupt(risePin[2]));
    riseFin[2] = 1;
  }
}
void down_3 ()
{
  fall[2][countDown[2]] = ARM_DWT_CYCCNT;
  countDown[2] += 1;
  if (countDown[2] > 999) {
    detachInterrupt(digitalPinToInterrupt(fallPin[2]));
    fallFin[2] = 1;
  }
}
void up_4 ()
{
  rise[3][countUp[3]] = ARM_DWT_CYCCNT;
  countUp[3] += 1;
  if (countUp[3] > 999) {
    detachInterrupt(digitalPinToInterrupt(risePin[3]));
    riseFin[3] = 1;
  }
}
void down_4 ()
{
  fall[3][countDown[3]] = ARM_DWT_CYCCNT;
  countDown[3] += 1;
  if (countDown[3] > 999) {
    detachInterrupt(digitalPinToInterrupt(fallPin[3]));
    fallFin[3] = 1;
  }
}
void up_5 ()
{
  rise[4][countUp[4]] = ARM_DWT_CYCCNT;
  countUp[4] += 1;
  if (countUp[4] > 999) {
    detachInterrupt(digitalPinToInterrupt(risePin[4]));
    riseFin[4] = 1;
  }
}
void down_5 ()
{
  fall[4][countDown[4]] = ARM_DWT_CYCCNT;
  countDown[4] += 1;
  if (countDown[4] > 999) {
    detachInterrupt(digitalPinToInterrupt(fallPin[4]));
    fallFin[4] = 1;
  }
}
void up_6 ()
{
  rise[5][countUp[5]] = ARM_DWT_CYCCNT;
  countUp[5] += 1;
  if (countUp[5] > 999) {
    detachInterrupt(digitalPinToInterrupt(risePin[5]));
    riseFin[5] = 1;
  }
}
void down_6 ()
{
  fall[5][countDown[5]] = ARM_DWT_CYCCNT;
  countDown[5] += 1;
  if (countDown[5] > 999) {
    detachInterrupt(digitalPinToInterrupt(fallPin[5]));
    fallFin[5] = 1;
  }
}
void up_7 ()
{
  rise[6][countUp[6]] = ARM_DWT_CYCCNT;
  countUp[6] += 1;
  if (countUp[6] > 999) {
    detachInterrupt(digitalPinToInterrupt(risePin[6]));
    riseFin[6] = 1;
  }
}
void down_7 ()
{
  fall[6][countDown[6]] = ARM_DWT_CYCCNT;
  countDown[6] += 1;
  if (countDown[6] > 999) {
    detachInterrupt(digitalPinToInterrupt(fallPin[6]));
    fallFin[6] = 1;
  }
}
void up_8 ()
{
  rise[7][countUp[7]] = ARM_DWT_CYCCNT;
  countUp[7] += 1;
  if (countUp[7] > 999) {
    detachInterrupt(digitalPinToInterrupt(risePin[7]));
    riseFin[7] = 1;
  }
}
void down_8 ()
{
  fall[7][countDown[7]] = ARM_DWT_CYCCNT;
  countDown[7] += 1;
  if (countDown[7] > 999) {
    detachInterrupt(digitalPinToInterrupt(fallPin[7]));
    fallFin[7] = 1;
  }
}

void setup ()
{
  ARM_DEMCR |= ARM_DEMCR_TRCENA;
  ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;
  Serial.begin(9600);
  pinMode (LED, OUTPUT);  // so we can update the LED
  attachInterrupt (digitalPinToInterrupt (risePin[0]), up_1, RISING);  // attach interrupt handler
  attachInterrupt (digitalPinToInterrupt (fallPin[0]), down_1, FALLING);  // attach interrupt handler
  attachInterrupt (digitalPinToInterrupt (risePin[1]), up_2, RISING);  // attach interrupt handler
  attachInterrupt (digitalPinToInterrupt (fallPin[1]), down_2, FALLING);  // attach interrupt handler
  attachInterrupt (digitalPinToInterrupt (risePin[2]), up_3, RISING);  // attach interrupt handler
  attachInterrupt (digitalPinToInterrupt (fallPin[2]), down_3, FALLING);  // attach interrupt handler
  attachInterrupt (digitalPinToInterrupt (risePin[3]), up_4, RISING);  // attach interrupt handler
  attachInterrupt (digitalPinToInterrupt (fallPin[3]), down_4, FALLING);  // attach interrupt handler
  /*attachInterrupt (digitalPinToInterrupt (risePin5), up_5, RISING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (fallPin5), down_5, FALLING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (risePin6), up_6, RISING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (fallPin6), down_6, FALLING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (risePin7), up_7, RISING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (fallPin7), down_7, FALLING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (risePin8), up_8, RISING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (fallPin8), down_8, FALLING);  // attach interrupt handler*/
}  // end of setup

void loop ()
{
  if ((riseFin[0] == 1) && (fallFin[0] == 1) && (riseFin[1] == 1) && (fallFin[1] == 1) && (riseFin[2] == 1) && (fallFin[2] == 1) && (riseFin[3] == 1) && (fallFin[3] == 1) ) {
    for (int ch = 0; ch < numCh; ch++) {
      digitalWrite(LED, HIGH);
      //print rises
      Serial.print(ch);
      Serial.println("rs");
      for (int i = 0; i < 900; i++) {
        Serial.println(rise[ch][i]);
      }
      //delay(1);
      Serial.print(ch);
      Serial.println("re");
      delay(1000);
      //print falls
      Serial.print(ch);
      Serial.println("fs");
      for (int i = 0; i < 900; i++) {
        Serial.println(fall[ch][i]);
      }
      //delay(1);
      Serial.print(ch);
      Serial.println("fe");
    }
    delay(1000);
    digitalWrite(LED, LOW);
    for (int i = 0; i < 8; i++) {
      countUp[i] = 0;
      countDown[i] = 0;
      riseFin[i] = 0;
      fallFin[i] = 0;
    }


    attachInterrupt (digitalPinToInterrupt (risePin[0]), up_1, RISING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (fallPin[0]), down_1, FALLING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (risePin[1]), up_2, RISING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (fallPin[1]), down_2, FALLING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (risePin[2]), up_3, RISING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (fallPin[2]), down_3, FALLING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (risePin[3]), up_4, RISING);  // attach interrupt handler
    attachInterrupt (digitalPinToInterrupt (fallPin[3]), down_4, FALLING);  // attach interrupt handler

  }
}

I should mention that this code actually works really well as is, im just trying to make it so that i can change the number of samples more easily and have the possibility to change to it on the fly (it communicates with a python script via serial, currently one way coms but the next version will hopefully do returns coms).

Thanks again everyone, i really appreciate your help

LOVE it !!!!

declare all your variables you use in interrupts as volatile.

if you set the limit in a variable and you want to modify the variable in the loop, then do so in a critical section (suspend interrupts).

if you do anything with data coming from the interrupts like this

if ((riseFin[0] == 1) && (fallFin[0] == 1) && (riseFin[1] == 1) && (fallFin[1] == 1) && (riseFin[2] == 1) && (fallFin[2] == 1) && (riseFin[3] == 1) && (fallFin[3] == 1) ) {

make a copy first of the data in a critical section, and work on the copy. Murphy's law guarantees that an interrupt will come and mess up some bytes (esp. when variables are not fitting on one byte) right in the middle of the maths...

change Serial.begin(9600);to something way faster, if you have too much data to print you'll fill up the outgoing buffer and that will slow down the loop

give it a try.

@J-M-L thanks for the info.
just to clarify - do you mean i should have all variables in my loop as volatile?
ie for the case below...
rise, countUp, riseFin should all be volatile?

Thanks again

I read a bit more your code and because you don't access the data until all the ISRs have been removed, you are almost OK. The only part that would require a critical section is how you test for completion since data can be changing as you proceed (but not generating bugs as you'll catch that at the next loop).

I had something like this in mind, totally untested ( typed here) to make the structure of the code more configurable (you have the 2 constants you can modify at the start of the code, pins are declared in the isrDefinition array).

May be that will help?

#include <assert.h>
const uint8_t activeChannelCount = 4;     // the number of interrupts you want to track, needs to be <= 8
const uint16_t maxSamples = 1000;         // the number of samples you want to collect

// the pins
const uint8_t ledPin = 13;

// forward declaration of the iSRs
void isrUP_0(); void isrDown_0();
void isrUP_1(); void isrDown_1();
void isrUP_2(); void isrDown_2();
void isrUP_3(); void isrDown_3();
void isrUP_4(); void isrDown_4();
void isrUP_5(); void isrDown_5();
void isrUP_6(); void isrDown_6();
void isrUP_7(); void isrDown_7();

// define an array of interrupts functions to make configuration easier
struct {
  const uint8_t risePin;
  const uint8_t fallPin;
  void (* isrRaise)();
  void (* isrFall)();
} isrDefinition[] = {
  { 0,  1, isrUP_0, isrDown_0},
  { 2,  3, isrUP_1, isrDown_1},
  { 4,  5, isrUP_2, isrDown_2},
  { 6,  7, isrUP_3, isrDown_3},
  { 8,  9, isrUP_4, isrDown_4},
  {10, 11, isrUP_5, isrDown_5},
  {12, 13, isrUP_6, isrDown_6},
  {14, 15, isrUP_7, isrDown_7},
};
const uint8_t isrDefinitionCount = sizeof isrDefinition / sizeof isrDefinition[0];

// Verification at compile time to ensure all is OK
static_assert((isrDefinitionCount >= activeChannelCount), "Not enough ISRs definitions");

//define logging arrays (not in the structure to avoid an extra indirection in the ISR)
volatile uint32_t riseChrono[isrDefinitionCount][maxSamples];
volatile uint32_t fallChrono[isrDefinitionCount][maxSamples];

// define counters arrays (not in the structure to avoid an extra indirection in the ISR)
volatile uint16_t hitCountRise[isrDefinitionCount];
volatile uint16_t hitCountFall[isrDefinitionCount];

// maintain the count of ISR that have completed their job
volatile uint8_t isrDoneCount = 0;


// establish correct environment
void configureISRs() {
  noInterrupts();
  isrDoneCount = 0;
  for (uint8_t i = 0; i < activeChannelCount; i++) {
    hitCountRise[i] = 0;
    hitCountFall[i] = 0;
    attachInterrupt(digitalPinToInterrupt(isrDefinition[i].risePin), isrDefinition[i].isrRaise, RISING);   // attach Rising  interrupt handler
    attachInterrupt(digitalPinToInterrupt(isrDefinition[i].fallPin), isrDefinition[i].isrFall,  FALLING);  // attach Falling interrupt handler
  }
  interrupts();
}

void setup ()
{
  // start the cycle counter
  ARM_DEMCR |= ARM_DEMCR_TRCENA;
  ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;
  
  pinMode (ledPin, OUTPUT);
  Serial.begin(115200);  // Serial monitor configured at 115200 bauds
  configureISRs();
}

void loop ()
{
  bool captureComplete;

  // critical section
  noInterrupts();
  captureComplete = (isrDoneCount >= 2 * activeChannelCount); // are all ISRs done ?
  interrupts();

  if (captureComplete) { // here we know all ISRs have been deactivated, no need for a critical section

    digitalWrite(ledPin, HIGH);
    for (int ch = 0; ch < activeChannelCount; ch++) {
      //print rises
      Serial.print(ch);
      Serial.println(F("rs"));
      for (uint16_t i = 0; i < maxSamples; i++) Serial.println(riseChrono[ch][i]);
      Serial.print(ch);
      Serial.println(F("rs"));

      //print falls
      Serial.print(ch);
      Serial.println(F("fs"));
      for (uint16_t i = 0; i < maxSamples; i++) Serial.println(fallChrono[ch][i]);
      Serial.print(ch);
      Serial.println(F("fe"));
    }
    digitalWrite(ledPin, LOW);

    // get ready for next round
    configureISRs();
  }
}


// ------ the interrupt Service Routines (ISR) ------
// could be done an easy way with #define, or lambda probably

inline void riseAction(const byte isrID) {
  riseChrono[isrID][hitCountRise[isrID]] = ARM_DWT_CYCCNT;
  if (++hitCountRise[isrID] >= maxSamples) {
    detachInterrupt(digitalPinToInterrupt(isrDefinition[isrID].risePin));
    isrDoneCount++;
  }
}

inline void fallAction(const byte isrID) {
  fallChrono[isrID][hitCountFall[isrID]] = ARM_DWT_CYCCNT;
  if (++hitCountFall[isrID] >= maxSamples) {
    detachInterrupt(digitalPinToInterrupt(isrDefinition[isrID].fallPin));
    isrDoneCount++;
  }
}

void isrUP_0()   {riseAction(0);}
void isrDown_0() {fallAction(0);}
void isrUP_1()   {riseAction(1);}
void isrDown_1() {fallAction(1);}
void isrUP_2()   {riseAction(2);}
void isrDown_2() {fallAction(2);}
void isrUP_3()   {riseAction(3);}
void isrDown_3() {fallAction(3);}
void isrUP_4()   {riseAction(4);}
void isrDown_4() {fallAction(4);}
void isrUP_5()   {riseAction(5);}
void isrDown_5() {fallAction(5);}
void isrUP_6()   {riseAction(6);}
void isrDown_6() {fallAction(6);}
void isrUP_7()   {riseAction(7);}
void isrDown_7() {fallAction(7);}

wow! thanks Jackson, thats incredible, it's abit above my code reading skills at the moment but will have a dig through it and give it a go asap.
really cant thank you enough for the work you put in there. fully above and beyond :smiley:

thank me if it works :wink: :innocent:
it's totally untested, I typed that here in the forum...

It wasn't clear in your snippet of code that the variables were global.