0
0
Arduinoprogramming~30 mins

attachInterrupt() function in Arduino - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the attachInterrupt() Function in Arduino
📖 Scenario: You are building a simple Arduino project where a button press triggers an immediate action without waiting for the main loop. This is useful for reacting quickly to events like button presses or sensor signals.
🎯 Goal: Create an Arduino sketch that uses the attachInterrupt() function to detect a button press on pin 2 and toggle an LED on pin 13 each time the button is pressed.
📋 What You'll Learn
Create a variable to store the LED pin number (13).
Create a variable to store the button pin number (2).
Set the LED pin as output and the button pin as input in setup().
Use attachInterrupt() to call an interrupt service routine when the button is pressed.
In the interrupt service routine, toggle the LED state.
Print the LED state to the Serial Monitor each time it changes.
💡 Why This Matters
🌍 Real World
Interrupts are used in real devices to react quickly to events like button presses, sensor signals, or communication data without waiting for the main program loop.
💼 Career
Understanding interrupts is important for embedded systems programming, robotics, and hardware interfacing jobs where timely responses to hardware events are critical.
Progress0 / 4 steps
1
Set up LED and button pins
Create two integer variables called ledPin and buttonPin with values 13 and 2 respectively. In the setup() function, set ledPin as an output and buttonPin as an input.
Arduino
Need a hint?

Use pinMode() inside setup() to set the pin modes.

2
Create variables for LED state and interrupt setup
Create a boolean variable called ledState and set it to false. In the setup() function, initialize serial communication at 9600 baud using Serial.begin(9600);.
Arduino
Need a hint?

Use Serial.begin(9600); to start serial communication.

3
Attach interrupt and write ISR to toggle LED
Write an interrupt service routine function called toggleLED() that toggles the ledState variable and sets the ledPin output accordingly. In the setup() function, use attachInterrupt() with interrupt number digitalPinToInterrupt(buttonPin), the function toggleLED, and mode RISING to detect button presses.
Arduino
Need a hint?

Use attachInterrupt(digitalPinToInterrupt(buttonPin), toggleLED, RISING); inside setup().

4
Print LED state changes in loop
In the loop() function, print the current LED state as "LED is ON" or "LED is OFF" to the Serial Monitor whenever the state changes. Use a static variable to track the previous state and only print when the state changes.
Arduino
Need a hint?

Use a static variable inside loop() to detect changes in ledState and print accordingly.