Pico: dim an LED with a knob
A Raspberry Pi Pico reads a potentiometer with its 12-bit ADC and sets an LED's brightness with PWM.
Output · Beginner
In a real product: Desk lamp dimmer (Consumer electronics): A knob sets how bright the lamp is.
The Raspberry Pi Pico carries an RP2040: two Arm Cortex-M0+ cores, 264 KB of RAM and 2 MB of flash outside the chip. This sketch runs on the Arduino core for it. A potentiometer on GP26 sets how bright an LED on GP15 glows.
What you'll learn
- Reading GP26 (ADC0) with 12 bits instead of the Uno's 10, using
analogReadResolution(12) - Driving an LED with PWM at a frequency and resolution you choose (
analogWriteFreq,analogWriteRange) - Why the Pico's pins are 3.3 V, and what that means for the resistor
How it works
The RP2040's ADC measures 0 to 3.3 V as 0 to 4095. analogReadResolution(12) keeps all 12 bits, where the Arduino default would be 10.
Every GPIO pin can be a PWM output: the chip has 8 PWM slices with two channels each. analogWriteFreq(1000) sets 1 kHz and analogWriteRange(4095) makes the duty cycle go from 0 to 4095. That way the ADC reading can be written straight to the LED.
Our eyes don't see brightness in a straight line: half the duty cycle looks much brighter than half. So the sketch squares the reading first, a simple gamma correction, and the knob feels even from end to end.
With 3.3 V, a red LED's 2 V drop and 220 Ω, the current is (3.3 − 2) / 220 ≈ 6 mA. Each Pico pin can drive about 12 mA safely.
Try this
- Remove the gamma line and compare how the knob feels.
- Set
analogWriteFreq(20): the LED visibly flickers, because each pulse is now 50 ms long. - Add a second LED on GP14 that gets brighter as the first gets dimmer.
sketch.ino
// Raspberry Pi Pico (Arduino core): a potentiometer on GP26 (ADC0) sets an LED's brightness on GP15 with PWM.
const int KNOB = 26;
const int LED = 15;
void setup() {
Serial.begin(115200);
analogReadResolution(12); // 0-4095 for 0-3.3 V
analogWriteFreq(1000); // 1 kHz PWM
analogWriteRange(4095); // duty cycle 0-4095
pinMode(LED, OUTPUT);
}
void loop() {
int raw = analogRead(KNOB);
uint32_t duty = (uint32_t)raw * raw / 4095; // gamma: square it, so brightness looks even
analogWrite(LED, duty);
static unsigned long last = 0;
if (millis() - last >= 500) {
last = millis();
Serial.print("knob ");
Serial.print(raw);
Serial.print(" (");
Serial.print(raw * 3.3 / 4095, 2);
Serial.print(" V), duty ");
Serial.print(duty * 100 / 4095);
Serial.println(" %");
}
}