// Efficient Management of Interrupts and ISRs Demo for Wokwi
// Pin Definitions (referencing your diagram.json)
const int RED_LED_PIN = 7;
const int GREEN_LED_PIN = 6;
const int YELLOW_LED_PIN = 5; // Not used in this specific demo
const int PUSH_BUTTON_PIN = 8;
const int SERVO_PIN = 4; // Not used in this specific demo
// This flag is set by the ISR and read by the loop().
// 'volatile' is crucial: it tells the compiler that 'buttonPressed'
// can change unexpectedly (i.e., by the ISR) and should always be
// read from memory, not from a CPU register cache.
volatile bool buttonPressed = false;
// --- Interrupt Service Routine (ISR) ---
// This function is called immediately when the interrupt triggers.
// IRAM_ATTR places the ISR in Instruction RAM for faster execution.
void IRAM_ATTR buttonISR() {
// ISRs should be as short and fast as possible!
// Avoid Serial.print, delays, or complex calculations in an ISR.
// We only set a flag here. The main processing happens outside the ISR.
buttonPressed = true;
}
void setup() {
Serial.begin(115200); // Initialize serial communication
Serial.println("--- Demo 4: Efficient Management of Interrupts and ISRs ---");
// Initialize LED pins as outputs
pinMode(RED_LED_PIN, OUTPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
digitalWrite(RED_LED_PIN, LOW); // Ensure Red LED starts OFF
digitalWrite(GREEN_LED_PIN, LOW); // Ensure Green LED starts OFF
// Configure the pushbutton pin with an internal pull-up resistor.
// Since the button is wired to GND, pressing it will pull the pin LOW.
pinMode(PUSH_BUTTON_PIN, INPUT_PULLUP);
// Attach the interrupt to the button pin.
// digitalPinToInterrupt() converts the GPIO pin number to an interrupt number.
// buttonISR is the function that will be called when the interrupt triggers.
// FALLING means the interrupt triggers when the pin goes from HIGH to LOW (button pressed).
attachInterrupt(digitalPinToInterrupt(PUSH_BUTTON_PIN), buttonISR, FALLING);
Serial.println("Press the button to see the interrupt response!");
Serial.println("Green LED blinks to show the main loop is active.");
}
void loop() {
// --- Main Loop Activity (simulating other tasks) ---
// The Green LED blinks regularly to show that the main loop() is constantly running,
// doing its "other work" (even if it's just blinking).
digitalWrite(GREEN_LED_PIN, HIGH);
delay(100); // Small delay
digitalWrite(GREEN_LED_PIN, LOW);
delay(400); // More delay (total 500ms cycle)
// --- Checking the Interrupt Flag ---
// We check the 'buttonPressed' flag here. This code runs in the main loop,
// so it's safe to use Serial.print, delays, or more complex logic.
if (buttonPressed) {
Serial.println(">>> Button was PRESSED (detected by ISR)! <<<");
digitalWrite(RED_LED_PIN, HIGH); // Turn on Red LED to indicate the press
delay(1000); // Keep Red LED on for 1 second
digitalWrite(RED_LED_PIN, LOW); // Turn Red LED off
buttonPressed = false; // Reset the flag so it can be detected again
}
}