Fade an LED on an Arduino Uno
An LED on pin 9 breathes up and down with analogWrite: 490 Hz hardware PWM from the Uno’s timer, through a 220 ohm resistor. The whole build, an Arduino Uno and 2 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Beginner Runs in your browser. Free, and no account needed.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Fade: a breathing LED on pin 9, from the timer, not from the CPU.
//
// Pin 9 is OC1A, timer 1's compare output. analogWrite() puts timer 1 into
// 8-bit phase-correct PWM with a 64 prescaler, which is 16 MHz / (64 x 510) =
// 490 Hz, and after that the hardware holds the duty cycle on its own: the
// sketch only changes OCR1A thirty times a second and sleeps in between.
//
// Wire an LED and a 220 ohm resistor from pin 9 to GND.
//
// The table is one cycle of (1 - cos)/2, which is what makes the light look
// like it is breathing rather than ramping: the eye reads brightness roughly
// logarithmically, so a linear ramp looks like it rushes the top end.
const int LED_PIN = 9;
const int STEPS = 64;
const int MS_PER_STEP = 30;
const uint8_t breath[STEPS] = {
0, 1, 2, 5, 10, 15, 21, 28,
37, 46, 56, 66, 77, 89, 101, 113,
125, 137, 149, 161, 173, 184, 194, 204,
213, 222, 229, 235, 240, 245, 248, 249,
250, 249, 248, 245, 240, 235, 229, 222,
213, 204, 194, 184, 173, 161, 149, 137,
125, 113, 101, 89, 77, 66, 56, 46,
37, 28, 21, 15, 10, 5, 2, 1,
};
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
for (int step = 0; step < STEPS; step++) {
analogWrite(LED_PIN, breath[step]);
delay(MS_PER_STEP);
}
}
Parts list
4 parts, plus the jumper wires. Every one is in the editor's parts bin.
- 1 × Arduino Uno R3
- 1 × Full-size breadboard
- 1 × Resistor, 220 Ω
- 1 × LED, red
How it is wired
3 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Ground: Arduino Uno R3 pin GND; LED, red pin C
- Arduino Uno R3 pin 9; Resistor, 220 Ω pin 1
- Resistor, 220 Ω pin 2; LED, red pin A
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.
Free forever. Every board and part. Saves your projects. Works on Chromebooks.