Start here · 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.
Scale an analog reading into a PWM output.
Understand it
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.
Your 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
Sketch
This sketch illustrates the hardware logic. The workbench runs its corresponding teaching model, not a C++ compiler.
void setup() {
pinMode(9, OUTPUT);
Serial.begin(9600);
}
void loop() {
int reading = analogRead(A0);
analogWrite(9, reading / 4);
Serial.println(reading);
}Quick check
What PWM value does an input of 512 produce here?
Show explanation
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.