Consider the following Arduino code with an ISR that increments a counter. What will be printed to the serial monitor?
volatile int counter = 0; void setup() { Serial.begin(9600); attachInterrupt(digitalPinToInterrupt(2), incrementCounter, RISING); } void loop() { Serial.println(counter); delay(1000); } void incrementCounter() { counter++; }
Think about how often the interrupt triggers and how the counter variable is updated.
The ISR increments the counter every time the interrupt triggers on pin 2's rising edge. If the signal on pin 2 is fast or noisy, the counter will increase rapidly. The loop prints the current counter value every second, so you will see large numbers increasing quickly.
In Arduino programming, why is it important to declare variables shared between an ISR and the main program as volatile?
Think about how the compiler might optimize variables that seem unchanged in the main code.
The volatile keyword tells the compiler that the variable can change unexpectedly, such as inside an ISR. Without it, the compiler might cache the variable in a register and not see updates made by the ISR, causing incorrect behavior.
Examine the following ISR code. What issue might cause unexpected behavior?
volatile int count = 0; void setup() { attachInterrupt(digitalPinToInterrupt(3), countUp, FALLING); } void loop() { // main code } void countUp() { count += 2; delay(10); }
Consider what functions are safe to use inside an ISR.
Using delay() inside an ISR is unsafe because it relies on interrupts and timers that are disabled during ISR execution. This can cause the program to freeze or behave erratically.
Which of the following ISR function declarations is syntactically correct for Arduino?
Think about the standard function declaration syntax in Arduino C++.
In Arduino, ISR functions must be declared as void and take no parameters. The syntax void ISR_handler(void) is correct. The interrupt keyword is not used in Arduino. Returning a value or using other keywords causes errors.
You have a 16-bit volatile variable volatile uint16_t sensorValue; updated inside an ISR and read in the main loop. How should you safely read sensorValue in the main loop to avoid corrupted data?
Think about atomicity when reading multi-byte variables shared with ISRs.
Multi-byte variables like 16-bit integers can be corrupted if an interrupt occurs during reading. To avoid this, disable interrupts before reading the variable and re-enable them after. Declaring volatile alone does not guarantee atomic access.