This program counts how many times a button connected to pin 2 is pressed. The ISR countPress runs quickly on each press. The main loop prints the count when it changes.
volatile int flag = 0;
void setup() {
attachInterrupt(digitalPinToInterrupt(3), toggleFlag, FALLING);
}
void loop() {
if(flag) {
// do something
flag = 0;
}
}
void toggleFlag() {
flag = !flag;
}
medium
A. Not declaring 'flag' as volatile
B. Missing Serial.begin() in setup
C. Incorrect interrupt mode FALLING
D. Using non-atomic operation on 'flag' inside ISR
Solution
Step 1: Analyze ISR operation on 'flag'
The ISR toggles 'flag' using '!flag', which is a read-modify-write operation and not atomic.
Step 2: Understand atomicity importance
Non-atomic operations on shared variables can cause race conditions and unpredictable behavior.
Final Answer:
Using non-atomic operation on 'flag' inside ISR -> Option D
Quick Check:
ISR must avoid non-atomic variable changes [OK]
Hint: Avoid read-modify-write on shared vars in ISR [OK]
Common Mistakes:
Ignoring atomicity of operations
Thinking volatile alone fixes all issues
Confusing interrupt mode with logic error
5. You want to count button presses using an ISR on pin 2. Which approach best follows ISR best practices in Arduino?
hard
A. Increment a volatile counter in ISR; read and reset it safely in loop
B. Print a message directly inside the ISR using Serial.println()
C. Use delay() inside ISR to debounce the button
D. Declare the counter as static inside ISR without volatile
Solution
Step 1: Review ISR best practices for counting events
ISRs should be short and only update volatile variables; printing or delays inside ISR are bad.
Step 2: Evaluate each option
Increment a volatile counter in ISR; read and reset it safely in loop uses a volatile counter incremented in ISR and safely handled in loop, which is correct.
Final Answer:
Increment a volatile counter in ISR; read and reset it safely in loop -> Option A
Quick Check:
Keep ISR short; update volatile vars only [OK]
Hint: Update volatile counter in ISR; handle logic outside [OK]
Common Mistakes:
Using Serial.print inside ISR causing delays
Using delay() inside ISR causing blocking
Not declaring shared variables volatile
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.