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 ;
}
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.
ArduinoTom: What happens if both external interrupts are triggered at the same time? The interrupt with the higher priority runs first.
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).
There are only two external interrupt pin in arduino uno.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With