Consider this Arduino code snippet using millis() to toggle an LED every 1000 milliseconds. What will be printed to the serial monitor after 3500 milliseconds?
unsigned long previousMillis = 0; const long interval = 1000; int ledState = LOW; void setup() { Serial.begin(9600); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; ledState = !ledState; Serial.println(ledState); } }
Think about how many times the interval of 1000 ms fits into 3500 ms and how the LED state toggles each time.
ledState starts LOW but initial state is not printed. First toggle at 1000 ms prints HIGH (1), at 2000 ms LOW (0), at 3000 ms HIGH (1). So printed: 1 0 1
Which of the following best explains why millis() is preferred over delay() for non-blocking timing in Arduino?
Think about what happens to the program flow when delay() is called.
delay() pauses the entire program, blocking other code from running. millis() lets you check elapsed time without stopping the program, enabling multitasking.
What is the problem with this Arduino code that tries to toggle an LED every 500 ms?
unsigned long previousMillis = 0; const long interval = 500; int ledState = LOW; void setup() { pinMode(LED_BUILTIN, OUTPUT); } void loop() { unsigned long currentMillis = millis(); if (currentMillis > previousMillis + interval) { previousMillis = currentMillis; ledState = !ledState; digitalWrite(LED_BUILTIN, ledState); } }
Consider what happens when millis() value wraps around after about 50 days.
Using subtraction (currentMillis - previousMillis >= interval) handles millis() overflow correctly. Using '>' can fail when millis() resets to zero.
Which of the following code snippets correctly toggles an LED every 2000 milliseconds without blocking the program?
Look for the safest way to compare times that handles overflow correctly.
Option B uses subtraction and '>=' which safely handles millis() overflow. Options A and B use addition with '>=' or '>' which can fail on overflow. Option B incorrectly uses delay() causing blocking.
Given this Arduino code toggling an LED every 1500 milliseconds using millis(), how many times will the LED change state in 10 seconds?
unsigned long previousMillis = 0; const long interval = 1500; int ledState = LOW; void setup() { pinMode(LED_BUILTIN, OUTPUT); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; ledState = !ledState; digitalWrite(LED_BUILTIN, ledState); } }
Divide 10,000 milliseconds by 1500 milliseconds and consider integer division.
10,000 ms / 1500 ms = 6.66, so the LED toggles 6 full times within 10 seconds.
