8

I got some code from a student of mine who has recently started with arduino.

He tried to do an Interrupt and it sort of worked. The thing was that it ran twice (the function he called) so the booleans were reset.

I've tried to find answers but I couldn't find any, so here I am.

Please help me.

boolean state = 1 ;
void setup()

{
pinMode (2 , INPUT);
pinMode (8 , OUTPUT);
Serial.begin(38400);        
attachInterrupt( 0 , ngt, RISING);


}


void loop()

{

Serial.println (digitalRead(2));
digitalWrite ( 8 , state );
delay(50);

}

void ngt()
{

state = !state ;


}
2
  • What is the Arduino being interrupted by? Are you using a push button? Any sensor? Commented Apr 20, 2015 at 19:33
  • Yes exactly a pull down configuration of a fysical button Commented Apr 20, 2015 at 20:22

1 Answer 1

19

The problem you are having is because the button glitches are producing many interrupts on each button press. You can find a good description and a way of solving it using hardware here.

Let me explain, when you press the button, the mechanical contact will have a transcient state in which it will fluctuate ON-OFF for a short period of time. The same effect might happen when you release the button.

One way of solving this problem is using a capacitor parallel to the load. Another "easier" way would be done by software. The idea is to set a fixed arbitrary time in which you don't allow new interrupts. You could use the millis() or micros() library to set this time. The code would look something like this.

unsigned long lastInterrupt;

void ngt()
{

  if(millis() - lastInterrupt > 10) // we set a 10ms no-interrupts window
    {    

    state = !state;

    lastInterrupt = millis();

    }
}

This way you don't process new interrupts until 10ms have elapsed.

Note: adjust the time to your requirements.

2
  • 2
    this answer is actually worth much more upvotes that what it is given. Although it seems trivial and people with experience just know it, but in fact, it is not that easy to figure out when you face it for the first time. Especially if you already have experience in circuits and Arduino, but never tried to use switches with fast responses like interrupts.
    – himura
    Commented May 18, 2017 at 23:42
  • this answer was very much helpful. it solved the problem for me! Commented Mar 3, 2018 at 19:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.