04 / 16
Potentiometer: analogRead to PWM
Turn a potentiometer to dim an LED. Compare the A0 reading from 0 to 1023 with the D9 PWM output from 0 to 255.
Run this experiment →
Why it’s here
Scale an analog reading into a PWM output.
How it works
The 10-bit input spans 0–1023, while PWM spans 0–255. Integer division by four maps the first range to the second. PWM changes the proportion of time spent HIGH, not the HIGH voltage itself.
Try it
- Open this experiment
- Run the example. Set the input to 0, 512 and 1023, and compare each reading with the PWM value and LED brightness.
Connections
- A0 — Potentiometer wiper
- 5V / GND — Potentiometer ends
- D9 ~ — LED through resistor
Example sketch
void setup() {
pinMode(9, OUTPUT);
Serial.begin(9600);
}
void loop() {
int reading = analogRead(A0);
analogWrite(9, reading / 4);
Serial.println(reading);
}Check your understanding
What PWM value does an input of 512 produce here?
Show the answer
128. This sketch uses integer division by four. The input and output use different ranges; PWM does not turn D9 into a true analog output.