Sub topic 8
Controlling Brightness with a Potentiometer
This chapter connects a knob to the LED. You will read a potentiometer with analogRead(), scale the result to the range analogWrite() accepts, and handle the problems that appear on real hardware: noise, out-of-range values, and the choice of scaling method.
It assumes you can write a basic sketch with setup() and loop(), wire a breadboard, and apply Ohm's law. It also assumes you already have the LED on pin 9 with a current-limiting resistor from the earlier chapters, and that you know analogWrite(pin, value) takes 0 to 255.
What a potentiometer does
A potentiometer (pot) is a resistor with three terminals and a sliding contact. The outer two terminals connect to the ends of a fixed resistive track. The middle terminal, the wiper, touches the track at a point you set by turning the knob.
Connect one outer terminal to 5 V and the other to GND. The wiper then acts as a voltage divider. Its voltage is a fraction of the supply set by the knob position:
- Knob at the GND end: the wiper reads about 0 V.
- Knob in the middle: about 2.5 V, if the pot is linear.
- Knob at the 5 V end: about 5 V.
This gives you a smooth analog voltage that you can measure and use as a brightness command.
The common 10 kΩ pot suits the Uno. The ATmega328P datasheet recommends a source impedance of 10 kΩ or less for the ADC (analog-to-digital converter). A much larger pot can make readings sluggish or inaccurate, because the ADC's sampling capacitor needs time to charge through the pot.
Wiring
The circuit has two independent parts that share a ground.
- Pot, left terminal to 5 V.
- Pot, right terminal to GND.
- Pot, wiper (middle) to A0.
- LED circuit as before: pin 9, through a 220 Ω resistor, to the LED anode. The LED cathode goes to GND.
Swapping the two outer terminals is harmless. It only reverses the direction the knob turns. Connecting the wiper to 5 V or GND instead of A0 gives a constant reading. Leaving A0 unconnected makes it "float", and the reading wanders with noise from nearby wires and your hand.
Reading the pot: analogRead()
analogRead(pin) measures the voltage on an analog input and returns an integer from 0 to 1023. The Uno's ADC has 10 bits, so it distinguishes 2^10 = 1024 levels across the reference range. By default the reference is the 5 V supply (DEFAULT), so one step is about 5 V / 1024 ≈ 4.88 mV.
The result is floor(Vin / Vref * 1024), capped at 1023. At 5 V the reading is 1023, never 1024.
Two practical points:
- A conversion takes about 100 µs on an Uno with the default ADC clock. At that speed you can call
analogRead()thousands of times per second without noticeably slowingloop(). - Pass
A0or the plain number0. Both work foranalogRead(), butA0is clearer and avoids confusion with digital pin 0.
Matching the ranges: 10 bits in, 8 bits out
analogRead() returns 0 to 1023 and analogWrite() expects 0 to 255. The ranges differ by a factor of four, so the reading has to be scaled down.
Passing the raw reading directly is a common bug. The documented range for analogWrite() is 0 to 255, and values outside it are not guaranteed to behave sensibly. On an Uno, a value above 255 can wrap or saturate. The LED then goes bright at the wrong knob positions, usually in a repeating pattern.
The simplest correct sketch shifts the reading right by two bits, which divides by four and drops the remainder:
const uint8_t LED_PIN = 9;
const uint8_t POT_PIN = A0;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
int reading = analogRead(POT_PIN); // 0..1023
analogWrite(LED_PIN, reading >> 2); // scale to 0..255
}There is no delay() here. loop() runs continuously, and each pass reads the pot and updates the duty cycle. Because analogWrite() keeps the PWM running in hardware between calls, repeating it with the same value is harmless.
The table shows how the knob position maps to duty cycle:
| Knob position | `analogRead()` | After `>> 2` | Duty cycle |
|---|---|---|---|
| Fully toward GND | 0 | 0 | 0% |
| Quarter turn | 256 | 64 | about 25% |
| Middle | 512 | 128 | about 50% |
| Three quarters | 768 | 192 | about 75% |
| Fully toward 5 V | 1023 | 255 | 100% |
Duty percentage is value / 255, so 128 gives 50.2%, which is close enough to treat as half.
Shift versus map()
Arduino also provides map():
analogWrite(LED_PIN, map(reading, 0, 1023, 0, 255));For this range both methods return 0 at the bottom and 255 at the top, and they are nearly identical in between. The differences matter in other situations.
>> 2is exact, fast, and needs no thought, but works only when the ratio is a power of two.map()handles arbitrary ranges, such as a minimum brightness of 10 instead of 0. It uses integer arithmetic, so it truncates, and it does not clamp values outside the input range.- To invert the knob, use
255 - (reading >> 2)ormap(reading, 0, 1023, 255, 0).
Noise and jitter
On a real board, the reading of a pot sitting still is rarely perfectly constant. Common causes are:
- Supply noise, especially when the board runs from USB and the LED is switching on the same 5 V rail.
- A worn or dirty pot track, which makes the wiper contact resistance vary.
- Long, unshielded wires acting as antennas.
- Quantization at a boundary. When the true voltage sits close to a step edge, the reading flips between two neighbouring values.
A one-count flicker in the 10-bit reading becomes at most a one-count change in the 8-bit duty after the shift, which is under 0.4% of the range. On an LED you will not see this. It becomes visible when the output drives something sensitive, such as a motor that audibly changes pitch or a threshold that toggles an action.
Averaging several readings
Averaging a few samples reduces random noise by roughly the square root of the sample count. With 8 samples, the sum of eight 10-bit readings is at most 8 × 1023 = 8184, which fits in a uint16_t. Dividing the sum by 8 gives the average, and shifting right by 2 more gives 8 bits. Together that is a shift of 5:
const uint8_t LED_PIN = 9;
const uint8_t POT_PIN = A0;
// SAMPLES must be 8 for the >> 5 below to scale 8 summed readings to 0..255.
const uint8_t SAMPLES = 8;
const unsigned long PRINT_INTERVAL_MS = 200;
unsigned long lastPrintTime = 0;
uint8_t readDuty() {
uint16_t sum = 0;
for (uint8_t i = 0; i < SAMPLES; i++) {
sum += analogRead(POT_PIN);
}
return sum >> 5; // (sum / 8) / 4, giving 0..255
}
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(115200);
}
void loop() {
uint8_t duty = readDuty();
analogWrite(LED_PIN, duty);
unsigned long now = millis();
if (now - lastPrintTime >= PRINT_INTERVAL_MS) {
lastPrintTime = now;
Serial.print("duty=");
Serial.print(duty);
Serial.print(" (");
Serial.print((duty * 100UL) / 255);
Serial.println("%)");
}
}The sketch has three details worth noting:
- Eight reads take roughly 0.8 ms, so the LED still updates over a thousand times per second.
- The serial output is rate-limited with
millis(), using the same pattern as the previous chapter. Printing on every pass would fill the serial buffer and makeloop()wait for it to drain. duty * 100ULforces unsigned long arithmetic. With plainint,255 * 100 = 25500still fits in a 16-bitint(maximum 32767), but the habit protects you when the numbers grow.
Averaging smooths noise but does not remove hysteresis problems. If you need a value that stays fixed until the knob really moves, only accept a new value when it differs from the last accepted one by more than some threshold, for example 2 counts. This "deadband" trades a little resolution for stability.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| LED is always off or always fully on | Wiper not connected to A0, or outer terminals not on 5 V and GND | Check the wiper goes to A0 and that the outer pins carry 5 V and GND |
| LED jumps brightness repeatedly as you turn the knob | Raw 0..1023 passed to `analogWrite()` | Scale with `>> 2` or `map()` |
| Brightness changes with no one touching the knob | A0 floating, or noisy supply | Check the connection, shorten wires, average samples |
| Knob turns the wrong way | Outer terminals swapped | Swap them, or invert in software |
| LED does not reach full brightness | Reading stops below 1023, or the 8-bit value stops below 255 | Check 5 V supply level and the pot's end-of-travel resistance |
| Sketch feels slow | `delay()` or heavy `Serial.print()` in `loop()` | Rate-limit output with `millis()` |
Combining the pot with other behaviour
The pot control is already non-blocking, so it combines well with the millis() fade from the previous chapter. A common design uses the pot as a maximum-brightness limit while a fade runs below it. Compute the fade value as before, then scale it:
uint8_t scaled = (fadeValue * (uint16_t)maxBrightness) / 255;
analogWrite(LED_PIN, scaled);Here fadeValue and maxBrightness are both 0 to 255, so the product is at most 65025. That fits in uint16_t, which is why the cast matters. Without it, int arithmetic overflows on a 16-bit board once the product exceeds 32767.
The pot can also set the fade speed instead of the brightness, by mapping the reading onto INTERVAL_MS. The rule is the same: the knob changes a variable, and the timing code reads that variable on every pass.
A pot controlling brightness directly has one more subtlety. A linear pot gives linear duty, but the eye does not see equal steps in duty as equal steps in brightness. The bottom part of the knob travel looks too bright and the top part looks flat. A later chapter on gamma correction addresses this by passing the scaled value through a curve before analogWrite(). The structure stays the same: read, scale, correct, write.
Exercise
A student connects a pot to A0 and writes analogWrite(9, analogRead(A0));. The LED brightens as the knob turns up from zero, then abruptly drops to dark and brightens again, repeating several times over the knob's travel. What is wrong, and what is the smallest fix? Also, with your fix, what duty cycle results when analogRead() returns 600?
Show answer
The sketch passes a 10-bit reading (0 to 1023) to analogWrite(), which expects 0 to 255. Values above 255 fall outside the documented range and wrap on the Uno, so the brightness restarts roughly every 256 counts. The smallest fix is analogWrite(9, analogRead(A0) >> 2); (or map(..., 0, 1023, 0, 255)). For a reading of 600, 600 >> 2 is 150, so the duty cycle is 150 / 255, about 58.8%.
Exercise
You average 16 analogRead() samples instead of 8. The sum can reach 16 × 1023 = 16368. Does it fit in a uint16_t, and what shift gives a 0 to 255 duty value?
Show answer
It fits, because 16368 is below 65535. Dividing the sum by 16 gives the 10-bit average, and dividing by 4 more gives 8 bits, so the total is a divide by 64, which is sum >> 6. The maximum is 16368 >> 6 = 255.