Jump to content


Silly simple Arduino hardware interrupts


Recommended Posts

Arduino  hardware (as opposed to timer) interrupts are incredibly easy to use... here's a very basic sketch to turn the LED on and off depending on the input to a particular digital input pin

The arduino Nano only has 2 interrupts , on digital pins 2 and 3 (other arduinos have more) but you can get the jist of  how useful they can be.

The two functions lightOn and lightOff can be triggered regardless of what is happening in the loop() function. as you can see, the digital inputs do not need to be constantly polled to check for input.

int button_interrupt_zero = 0; // interrupt on nano digital pin 2
int button_interrupt_one = 1; // interrupt on nano digital pin 3

const int ledPin =  13; // this is used purely as an input/activity indicator for buttons 1 - 3

void setup() 
  // initialize digital pin 13 as an input indicator.
  pinMode(ledPin, OUTPUT);

  // attachInterrupt( *which interrupt* , *function to run*, *mode*)
  attachInterrupt(button_interrupt_zero ,lightOn, RISING);
  attachInterrupt(button_interrupt_one ,lightOff, RISING);

void loop() 

void lightOn()
  digitalWrite(ledPin, HIGH);

void lightOff()
  digitalWrite(ledPin, LOW);

hope this is useful :)


  • Like 3
Link to comment
Share on other sites

+1 for Good Stuff.

At the risk of making it slightly less simple, you can actually use pretty much all the Arduino pins for interrupts, not just pins 2 and 3. These other interrupts, called Pin Change Interrupts, are slightly different in that they are triggered by each change of state on the pin, i.e. high TO low AND low TO high. Unlike the interrupts on pins 2 and 3, you can't specify rising edge, falling edge etc. Also, although pretty much all the pins will generate an interrupt, there are only a limited number of interrupt vectors, one vector for each port, so you may need extra code to work out which particular pin within a port caused the interrupt.

For sure, start with the 'easy' interrupts on pins 2 and 3 but if you do need more it is well worth the effort in learning how to use pin change interrupts. A very good introduction is http://gammon.com.au/interrupts

Or - use a Teensy 3.1 or 3.2 with an ARM M4 processor. Then all the pins have 'proper' interupts and you can use the Arduino 'attachInterrupt' method for any pin.

Regards, Hugh

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. By using this site, you agree to our Terms of Use.