Do two things at once with millis()

Make two LEDs blink at their own speeds while a button still reacts the moment you press it. You learn why delay() freezes your sketch, and how millis() lets the UNO keep many jobs going at once.
  • Level:Beginner
  • Duration: 40 min
  • Ages 10+
  • Platform: Arduino

Tools for this lesson

Helpful for this build. Open a tool to see tips and more projects that use it.

Do two things at once with millis() – EEMENTOR STEM™ lesson

So far your sketches have used delay() to wait: switch the LED on, wait half a second, switch it off, wait again. That's fine for one job. But try to blink two LEDs at different speeds and read a button at the same time, and it falls apart: while the UNO waits inside delay(), it can't do anything else, not even notice your button. In this lesson you learn the trick almost every real Arduino project uses: millis(). Instead of waiting, the UNO keeps looking at a clock and only acts when it's time. You'll make two LEDs blink at their own speeds while a third LED switches the instant you press a button.

What you'll learn

  • Why delay() stops your whole sketch
  • What millis() counts, and how to use it like a kitchen timer
  • How to run several jobs at once, each with its own timing
  • How to ignore button bounce without using delay()

What you need

  • UNO R3 board and USB cable (UNO R3 Starter Kit)
  • 3 LEDs: red, green and yellow, and 3 resistors, 220 Ω (red, red, brown) (UNO R3 Starter Kit)
  • 1 push button (UNO R3 Starter Kit)
  • Breadboard and jumper wires (UNO R3 Starter Kit)
  • The free Arduino IDE

The problem with delay()

Here is a sketch that blinks one LED and is supposed to react to a button. Look at what the UNO is doing most of the time:

void loop() {
  digitalWrite(9, HIGH);
  delay(500);              // stuck here for half a second
  digitalWrite(9, LOW);
  delay(500);              // and here for another half second
  // the button can only be checked here, once a second
}

For 999 of every 1000 milliseconds, the UNO is stuck inside delay(). Press the button quickly and it misses it completely. Add a second LED with its own speed and you'd have to work out one long, complicated pattern of delays. The Arduino reference says it plainly: during delay(), no other reading of sensors, calculations or pin changes can happen.

Wiring

Each LED gets its own 220 Ω resistor. The button sits across the middle gap of the breadboard: one leg goes to pin 2, the leg diagonally opposite goes to GND. The sketch switches on the UNO's built-in pull-up resistor, so the pin reads HIGH normally and LOW while you press.

Breadboard wiring diagram: red LED on UNO pin 9, green LED on pin 10 and yellow LED on pin 11, each through a 220 ohm resistor, and a push button from pin 2 to GND.
Breadboard view. Check each connection against the wiring table below.
From To
UNO pin 9 220 Ω resistor → red LED long leg (+)
UNO pin 10 220 Ω resistor → green LED long leg (+)
UNO pin 11 220 Ω resistor → yellow LED long leg (+)
All three LED short legs (−) The blue (−) rail
Push button, one leg UNO pin 2
Push button, diagonally opposite leg The blue (−) rail
The blue (−) rail UNO GND
FREE

Build this circuit in EEMENTOR Lab

Wire it yourself in your browser before you touch a real wire. No sign-up, nothing to install.

The UNO and the parts for this lesson laid out in EEMENTOR Lab, ready to wireBuild it yourself
  1. The UNO and this lesson’s parts are already placed. Wire them using the wiring table above. Pins with no wire show red.
  2. Missing a part? Add it from the parts list on the left.
  3. Press Run, then try the inputs: click, hold or slide them under Selected.
  4. Then try this lesson’s sketch: paste it into the Code tab and press Compile & Run.

EEMENTOR Lab is free and in beta. Results are a guide; a real build can differ slightly. About the Lab

The sketch

Copy the sketch into the Arduino IDE, choose Arduino Uno as the board and the right port, and click Upload. Then open the Serial Monitor at 9600 baud.

// Do two things at once with millis(): two LEDs blink at their own speed,
// and the button switches the yellow LED the moment you press it.
// There is no delay() anywhere in loop().
const int RED_PIN = 9;
const int GREEN_PIN = 10;
const int YELLOW_PIN = 11;
const int BUTTON_PIN = 2;

const unsigned long RED_INTERVAL = 500;     // red changes every 0.5 s
const unsigned long GREEN_INTERVAL = 1300;  // green changes every 1.3 s
const unsigned long BOUNCE_TIME = 30;       // ignore button chatter shorter than this

