Using detachInterrupt() inside ISR

I hope everyone's having a good new year's weekend. :smiley: My question: Is it safe to use detachInterrupt(X) at the end of interrupt(X)? The reason I want to detach before exiting the ISR is because I'm using the ISR to send the code into a loop until a certain event happens and I don't want the interrupt to happen while in that loop. Does this make sense? If anyone knows of any links to such info or has any advice on doing this I would be gratefull for your input.

Thanks to all,
DigitalJohnson

I think yes, never done it. But I have read about people doing this to implement button de-bouncing on an interrupt driven button.

Thanks pYro_65 for your reply. I'm going to go ahead and try this and do a little testing and see if I get any ill effects. I'll post here on this thread with my results in case anyone else is interested in doing this. If anyone knows of any "possible" side effects or dangers of doing this, please chime in. I always like to learn. Even the obscure information about rare cases interest me. Thanks again to everybody here in the forum for your help, past, present and future. :slight_smile:

DJ

I've done it, it's fine. ISRs are not magical beings; the registers are only looked at when the pin changes.

An alternative is to have a (volatile) flag in your main application that is checked by your ISR. There might be things that you still want to be done (e.g. increasing a counter), and other that are conditional. something like below

volatile bool flag;
void isr()
{
  // do allowed things
  if (flag) 
  {
    // do conditional isr things
  }
}

loop()
{
  flag = true;
  // code
  flag = false;
  // more code
}

Thanks for your replies guys.

@robtillaart

Wouldn't the flag only need to be volatile if the ISR changed the flag's state?

DJ

Wouldn't the flag only need to be volatile if the ISR changed the flag's state?

Sure. But the only reason for having the flag is so that the ISR can change its state.

@PaulS

I agree. I usually have an isr set a flag to signal some action to be dealt with in the main loop or by an outside function call, to keep the isr short and simple. I only asked because in robtillaart's example, it's the other way around. The flag is changed in loop() and the isr checks the state of the flag. Am I correct, that in this case the flag does not have to be declared as volatile, because the isr does not change it? I just want to be sure I'm uderstanding the use of "volatile" and weather or not it needs to be used in cases where the variable is not being modified by the isr. Also, I have another question (only for learning's sake). Are there any other times when a variable needs to be declared volatile, other than when it's shared within an isr?

Thanks for your replies, and your time.
DJ

The volatile keyword tells the compiler that it can not optimize away any reads of the value. If the ISR reads the value into a register, the compiler could optimize the code to not actually read the value again.

The volatile keyword tells the compiler to not do this. It doesn't matter whether it is the ISR that can change the value, or the non-interrupt based code that can change the value.

So this only applies to variables shared with an ISR because program is not aware if an interrupt has changed it's value or not? And that's why even though global variables are shared among all functions in the program, the ISR is not part of the program, but an interruption of the program. Where one is not aware of the changes made by the other. Is this correct?

Thanks PaulS, for your time and explaination of this. It's helped me understand a little more on this.
DJ

DigitalJohnson:
Also, I have another question (only for learning's sake). Are there any other times when a variable needs to be declared volatile, other than when it's shared within an isr?

You might make a variable volatile in a timing loop, otherwise code like this might not work:

for (int i = 0; i < 30000; i++)
  { } // waste time

The compiler might think "oh that never gets used" and optimise the whole loop away.

Is it safe to use detachInterrupt(X) at the end of interrupt(X)?

Yes it is safe, and indeed good practice in some cases. For example a LOW interrupt keeps firing continuously while the (relevant) pin is low. To not detach the interrupt from within the ISR leaves you open to the program running extremely slowly.

Thanks Nick, those are useful tips to keep in mind. What I'm getting from these repies is that the use of volatile has a couple purposes. 1) to make sure a variable is re-read upon each use. 2) To make sure the compiler doesn't optimize away the variable. If this is correct then I think I understand when it's use is called for.

Thanks very much for everyones replies. :slight_smile: To take a qoute from south park, "I think I've learned something here today". :wink:
DJ

While declaring variables shared between the (main) loop and and ISR as 'volatile' is necessary, it is not sufficient in the general case: care must also be taken to avoid race conditions, ie. uncontrolled access to such shared variables by the two threads of control, loop() and ISR, resulting in data and behaviour inconsistencies.

To make an overly simple example:

volatile uint16_t ctr = 0xFFFF;

ISR(SOME_vector) {
  ctr--;
}

void loop() {
  // do stuff

  if (ctr == 0xFFF) {
    // handle case
  }

  // do more stuff
}

is calling for trouble, as the 16-bit value can not be handled in atomic fashion on an 8-bit CPU as use on the Arduino. So it could happen that the compare operation (ctr == 0xFF) in loop() get's interrupted by the ISR, doing the decrement (ctr--), then loop() continues its comparison...

loop() could temporarily disable the interrupts with cli() and sei():

#include <avr/interrupt.h>

void loop() {
  // do stuff

  cli();  // disable all interrupts
  if (ctr == 0xFFF) {
    // handle case
  }
  sei();  // enable interrupts

  // do more stuff
}

but this is dangerous as well, as sei() will forcibly enable the interrupts, but they might have been disabled in another location in the code (consider a somewhat more complex program than the above...), hence just enabling them might result in unexpected behavior.

What you find in the Arduino libs (eg. in digitalWrite()) is something along these lines to overcome this issue:

#include <avr/interrupt.h>

#uint8_t _SREG;

void loop() {
  // do stuff

  _SREG = SREG;  // save the current (interrupt) state
  cli();
  if (ctr == 0xFFF) {
    // handle case
  }
  SREG = _SREG; // restore (interrupt) state

  // do more stuff
}

Better. However, when the ISR is triggered right after the saving the state (_SREG = SREG) and disabling interrupts, we have the inconsistency issue again.

So what the AVR library provides and recommends, is using a macro to define atomic blocks like so:

#include <avr/atomic.h>

volatile uint16_t ctr = 0xFFFF;

ISR(SOME_vector) {
  ctr--;
}

void loop() {
  // do stuff
  
  ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
    if (ctr == 0xFFF) {
      // handle case
    }
  }

  // do more stuff
}

