Consider this Arduino sketch using the TimerOne library to toggle an LED every 1 second. What will be printed on the Serial Monitor?
volatile bool ledState = false; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); Timer1.initialize(1000000); // 1 second Timer1.attachInterrupt(toggleLED); } void loop() { // main loop does nothing } void toggleLED() { ledState = !ledState; digitalWrite(13, ledState); Serial.println(ledState ? "LED ON" : "LED OFF"); }
Think about what the toggleLED function does each time the interrupt fires.
The interrupt toggles the ledState boolean every second. It prints "LED ON" when ledState is true and "LED OFF" when false, so the output alternates every second.
Choose the correct statement about using TimerOne interrupts in Arduino sketches.
Think about how interrupts help with timing and multitasking.
TimerOne interrupts allow code to run at precise intervals without blocking the main loop. They do not disable all other interrupts, and delay() should not be used inside interrupts. TimerOne works on many AVR-based boards, not only Uno.
Examine the code below. The LED connected to pin 13 flickers irregularly instead of toggling every 0.5 seconds. What is the cause?
volatile int ledState = LOW; void setup() { pinMode(13, OUTPUT); Timer1.initialize(500000); // 0.5 seconds Timer1.attachInterrupt(toggleLED); } void loop() { // empty } void toggleLED() { ledState = !ledState; digitalWrite(13, ledState); }
Consider the data type and how the ! operator works on integers.
The ! operator on an int toggles between 0 and 1, but ledState was initialized to LOW (0). The toggle works but ledState becomes 1 or 0, which is fine for digitalWrite. However, using int instead of bool can cause confusion. The flicker is likely due to the improper use of ! on int instead of bool.
Identify the option that corrects the syntax error in the TimerOne initialization code below:
Timer1.initialize(1000000) Timer1.attachInterrupt(toggleLED);
Check the end of each statement for proper punctuation.
In Arduino (C++), each statement must end with a semicolon. The first line is missing a semicolon, causing a syntax error.
Given this code snippet, how many times will the LED connected to pin 13 toggle in 10 seconds?
volatile bool ledState = false;
void setup() {
pinMode(13, OUTPUT);
Timer1.initialize(2500000); // 2.5 seconds
Timer1.attachInterrupt(toggleLED);
}
void loop() {}
void toggleLED() {
ledState = !ledState;
digitalWrite(13, ledState);
}Calculate how many 2.5 second intervals fit into 10 seconds.
The interrupt fires every 2.5 seconds. In 10 seconds, 10 / 2.5 = 4 interrupts occur, so the LED toggles 4 times.