unsigned long redLast = 0;      // when red last changed
unsigned long greenLast = 0;    // when green last changed
unsigned long buttonLast = 0;   // when the button last changed
bool redOn = false;
bool greenOn = false;
bool yellowOn = false;
int lastButton = HIGH;

void setup() {
  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(YELLOW_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);   // HIGH normally, LOW while pressed
  Serial.begin(9600);
  Serial.println("Two LEDs blinking. Press the button any time.");
}

void loop() {
  unsigned long now = millis();        // milliseconds since the UNO started

  // Job 1: the red LED
  if (now - redLast >= RED_INTERVAL) {
    redLast = now;
    redOn = !redOn;
    digitalWrite(RED_PIN, redOn ? HIGH : LOW);
  }

  // Job 2: the green LED
  if (now - greenLast >= GREEN_INTERVAL) {
    greenLast = now;
    greenOn = !greenOn;
    digitalWrite(GREEN_PIN, greenOn ? HIGH : LOW);
  }

  // Job 3: the button switches the yellow LED
  int button = digitalRead(BUTTON_PIN);
  if (button != lastButton && now - buttonLast >= BOUNCE_TIME) {
    buttonLast = now;
    lastButton = button;
    if (button == LOW) {               // it has just been pressed
      yellowOn = !yellowOn;
      digitalWrite(YELLOW_PIN, yellowOn ? HIGH : LOW);
      Serial.print(now);
      Serial.print(" ms: button pressed, yellow is ");
      Serial.println(yellowOn ? "ON" : "OFF");
    }
  }
}

Try it

  1. Upload the sketch. The red LED blinks fast and the green one slowly. They drift in and out of step, because 500 and 1300 don't fit neatly into each other.
  2. Press the button. The yellow LED switches on instantly, however the other two are blinking. Press again to switch it off.
  3. Tap the button as fast as you can. Every press counts, and the Serial Monitor shows the exact millisecond of each one.
  4. Change GREEN_INTERVAL to 200 and upload again. Each LED keeps its own speed, and you didn't have to touch the code for the others.

What you should see

Serial Monitor at 9600 baud: the start message, then each button press with its time in milliseconds and whether the yellow LED is on or off.
Every press is caught, to the millisecond.

How it works

Timeline: with delay() the UNO waits in four half-second blocks and misses a button press; with millis() loop() checks thousands of times a second, so the LEDs change on time and the button works at once.
Waiting blocks everything; checking the clock doesn’t.

From the moment the UNO starts, millis() counts the milliseconds that have passed, like a stopwatch that never stops. It returns an unsigned long, a whole number that can go above 4 billion, so it only runs out and starts again from zero after about 50 days.

Each job works like a kitchen timer. redLast remembers when the red LED last changed. Every time round loop(), the sketch asks: "has RED_INTERVAL passed since then?" That's now - redLast >= RED_INTERVAL. If not, it does nothing and moves on straight away. If yes, it switches the LED and writes down the new time. Because nothing ever waits, loop() runs many thousands of times every second, and each job gets checked over and over.

Always write the test as a subtraction, now - last >= interval, and keep the times in unsigned long variables. That way the sum still works when millis() rolls back to zero after 50 days. The same idea stops button bounce: the metal inside a button chatters for a few milliseconds when you press it, so the sketch ignores any change that comes less than 30 ms after the last one.

Try this next

  • Add a fourth job: read a potentiometer on A0 every 200 ms and print its value, without disturbing the LEDs.
  • Make the button change the red LED's speed instead: each press makes RED_INTERVAL shorter.
  • Build a reaction game: light the yellow LED after a random time with random() and measure how many milliseconds you take to press.
  • Look back at your earlier sketches and find one that would work better without delay().

Troubleshooting

  • An LED never lights: turn it round (long leg towards the resistor and the pin) and check its resistor.
  • The yellow LED switches on and off on its own: the button pin is floating. Check that the sketch has INPUT_PULLUP and that the other leg of the button goes to GND.
  • One press switches it twice: the button bounces longer than 30 ms. Change BOUNCE_TIME to 50.
  • The button does nothing: use two legs that are diagonally opposite, on different sides of the middle gap. Two legs on the same side are always connected inside the button.
  • Nothing in the Serial Monitor: set it to 9600 baud, the same as Serial.begin(9600).