typestar

Two timers in Arduino

Two jobs, two timestamps, neither waiting for the other.

// Two jobs, two timestamps: neither waits for the other.
unsigned long lastBlink = 0;
unsigned long lastReport = 0;
bool ledOn = false;
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (millis() - lastBlink >= 250) {
    lastBlink = millis();
    ledOn = !ledOn;
    digitalWrite(LED_BUILTIN, ledOn ? HIGH : LOW);
  }
  if (millis() - lastReport >= 2000) {
    lastReport = millis();
    Serial.println(analogRead(A0));
  }
}

How it works

  1. Each job owns a last... timestamp and an interval.
  2. The blink runs at 250 ms while reports go every 2 s.
  3. This is the shape multitasking takes without an OS.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
436
Tokens
108
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 2 of 3 in Timing, step 11 of 27 in Language basics.

← Previous Next →