Consider this Arduino code that uses a timing-based state machine to blink an LED connected to pin 13. What will be the output on the LED over 5 seconds?
const int ledPin = 13; unsigned long previousMillis = 0; const long interval = 1000; int ledState = LOW; void setup() { pinMode(ledPin, OUTPUT); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; ledState = (ledState == LOW) ? HIGH : LOW; digitalWrite(ledPin, ledState); } }
Look at the interval variable and how it controls the timing of state changes.
The code toggles the LED state every 1000 milliseconds (1 second). Over 5 seconds, it will blink 5 times (ON then OFF repeatedly).
In a timing-based state machine on Arduino, what is the main purpose of storing the variable previousMillis?
Think about how you know when to change states based on time.
The variable previousMillis records the last time the state changed, so the program can compare it with the current time and decide if enough time has passed to move to the next state.
Here is an Arduino code snippet intended to blink an LED every 2 seconds. However, the LED never turns ON. What is the cause?
const int ledPin = 13; unsigned long previousMillis = 0; const long interval = 2000; int ledState = LOW; void setup() { pinMode(ledPin, OUTPUT); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis > interval) { previousMillis = currentMillis; if (ledState == LOW) { ledState = HIGH; } else { ledState = LOW; } digitalWrite(ledPin, ledState); } }
Check the condition inside the if statement that tests ledState.
The code uses = (assignment) instead of == (comparison) in the if condition, so ledState is set to LOW every time, preventing it from turning ON.
Which option contains the correct syntax to toggle an LED state variable ledState between HIGH and LOW using a ternary operator in Arduino C++?
Remember the ternary operator format: condition ? value_if_true : value_if_false
Option A correctly compares ledState to LOW and assigns HIGH or LOW accordingly. Other options have wrong operators or reversed logic.
An Arduino timing-based state machine toggles an output pin every 750 milliseconds. How many times will it toggle in 10 seconds?
Divide total time by interval and consider if toggling happens at start or after interval.
10 seconds = 10000 ms. 10000 / 750 ≈ 13.33. No toggle at t=0; first at 750 ms, up to 13th at 9750 ms, so 13 toggles.
