An LED connected straight to a battery can burn out in a flash. It needs a partner: a resistor in series.
Key idea
An LED drops a nearly fixed voltage, its forward voltage $V_f$ (about 2 V for red, about 3 V for blue or white). The resistor takes the rest. Choose $R = \dfrac{V_{\text{supply}} - V_f}{I}$, with $I$ about 10 to 20 mA for a small LED.
Why it works
The LED's own resistance changes wildly with voltage, so you cannot set its current by voltage alone. The resistor makes the current steady and safe. The same idea, limiting current, protects microcontroller pins.
Worked example: Pick a resistor
A red LED ($V_f = 2\ \text{V}$) on a 5 V pin, at 15 mA.
- Left for the resistor: $5 - 2 = 3\ \text{V}$.
- $R = 3 / 0.015 = 200\ \Omega$.
- Pick the next standard value up: $220\ \Omega$.
Answer: 220 Ξ©.
Worked example: Blue on 3.3 V
A blue LED ($V_f = 3.0\ \text{V}$) on a 3.3 V pin at 10 mA.
- $3.3 - 3.0 = 0.3\ \text{V}$.
- $R = 0.3/0.010 = 30\ \Omega$.
Answer: About 30 Ξ©; it will be dim if $V_f$ is a little higher, which is normal for blue on 3.3 V.
Common mistake
Dividing the whole supply voltage by the current. Subtract the LED's forward voltage first.
Microcontroller pins can only supply a small current; check the board's documentation. An Arduino Uno pin is rated for 20 mA continuous, with an absolute maximum of 40 mA; a Raspberry Pi Pico pin is safest at a few milliamps. Use a transistor or driver for anything bigger, like a motor.