Sub topic 3
Building the circuit on a breadboard
This chapter assumes you can upload a sketch with setup() and loop(), you know Ohm's law (V = I × R), and you have a board, a USB cable, a breadboard, an LED, a 220 Ω resistor, and jumper wires.
Wiring the external LED
Connect the parts in series from the pin to ground. The LED's anode (long leg) takes current from the pin through the resistor, and its cathode (short leg) returns to GND.
With a 5 V pin and a 2 V forward drop across the LED, a 20 mA target gives R = (5 − 2) / 0.020 = 150 Ω. A 220 Ω resistor is a common choice and limits current to about 14 mA.
Blinking an external LED on a chosen pin
Store the pin number in a constant so you change it in one place.
const uint8_t LED_PIN = 8;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
}When nothing blinks: a checklist
| Symptom | Check |
|---|---|
| Upload fails | Confirm the correct board and port are selected. |
| LED stays dark | Confirm the LED is oriented with the anode toward the resistor. |
| LED stays dark | Confirm `LED_PIN` matches the wire's pin. |
| LED stays lit | Confirm the LED is not wired directly to 5 V without a resistor. |
Blinking without blocking: millis()
delay() stops the program, so nothing else runs while the LED waits. millis() returns the milliseconds since the board started. Comparing that value to a stored time lets loop() keep running.
const uint8_t LED_PIN = 8;
const unsigned long INTERVAL_MS = 500;
unsigned long previousToggle = 0;
bool ledOn = false;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousToggle >= INTERVAL_MS) {
previousToggle = now;
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
}
// Other code can run here without waiting for the blink.
}Exercise
Using the millis() version, how would you blink two LEDs on pins 8 and 9 at different intervals?
Show answer
Store a separate previous-toggle time, state flag, and interval for each LED, and check each one's elapsed time inside loop().