Reputation: 83
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 ;
}
Upvotes: 8
Views: 6541
Reputation: 1211
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.
Upvotes: 19