Sub topic 2
Measuring Time with millis()
This chapter assumes you know setup() and loop(), pinMode(), digitalRead(), digitalWrite(), if statements, and the unsigned long and bool types. You need an Arduino board with a pushbutton wired to pin 2 and GND.
Measuring time with millis()
millis() returns the number of milliseconds since the board started, as an unsigned long. Save the value, then subtract it from a later call to get elapsed time. Unlike delay(), millis() returns immediately, so loop() keeps running.
Surviving millis() rollover
The counter is 32 bits wide, so it wraps back to 0 after about 49.7 days. Compute elapsed time by subtracting the start time from the current time. Unsigned subtraction gives the correct result across the wrap.
unsigned long startTime = millis();
const unsigned long timeout = 1000;
void loop() {
// Correct: stays right after millis() wraps to 0.
if (millis() - startTime >= timeout) {
// timeout has elapsed
}
}Blinking without delay()
delay(500) freezes the sketch for half a second. Instead, record when you last toggled the LED, and toggle again once 500 ms have passed.
const unsigned long INTERVAL_MS = 500;
unsigned long previousMillis = 0;
bool ledState = LOW;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousMillis >= INTERVAL_MS) {
previousMillis = now;
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
// Other work runs here on every pass through loop().
}Reacting to a press once, not continuously
A held button reads LOW on every pass through loop(). Store the previous reading and act only when it changes from HIGH to LOW.
const uint8_t BUTTON_PIN = 2;
int lastReading = HIGH;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop() {
int reading = digitalRead(BUTTON_PIN);
if (reading == LOW && lastReading == HIGH) {
// Runs once per press.
}
lastReading = reading;
}Exercise
Why can if (millis() >= startTime + timeout) fail after rollover, and what should you write instead?
Show answer
The sum startTime + timeout can wrap to a small value, so the test may fire immediately or never fire. Write millis() - startTime >= timeout instead, because unsigned subtraction gives the correct elapsed time across the wrap.