Blink without delay in Arduino
millis never blocks: compare timestamps instead of sleeping.
// millis never blocks: compare timestamps instead of sleeping.
const unsigned long INTERVAL_MS = 750;
unsigned long lastToggle = 0;
bool ledOn = false;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
// Subtraction stays correct even when millis wraps around.
if (now - lastToggle >= INTERVAL_MS) {
lastToggle = now;
ledOn = !ledOn;
digitalWrite(LED_BUILTIN, ledOn ? HIGH : LOW);
}
}
How it works
millis()is the free-running clock since power-on.now - lastToggle >= INTERVAL_MSsurvives the 49-day wraparound.- The loop stays free to do other work between toggles.
Keywords and builtins used here
HIGHLED_BUILTINLOWOUTPUTboolconstdigitalWritefalseiflongloopmillispinModesetupunsignedvoid
The run, in numbers
- Lines
- 19
- Characters to type
- 430
- Tokens
- 78
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 72 seconds.
Step 1 of 3 in Timing, step 10 of 27 in Language basics.