Overview
delay() stops everything. millis() returns the milliseconds since
start-up, so the sketch can instead check "has enough time passed?" on every pass of the loop and keep doing
other work in between.
You will need
- Arduino Uno R3
- 2 LEDs
- 2 × 330 Ω resistors
- Breadboard
Wiring
| Uno pin | Connects to | Notes |
|---|---|---|
| 6 | 330 Ω → LED A anode | |
| 7 | 330 Ω → LED B anode | |
| GND | Both LED cathodes |
Diagram
The sketch
const int LED_A_PIN = 6;
const int LED_B_PIN = 7;
const unsigned long INTERVAL_A_MS = 250;
const unsigned long INTERVAL_B_MS = 700;
unsigned long lastToggleA = 0;
unsigned long lastToggleB = 0;
bool stateA = false;
bool stateB = false;
void setup() {
pinMode(LED_A_PIN, OUTPUT);
pinMode(LED_B_PIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - lastToggleA >= INTERVAL_A_MS) {
lastToggleA = now;
stateA = !stateA;
digitalWrite(LED_A_PIN, stateA ? HIGH : LOW);
}
if (now - lastToggleB >= INTERVAL_B_MS) {
lastToggleB = now;
stateB = !stateB;
digitalWrite(LED_B_PIN, stateB ? HIGH : LOW);
}
// Free to read buttons or sensors here without slowing the LEDs
}How the code works
Always store times in unsigned long and compare with
now - last >= interval. The counter rolls over to 0 after about 49.7 days; unsigned
subtraction still gives the right elapsed time across the rollover, while now >= last + interval
does not.
What you should observe
- LED A blinks quickly, LED B slowly, and neither disturbs the other.