How to use attachInterrupt() in Arduino IDE to toggle an LED

Posted

in

by

Arduino, with its user-friendly environment and a vast array of libraries, opens up a world of possibilities for electronic enthusiasts and hobbyists. One of the key features that makes Arduino a versatile platform is the ability to use interrupts. In this blog post, we will explore the use of attachInterrupt() in the Arduino IDE to toggle an LED with the press of a button.

Understanding attachInterrupt()

The attachInterrupt() function in Arduino is a powerful tool that allows you to execute a specified function (interrupt service routine or ISR) when a certain condition occurs on a digital pin. This capability is particularly useful for handling external events without constantly polling the pin in the main loop, thus improving efficiency and responsiveness.

For more documentation visit the lin below.

https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

Components Required

Before we delve into the code, let’s gather the necessary components for this project:

  1. Arduino board (e.g., Arduino Uno)
  2. LED
  3. Resistor (220-330 ohms)
  4. Push button
  5. Jumper wires

Wiring the Circuit

Connect the components as follows:

  • Connect the longer leg of the LED (anode) to a current-limiting resistor (220-330 ohms) then the other end of the resistor to pin A2 on the Arduino.
  • Connect the shorter leg of the LED (cathode) GND on the Arduino.
  • Connect one side of the push button to pin 2 on the Arduino.
  • Connect the other side of the push button to the GND on the Arduino.

The Arduino Sketch

Now, let’s dive into the Arduino sketch that utilizes attachInterrupt() to toggle the LED state when the button is pressed.


int led=A2;
int button=2;
volatile byte state = LOW;

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2),blink,CHANGE);
}

void blink()
{
  state = !state;
}

void loop()
{
  digitalWrite(led, !state);
}

Breaking Down the Code

  • We define led and button as the respective pin numbers for the LED and the push button.
  • volatile byte state is a variable that holds the state of the LED, and it’s marked as volatile to indicate that it can be modified in an ISR.
  • In the setup() function, we set the LED pin and button pin modes. Additionally, we attach an interrupt to the button using attachInterrupt(), specifying the function blink to be executed on a state change (CHANGE) of the button pin.
  • The blink() function toggles the state variable when the interrupt is triggered.
  • In the loop() function, we continuously update the LED state based on the value of the state variable.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *