Consider this Arduino code snippet using an interrupt to count button presses. What will be printed to the serial monitor after pressing the button 3 times?
volatile int count = 0; void setup() { Serial.begin(9600); pinMode(2, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(2), incrementCount, FALLING); } void loop() { Serial.println(count); delay(1000); } void incrementCount() { count++; }
Interrupts update the count immediately when the button is pressed, so the main loop sees the updated value.
The interrupt function increments count each time the button is pressed. The main loop prints the current count every second. After 3 presses, count is 3, so the output stays at 3.
Why do interrupts help an Arduino respond faster to events compared to checking inputs inside the loop()?
Think about how the Arduino reacts when an event happens outside the normal loop.
Interrupts pause the main program and run special code immediately when an event occurs. This makes the Arduino respond faster than waiting for the loop to check inputs.
Look at this Arduino code. The count variable does not increase as expected when the button is pressed. What is the problem?
int count = 0; void setup() { Serial.begin(9600); pinMode(2, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(2), incrementCount, FALLING); } void loop() { Serial.println(count); delay(1000); } void incrementCount() { count++; }
Variables shared between interrupts and main code need special declaration.
The variable count is changed inside an interrupt and read in the main loop. It must be declared volatile so the compiler knows it can change anytime and does not optimize it away.
Choose the correct Arduino code to attach an interrupt on pin 3 that triggers on a rising signal.
Remember the correct order of parameters for attachInterrupt.
The correct syntax is attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);. Option C follows this exactly.
This Arduino code toggles an LED each time a button connected to pin 2 is pressed. The main loop runs a 5-second timer. How many times will the LED toggle if the button is pressed 4 times during those 5 seconds?
volatile int toggleCount = 0; const int ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); pinMode(2, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(2), toggleLED, FALLING); Serial.begin(9600); } void loop() { unsigned long start = millis(); while (millis() - start < 5000) { // wait 5 seconds } Serial.println(toggleCount); } void toggleLED() { digitalWrite(ledPin, !digitalRead(ledPin)); toggleCount++; }
Each button press triggers the interrupt once, toggling the LED and increasing the count.
The interrupt toggles the LED and increments toggleCount each time the button is pressed. Pressing 4 times means 4 toggles and count 4.