Dim an LED with a knobTinkerPieCircuit tutorial 10 of 24 · Beginner · 15 minutes
Use a potentiometer as an analog input and analogWrite to change the brightness of an LED.
Open this circuit in TinkerPieCircuit (free, runs in your browser)
What you will learn
- Analog input: analogRead gives 0 to 4095
- PWM brightness with analogWrite (0 to 255)
- Mapping one range to another with map()
Parts
Steps
Wire the LED
S1→ 220 Ω resistor → LED (+). LED (−) →GND.Add the potentiometer
A potentiometer is a knob with three pins. Wire the left pin A to
3V3, the right pin B toGND, and the middle pin W (wiper) toP11.Read the knob
analogRead(P11)returns a number from 0 (knob at GND) to 4095 (knob at 3.3 V).Set the brightness
map()squeezes 0 to 4095 into 0 to 255 foranalogWrite(S1, …).Turn the knob
Press ▶ Start and drag the small slider at the top of the potentiometer. Open the Serial monitor to see the numbers.
The code
function loop() {
const knob = analogRead(P11);
analogWrite(S1, map(knob, 0, 4095, 0, 255));
Serial.println("knob = " + knob);
delay(100);
}
Copy this into the Code tab. It is Arduino-style JavaScript. The real board uses the same pin names (S1, P10…) in TinkerPie Studio.
How it works
The knob splits 3.3 V into a smaller voltage on the wiper pin. analogWrite switches the LED on and off very fast: the longer it is on, the brighter it looks.
← Button controls an LED · All 24 circuit tutorials · Build a night light →