Potentiometer, LED Fade and map()
Read a potentiometer in Serial Monitor, fade an LED using simple division, then repeat with map() and compare the values.
Lesson 11 · Read a variable resistor
Use a 10 kΩ potentiometer as a three-terminal voltage divider. The middle wiper goes to A0; the two outer terminals go to 5 V and GND. Swapping the outer wires reverses the direction.
void setup() { Serial.begin(9600); }
void loop() {
int raw = analogRead(A0);
Serial.println(raw);
delay(100);
}Turn the knob and watch the raw 10-bit reading, normally near 0–1023 on an UNO R3.
Lesson 12 · Fade the LED without map()
Pin D9 supports PWM on the UNO. analogWrite() expects 0–255, so dividing the analogue reading by four gives a useful first conversion.
void setup() {
pinMode(9, OUTPUT);
Serial.begin(9600);
}
void loop() {
int raw = analogRead(A0);
int brightness = raw / 4;
analogWrite(9, brightness);
Serial.print("Raw: "); Serial.print(raw);
Serial.print(" PWM: "); Serial.println(brightness);
delay(50);
}Because 1023 / 4 is 255 with integer arithmetic, this covers the full PWM range. Observe both columns while turning the knob.
Lesson 13 · Replace the division with map()
int brightness = map(raw, 0, 1023, 0, 255);Replace only the brightness line in the previous sketch. The Serial Monitor now shows the old and new ranges side by side. Try map(raw, 0, 1023, 255, 0) to reverse the response.