/* Callback demo — hardware interrupt (Wokwi, Arduino Uno)
*
* A button on pin 2 fires a CALLBACK (an ISR) on every press. Notice: loop() never
* reads the button. The hardware "calls back" onPress() the instant the pin falls —
* that's the interrupt/callback pattern, vs. polling the pin on a schedule.
*
* Good practice shown: the ISR stays TINY (just flags the event); the real work
* happens back in loop(). Shared vars touched by the ISR are 'volatile'.
*
* Board: Arduino Uno. Pin 2 = INT0 (a dedicated interrupt pin). No library needed.
* Wiring: a pushbutton, one leg to D2, the diagonal leg to GND (uses internal pull-up).
*/
const int BTN = 2; // INT0-capable pin on the Uno
const int LED = LED_BUILTIN; // pin 13
volatile uint32_t pressCount = 0; // written by the ISR -> must be volatile
volatile bool pressed = false;
void onPress() { // <-- THE CALLBACK (interrupt service routine). Keep it tiny.
pressCount++;
pressed = true;
}
void setup() {
Serial.begin(9600);
pinMode(LED, OUTPUT);
pinMode(BTN, INPUT_PULLUP);
// Register the callback: call onPress() on a HIGH->LOW edge (button press).
attachInterrupt(digitalPinToInterrupt(BTN), onPress, FALLING);
Serial.println("Ready. Note: loop() is NOT polling the button.");
}
void loop() {
Serial.println("...loop doing its own thing...");
if (pressed) { // handle the event the callback flagged
pressed = false;
digitalWrite(LED, !digitalRead(LED));
Serial.print(" >> callback fired! count = ");
Serial.println(pressCount);
}
delay(500); // loop is slow on purpose — the callback still fires instantly
}