Interrupt still happening after detached. ( fix now available)

I have reproduced it on a Uno.

Extensive reading and testing seems to indicate what the problem is. Rather bizarrely the processor, when attachInterrupt is called, can "remember" whether the interrupt condition has already been met. Hence, if you ground the pin, and then call attachInterrupt, the interrupt fires.

This proves it:

volatile int flag = 0;

void setup() {
  Serial.begin (115200);
  digitalWrite(2, HIGH);      //pullup 2

  pinMode(13, OUTPUT);       //LED
  Serial.println ("go!");
  digitalWrite(13, HIGH);                 //time to go!
  delay (5000);
  digitalWrite(13, LOW);                 //time is up!
  
   // interrupt on
  attachInterrupt(0, isr0, FALLING);     //enable interrupt

  // did we get an interrupt?
  Serial.println (flag, DEC);
  }

void loop() {}

void isr0 () {
  flag = 1;
}

There is no detachInterrupt there. After the sketch starts and displays "go" you have 5 seconds to ground (and release) pin 2. If you do, and only if, then it displays 1, otherwise it displays 0. And this is despite the fact that you generate the "interrupt" before interrupts are enabled on that pin.

Now, add this line just before attaching the interrupt:

EIFR = 1;

That clears the interrupt flag (for interrupt 0). According to the datasheet:

The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it.

So this is manually clearing the "I saw an interrupt" flag, before enabling interrupts.

Arguably, attachInterrupt should do this. And note that detachInterrupt has no effect on the flag at all.

I don't know whether there would be programs around that rely on interrupts being "pre-triggered" before you even attach the interrupt. Perhaps there are.

Note that if you are using interrupt 1, it would be:

EIFR = 2;