attachInterrupt example not working on Arduino Nano

I tried to get the code provided on this page: attachinterrupt working on an Arduino Nano. Here is the code:

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;
}

I can build and upload it without a problem but nothing happens when I change the state of the interrupt pin (pin 2). What can be the possible causes and how can I get the interrupt working?
Thanks a lot for your help.

For informed help, please read and follow the instructions in the "How to get the best out of this forum" post.

I know it's not your fault as you copied this right from the official Arduino reference page, but that is some really CRAPPY code!

It has the loop() function looping away at full speed doing digital writes to ledPin regardless of whether or not the input pin changes. It might as well just poll the input pin in loop() and forget about using an interrupt.

Thanks, I know you can place code in the main loop or put a delay there but your reply does not solve my problem and has nothing to do with why i am not getting the interrupt pin to work.

I tried the code with an Uno and it "works". The interrupt will trigger on every change of state from the switch. Switch contacts bounce (lots of state changes). Switch bounce makes the outcome kind of random. You can help to mitigate bounce by putting a 0.1uF cap from the input to ground to add hardware debounce to the switch.

Please post a schematic or wiring diagram showing how the switch is connected. Photos of the wiring can also be helpful.

Hello fagenhauser

Welcome to the worldbest Arduino forum ever.

Consider this small modified sketch:

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()
{
  if (state == HIGH)
  {
    state = LOW;
    digitalWrite(ledPin, digitalRead(ledPin) ? LOW : HIGH);
  }
}
void blink()
{
  state = HIGH;
}

Have a nice day and enjoy coding in C++.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.