Understanding the Arduino Interrupt Function with Button and LED
In Arduino programming, the interrupt
function allows the microcontroller to momentarily pause its main program to respond to an important event. This event could be a button press, a sensor trigger, or a timer overflow. The special function that runs during this pause is called an Interrupt Service Routine (ISR).
How Interrupts Work
- Think of interrupts as alarms that demand the processor’s immediate attention.
- When an interrupt occurs, the Arduino stops what it’s doing, saves its progress, and executes the ISR.
- After the ISR finishes, the Arduino resumes its normal tasks exactly where it left off.
Key Points About Arduino Interrupts
-
Pin-Based Interrupts
- Arduino boards support hardware interrupts on specific pins.
- On an Arduino Uno, interrupts are available on pins 2 and 3.
- Other boards may support interrupts on more pins.
-
Attaching an Interrupt
Use the
attachInterrupt()
function:attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);
- pin: Pin number to monitor.
- ISR: The function to execute when the event occurs.
- mode: Condition to trigger the interrupt:
LOW
: Trigger when pin is LOW.CHANGE
: Trigger on any change in pin state.RISING
: Trigger on LOW to HIGH change.FALLING
: Trigger on HIGH to LOW change.
-
Disabling Interrupts
Use
detachInterrupt(interruptNumber)
to stop an interrupt. -
ISR Best Practices
- Keep the ISR short and efficient.
- Do not use
delay()
or Serial communication inside an ISR. - Use
volatile
variables for shared data between ISR and main program.
Example Project: Button Interrupt Controlling an LED
#define LED_PIN 13 // LED connected to pin 13
#define BUTTON_PIN 2 // Button connected to pin 2 (interrupt pin)
volatile bool ledState = false; // Track LED state
void setup() {
pinMode(LED_PIN, OUTPUT); // Set LED pin as output
pinMode(BUTTON_PIN, INPUT_PULLUP); // Button with pull-up resistor
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), toggleLED, FALLING); // Trigger on button press
}
void loop() {
// Main loop is empty; LED is handled by interrupt
}
void toggleLED() {
ledState = !ledState; // Toggle LED state
digitalWrite(LED_PIN, ledState); // Update LED
}
Project Link: Download Project Files
0 Comments