Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino AttachInterrupt() seems to run twice

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 ;


}
like image 566
Victor Lindholm Avatar asked Apr 20 '15 18:04

Victor Lindholm


People also ask

What does the Arduino function attachInterrupt () do when called?

This function is sometimes referred to as an interrupt service routine. mode : defines when the interrupt should be triggered. Four constants are predefined as valid values: LOW to trigger the interrupt whenever the pin is low, CHANGE to trigger the interrupt whenever the pin changes value.

What happens if two interrupts occur at the same time Arduino?

ArduinoTom: What happens if both external interrupts are triggered at the same time? The interrupt with the higher priority runs first.

How many interrupts Arduino Mega 2560?

The Arduino Mega has six hardware interrupts including the additional interrupts ("interrupt2" through "interrupt5") on pins 21, 20, 19, and 18. You can define a routine using a special function called as “Interrupt Service Routine” (usually known as ISR).

How many interrupts can Arduino handle?

There are only two external interrupt pin in arduino uno.


1 Answers

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.

like image 115
eventHandler Avatar answered Oct 10 '22 05:10

eventHandler