millis() instead of delay()
delay() stops the sketch on one line, and nothing else in loop() happens until it returns. millis() is a clock the sketch can glance at instead: blink on time, and still answer a key the moment it is pressed.
delay() holds the chip on one line
The obvious way to blink and listen is this:
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
while (Serial.available() > 0) {
Serial.write(Serial.read());
}
}It blinks correctly. It also only looks at Serial once every two seconds,
because delay(1000) does not return until a second has passed, and the line
after it waits.
The character is not lost. The UART receives it on its own, an interrupt puts it in Serial's 64-byte receive buffer, and it waits there until the sketch asks. What the sketch cannot do is answer it, and a key pressed just after the check waits nearly the full two seconds. With a button, a sensor or a motor instead of a key, that wait is a missed press or a late stop.
millis() is a clock you look at
millis() returns the number of milliseconds since the sketch started, as an
unsigned long. Timer0, started by init() before your
setup(), keeps it counting in the background.
Reading it takes almost no time.
The pattern is to remember when something last happened and, on every pass of
loop(), ask whether long enough has gone by:
if (millis() - lastToggle >= 1000) {
lastToggle = millis();
// change the lamp
}Most passes the answer is no, and loop() goes straight on to the next job.
Nothing waits, so a pass takes microseconds and loop() comes round thousands
of times a second. Each job gets checked every time, and each has its own
last variable and interval, so two lamps at two rates, or a blink and a
sensor read, run side by side.
The wrap, at about 49.7 days
An unsigned long holds up to 4,294,967,295. That many milliseconds is about
49.7 days, and one millisecond later millis() returns 0 and starts again.
The subtraction survives it. Unsigned arithmetic on this chip wraps the same
way the counter does, so just after the wrap, with lastToggle at
4,294,967,000 and now at 200, now - lastToggle is 496: the true number of
milliseconds between them. The test still works.
Written the other way, now >= lastToggle + 1000, it fails. Near the top,
lastToggle + 1000 wraps to a small number, the test is true on every pass,
and the lamp flickers as fast as loop() runs until now wraps too. Keep
times in unsigned long, and always subtract.
Finer than a millisecond
millis() is good to about a millisecond, and now and then it steps by two.
For shorter times, micros() counts microseconds in steps of 4 on a 16 MHz
board like this one, and wraps after about 70 minutes. The same subtraction
pattern applies.
delay() still has its place: a pause in setup() before anything else is
running costs nothing. Flash, SRAM and EEPROM
is where all these variables live.
The code
The lamp on pin 13 blinks once a second, on for one and off for one, and anything you type in the Serial Monitor at 9600 baud comes straight back, whatever the lamp is doing.
// Blink_And_Echo.ino — blink pin 13 with millis(), echo typing
// Tools > Board: Arduino Uno, or Arduino Nano with
// Processor ATmega328P (Old Bootloader if the upload says
// "not in sync")
// Tools > Port: the CH340 port
// Serial Monitor: 9600 baud
// Wiring: none
const unsigned long HALF_PERIOD = 1000; // ms on, then ms off
unsigned long lastToggle = 0;
bool lampOn = false;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
Serial.println("Type something and press Enter");
}
void loop() {
unsigned long now = millis();
if (now - lastToggle >= HALF_PERIOD) { // survives the wrap
lastToggle = now;
lampOn = !lampOn;
digitalWrite(LED_BUILTIN, lampOn);
}
while (Serial.available() > 0) {
Serial.write(Serial.read()); // send it straight back
}
}Try the delay() version from the page with the same typing and compare. The blink is identical; the echo is not.
When it does not work
The time is held in an int or a long, or the test is written as now >= last + interval. Hold every time in unsigned long and compare with now - last >= interval. That form gives the right answer across the wrap at about 49.7 days; the other does not.
Something else in loop() is still blocking: a delay() left in, or a function that waits. Every pass of loop() has to be quick for the sketch to answer at once. Search the sketch for delay( and for while loops that wait on something.
More than 64 characters arrived while the sketch was not reading. Serial keeps them in a 64-byte buffer, and anything past that is dropped. Read Serial on every pass of loop(), as the sketch here does, and the buffer never fills.
lastToggle = now restarts the interval from whenever the check happened, a little after the due time. For a steady rhythm write lastToggle += HALF_PERIOD instead. The board's clock source, a crystal on the UNO and a ceramic resonator on the Nano, is accurate enough for a blink, but it is not a clock.
The three memories in the chip, what the IDE's two lines after a build mean, and a count that survives a reset.
Flash, SRAM and EEPROM →Edit this page — content/books/atmega328p/millis-not-delay.mdx
Discuss this article
Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.