/* * Lab 1 - Task 4: External Interrupts & Timer Events
* Objective: Use a button interrupt to change the timer blink rate.
*/
const int buttonPin = 4; // Button connected to GPIO 4 (Pull-up)
const int ledPin = 2; // LED connected to GPIO 2
hw_timer_t * timer = NULL; // Timer pointer
volatile bool ledState = false; // State of the LED
volatile bool fastBlink = false; // Flag to track blink mode
// 1. Timer Interrupt Service Routine (ISR)
void IRAM_ATTR onTimer() {
ledState = !ledState; // Toggle LED state
digitalWrite(ledPin, ledState);
}
// 2. External GPIO Interrupt Service Routine (ISR)
void IRAM_ATTR onButtonPress() {
fastBlink = !fastBlink; // Toggle the blink mode flag
if (fastBlink) {
// Set timer to trigger every 200,000 microseconds (0.2 seconds = Fast)
timerAlarm(timer, 200000, true, 0);
} else {
// Set timer to trigger every 1,000,000 microseconds (1 second = Normal)
timerAlarm(timer, 1000000, true, 0);
}
}
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT); // Using external pull-up resistor
// Initialize the Hardware Timer (1 MHz frequency)
timer = timerBegin(1000000);
timerAttachInterrupt(timer, &onTimer);
timerAlarm(timer, 1000000, true, 0); // Start with 1 second alarm
// Initialize External Interrupt on the Button Pin
// digitalPinToInterrupt() ensures the correct mapping for the ESP32
// FALLING edge triggers the interrupt when voltage goes from HIGH (3.3V) to LOW (GND)
attachInterrupt(digitalPinToInterrupt(buttonPin), onButtonPress, FALLING);
Serial.println("Task 4 Ready: Press button to change blink rate.");
}
void loop() {
// Main loop remains empty. Everything is handled by interrupts!
}