which will handle the issue properly, ie. disabling interrupts as well as restoring the previous state. Of course, if handling the case in loop() takes too long with interrupts disabled, you'd make local copies of the shared variables in the atomic section, leave the atomic section, and handle the case outside.

See http://www.nongnu.org/avr-libc/user-manual/index.html for more info and more possibilities.

sbr_:
Better. However, when the ISR is triggered right after the saving the state (_SREG = SREG) and disabling interrupts, we have the inconsistency issue again.

I seem to recall having this discussion a while back. I don't think this is correct. After all:

  • A. Interrupts are effectively atomic. That is, they restore the registers to how they were before (if written correctly).
  • B. They cannot fire if interrupts are disabled.

Assuming interrupts are on:

At the point between saving the register, and clearing the interrupt mask, interrupts are enabled, which is what the mask was saved as. At the precise moment that interrupts are disabled, the ISR cannot fire, thus we no longer have to worry about what the interrupt routine does.

Assuming interrupts are off:

The ISR cannot fire, and thus there is no race condition.


I agree with your first point - checking volatile data, which may be changed inside an interrupt, and which is more than one byte long, may lead to inconsistencies. One workaround, which avoids setting and clearing interrupts yourself, is to have the interrupt routine set a single byte flag (which has to be atomic). Prior to setting the flag it changes such multi-byte variables as it needs to. Broadly speaking you could do something like this:

volatile int some_data;
volatile long other_data;
volatile boolean interrupt_fired;

void myISR ()
{
// check last interrupt was handled by main loop
if (interrupt_fired)
  return;
  
// set multi-byte variables 
some_data = 0x1234;
other_data = 0x567890;

interrupt_fired = true;  
} // end of myISR

void setup ()
  {
  Serial.begin (115200);
  attachInterrupt (0, myISR, FALLING);
  }  // end of setup
  
void loop ()
  {
  // if interrupt happened, access the changed variables
  if (interrupt_fired)
    {
    Serial.println (some_data);
    Serial.println (other_data);
    interrupt_fired = false;  // we are ready for another interrupt 
    }
  }  // end of loop

I used something similar when processing a rotary encoder interrupt. This general concept is pretty safe, and avoids mucking around setting and clearing interrupts, and remember if they are set or clear.

The reason why some routines (eg. millis() ) has to do the stuff about saving the flags and restoring them, is that they can't be sure that people will use the "interrupt flag" (and in fact there is no provision for such a flag).

What if the ISR kicks in exactly after SREG was saved, but before cli() disables interrupts?

What does it matter? The interrupt routine is itself atomic, that is it restores the register to what it was the moment the ISR was entered. So from the point of the "main" code (outside the ISR) the register is saved, it does stuff, it restores it.

Agreed. But at times things ain't as simple. Look at your IC2 slave example in Gammon Forum

// Written by Nick Gammon
// September 2011

#include <Wire.h>

#define MY_ADDRESS 100

char buf [1000];
volatile int inpoint, outpoint;

void setup (void)
{
  Serial.begin (115200);   // debugging

  Serial.println ();
  Serial.println ("Commencing debugging session ...");
  Serial.println ();

  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);

}  // end of setup


void receiveEvent (int howMany)
{
  while (Wire.available () > 0)
  {
    char c = Wire.receive ();
    int next = inpoint + 1;  // next insert point

    // wrap-around at end of buffer
    if (next >= sizeof buf)
      next = 0;

    if (next == outpoint)  // caught up with removal point?
      continue;  // give up

    // insert at insertion point
    buf [inpoint] = c;
    inpoint = next;  // advance to next
  }  // end of while available
}  // end of receiveEvent


void loop (void)
{
  // insertion and removal point the same, nothing there
  if (outpoint == inpoint)
    return;

  // display anything found in the circular buffer
  Serial.print (buf [outpoint++]);
  if (outpoint >= sizeof buf)
    outpoint = 0;  // wrap around

}  // end of loop

You don't want the receiveEvent() (which is called by an ISR) routine disabled during printing in loop(), in order not to lose data (after all, the circular buffer serves that purpose). 'inpoint' and 'outpoint' are 16 bit variables, and 'inpoint' could change during the 'if (outpoint == inpoint)' test. No?

(No finger-pointing here. It's a true question based on my interest in the matter. Maybe I got that wrong!)

The ISR could have changed state of affairs, and then you're restoring the wrong interrupt status later.

How could it have done this? By definition almost, if the ISR is entered, then interrupts are enabled. So between the lines:

  _SREG = SREG;  // save the current (interrupt) state
  cli();

... interrupts are not going to be disabled. If they were enabled anyway, then the ISR might fire. If not, it won't. Either way, what was saved will be correct.

Can't an ISR disable interrupts?