Example for attachInterrupt()

Hi!

IMO the example program for attachInterrupt() is suboptimal (if not wrong at all). I brushed it up a little bit:

int interruptPin = 2;
int LEDPin = 13;
volatile int state = LOW;

void setup() {
    pinMode(LEDPin, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(InterruptPin), blink, CHANGE);
}

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

void blink() {
    state = !state;
}

Maybe this one is less confusing :slight_smile:

Gregor

Is the original example really not wrong? I came here looking for clarification, as the original code reads:

int pin = 13;
volatile int state = LOW;

void setup() {
    pinMode(pin, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE);
}

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

void blink() {
    state = !state;
}

It uses the same pin, 13, both to drive the LED and to attach the interrupt. Isn't this an error?

Unless I'm mistaken, your code is correct while the original is indeed wrong.

I reported this error to the issue tracker: [Reference] attachInterrupt() example and documentation corrections · Issue #4723 · arduino/Arduino · GitHub

The example on the reference page has been corrected. Thanks for reporting this gregorss!