Problem with deep sleep and wake up interrupt

I have a project which uses deep sleep to save battery.

The wake up is triggered by an interrupt (falling edge on pin 2). It works ok but I discovered that if pin 2 is down (LOW) in the moment the processor goes to sleep, the wake up is never triggered.

I solved the problem by checking the pin is HIGH before seeping, but I think there must be a better solution.

void pin2_isr(){
  sleep_disable();
  detachInterrupt(0);
}

void gotosleep(){

  //ADDED FOR AVOIDING PROBLENM WITH WAKEUP
     while(digitalRead(2)==LOW)    delay(500);

     attachInterrupt(0,pin2_isr,LOW);
     set_sleep_mode(SLEEP_MODE_PWR_DOWN);
     cli();
     sleep_enable();

     sei();
     sleep_cpu();

//////// afeter wake up

     sleep_disable();
     detachInterrupt(0);
     Serial.println("encendido");
     Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
     tone(BUZZER,880,10);
     delay(100);
     while(kpd.getKey());
     delay(100);
     memchr(s,sizeof(s),'\0');
}
     while(digitalRead(2)==LOW)    delay(500);

Why do you have to do anything when the pin is LOW? Certainly, delay() is not the thing to do.

PaulS:

     while(digitalRead(2)==LOW)    delay(500);

Why do you have to do anything when the pin is LOW? Certainly, delay() is not the thing to do.

This is what I'm asking. Describing the situation: I have a pushbutton connected to pin2 and GND. I've activated the pin2 pullup. When you push the button, the program plays a tone and calls the "gotosleep" function. When you press again the button, the sywtem wakes up. All ok until now.

The problem: if you press the button and keeps it pressed, the processog goes to sleep but you can never wake up it again, even pressing the button.

I added this line to avoid it and it works, but I think it should be a better solution. A key bounce could produce the same situation and other sensor input could produce the same problem. Then, I want to find a better solution for the future.

I added this line to avoid it and it works, but I think it should be a better solution.

     while(digitalRead(2)==LOW)
{
  // Doing nothing
}

PaulS:

I added this line to avoid it and it works, but I think it should be a better solution.

     while(digitalRead(2)==LOW)

{
  // Doing nothing
}

Ah! I added the delay for avoiding contact bounces. Otherwise, the digitalRead could read a HIGH value but some microseconds later the value could be LOW and produce the described problem.

Ah! I added the delay for avoiding contact bounces.

If you have a switch that bounces for half a second, throw it away.

PaulS:

Ah! I added the delay for avoiding contact bounces.

If you have a switch that bounces for half a second, throw it away.

Ok, it could be less time, but I think a delay is needed.