reference-en icon indicating copy to clipboard operation
reference-en copied to clipboard

Add note re: contact bounce to `attachInterrupt` reference

Open per1234 opened this issue 6 years ago • 4 comments

Moved from https://github.com/arduino/Arduino/issues/8711 by @Omar-alSuntawi

This code does not work correctly !

const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {
  digitalWrite(ledPin, state);
}

void blink() {
  state = !state;
}

which is on the Arduino Reference https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

It seems to accidentally read random values.

per1234 avatar Mar 27 '19 21:03 per1234

I suspect that you are triggering the interrupt with something that has contact bounce, resulting in multiple interrupt triggers in very rapid succession and thus a random LED state for each press of the button. This could be be resolved by adding some debouncing code to the example, but I'm not sure whether this would be a good thing. The example is intended to be a simple demonstration of how to use attachInterrupt(). Debounce code has nothing to do with attachInterrupt().

I suppose an alternative that doesn't add any significant irrelevant code to the example would be to set the LED pin to mirror the state of the interrupt pin:

const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = HIGH;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {
  digitalWrite(ledPin, state);
}

void blink() {
  state = digitalRead(interruptPin);
}

That will not be visibly affected by contact bounce, but it's not a very interesting demonstration of the use of interrupts.

per1234 avatar Mar 27 '19 21:03 per1234

Perhaps the attachInterrupt page could mention the Bounce library and specifically recommend not using interrupts for pushbuttons, switches and other mechanisms that suffer from mechanical chatter? This seems to be a very common misunderstanding among novices. The documentation could really do much better to guide users towards the proper approach to meet their needs.

PaulStoffregen avatar Mar 27 '19 23:03 PaulStoffregen

I submitted a pull request. Hopefully it will help others avoid this common misunderstanding.

https://github.com/arduino/reference-en/pull/576

PaulStoffregen avatar Mar 28 '19 00:03 PaulStoffregen

@per1234 Along with this Issue, I am trying out all the examples mentioned on the Reference Pages with help of my Arduino Uno Board and other specifications necessary and will be happy to report any issue with any present example that will need an update or correction.

animeshsrivastava24 avatar Jun 05 '19 12:06 animeshsrivastava24