Consider this Arduino code that uses an interrupt to detect a button press. What will be printed to the serial monitor when the button is pressed?
volatile bool buttonPressed = false; void setup() { Serial.begin(9600); pinMode(2, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(2), buttonISR, FALLING); } void loop() { if (buttonPressed) { Serial.println("Button pressed!"); buttonPressed = false; } } void buttonISR() { buttonPressed = true; }
Think about what happens inside the interrupt and how the main loop reacts.
The interrupt sets buttonPressed to true once per button press. The main loop detects this and prints the message once, then resets the flag. This prevents continuous printing.
In interrupt-driven button handling, why is the volatile keyword used for variables shared between the ISR and the main code?
Think about how the compiler might optimize code if it assumes a variable never changes.
The volatile keyword tells the compiler the variable can change at any time, such as inside an ISR, so it must always read its current value from memory and not optimize it away.
Examine this Arduino code snippet. Why does it cause the program to crash or behave unpredictably?
volatile int count = 0; void setup() { pinMode(2, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(2), incrementCount, FALLING); Serial.begin(9600); } void loop() { Serial.println(count); delay(1000); } void incrementCount() { count++; delay(10); }
Think about what functions are safe to call inside an ISR.
Using delay() inside an ISR is unsafe because it relies on interrupts and timers that are disabled during ISR execution, causing the program to hang or crash.
Choose the correct Arduino code line to attach an interrupt to pin 3 that triggers on the FALLING edge.
Remember the correct way to convert a pin number to an interrupt number.
The function digitalPinToInterrupt(pin) converts a pin number to the correct interrupt number. The mode must be FALLING. Options B and C use wrong parameters, D uses an invalid mode.
This Arduino code toggles an LED each time a button connected to pin 2 is pressed using an interrupt. How many times will the LED state change after 5 distinct button presses?
volatile int pressCount = 0; void setup() { pinMode(2, INPUT_PULLUP); pinMode(13, OUTPUT); attachInterrupt(digitalPinToInterrupt(2), countPress, FALLING); } void loop() { static int lastCount = 0; if (pressCount != lastCount) { digitalWrite(13, !digitalRead(13)); lastCount = pressCount; } } void countPress() { pressCount++; }
Each button press increments the count and triggers a toggle in the main loop.
Each press increments pressCount. The loop detects the change and toggles the LED once per press. So after 5 presses, the LED toggles 5 times.