Arduino: Interrupts and Timers

Interrupts allow microcontrollers to response to events without having to poll continually to see if anything has changed. In addition to associating interrupts certain pins you can also use timer-generated interrupts. Let explore more on interrupts and timers here.

Hardware Interrupts

interrupting cartoon
interrupting cartoon
  1. Let look at an example to use interrupts, visit digital inputs.
  2. The common way to to detect when something has happened at the input is to use some code like this.
    • void loop {
      if digitalRead(inputPin) == LOW) { //do something } }
  3. This code means continually checking inputPin and it reads the LOW, whatever is specified a the //do something.
  4. However, if the loop has a lot of things to do, it takes time Potentially you will miss a very quick button press because processor is busy doing something else.
  5. For shorter pulses in milliseconds, you can use interrupts to catch such events, setting a function to run whenever these events happen.
  6. These are called hardware interrupts.
interrupt arduino cc
interrupt arduino cc

Arduino Hardware Interrupt

  1. In Arduino Uno, you can use two pins as hardware interrupts which is one reason they are used.
  2. Bigger boards have many more interrupt pins.
  3. Try breadboard with 1k ohm resistor and tactile push switch
  4. The resistor pulls the interrupt pin (D2) HIGH until the button on the switch is pressed at which point D2 is grounded and goes LOW.
  5. The attachInterrupt() function has three parameters: first is the interrupt pin converted to Interrupt using the digitalPinToInterrupt() function, second is the isr function named stuffHappened, and last is the mode which describes when the interrupt is triggered.
  6. Set to CHANGE which means the interrupt is triggered when the pin changes its state. Other possible options are:
    • LOW to trigger the interrupt whenever the pin is low
    • RISING to trigger when the pin goes from low to high
    • FALLING for when the pin goes from high to low
  7. There is no code in loop as we expect the program is triggered by the interrupts.
interrupt code1
interrupt code1
interrupt code2
interrupt code2

Finally, run the program and take a look a the serial monitor to see any interrupt is triggered by the toggle switch. Once the toggle switch is pressed, the LED light change from LOW to HIGH (light up). You have fun with the interrupts using Arduino board.

serial interrupt
serial interrupt

Take care and have a great day.

Leave a comment