Sub topic 10
Dimming an LED with the potentiometer
This chapter closes the loop from input to output. The potentiometer sets a value, and the sketch turns that value into LED brightness. It assumes you can already wire the potentiometer to A0 and read it with analogRead(), and that you know pinMode() and digitalWrite(). Examples target an Arduino Uno. The last section covers other boards.
The signal path
The chain has four stages. The potentiometer produces a voltage, the ADC turns it into a number from 0 to 1023, map() rescales that number, and analogWrite() produces an output signal on a PWM pin.
The input side is analog, but the output side is not. An Uno has no true analog output pin, so analogWrite() produces a fast digital signal that behaves like an adjustable voltage.
What PWM does
PWM (pulse-width modulation) switches a pin between HIGH (5 V) and LOW (0 V) at a fixed rate. The fraction of each cycle spent HIGH is the duty cycle. A duty cycle of 25% means HIGH for a quarter of each cycle and LOW for the rest.
The LED switches far faster than your eye can follow. You see the time-averaged power, not the flicker. The average voltage is the supply voltage times the duty cycle:
average voltage = 5 V × (value / 255)analogWrite(pin, value) takes a value from 0 to 255 on an Uno. It treats the two ends specially:
0holds the pin LOW all the time.255holds the pin HIGH all the time.- Values in between produce pulses with a duty cycle of
value / 255.
On an Uno, PWM is available only on pins marked with a tilde: 3, 5, 6, 9, 10 and 11. Pins 5 and 6 run at about 980 Hz and the others at about 490 Hz. This sketch uses pin 9.
Wiring the LED
Keep the potentiometer wiring from the earlier chapter: one outer terminal to 5V, the other to GND, and the middle terminal (the wiper) to A0. Add the LED on the output side:
- Connect pin 9 to one end of a 220 Ω resistor.
- Connect the other end of the resistor to the LED anode, the longer leg.
- Connect the LED cathode, the shorter leg, to GND.
The resistor limits the current. A red LED drops about 2 V, so the current is roughly (5 − 2) / 220 ≈ 14 mA. That is safe for the LED and within the Uno's per-pin limit. Never connect an LED directly to a pin without a resistor.
The basic sketch
const int POT_PIN = A0;
const int LED_PIN = 9;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
int raw = analogRead(POT_PIN);
int brightness = map(raw, 0, 1023, 0, 255);
analogWrite(LED_PIN, brightness);
}Turn the knob and the LED should move smoothly from off to full brightness. There is no delay() because nothing in this sketch needs pacing. The loop reads, rescales and writes as fast as it can, and analogWrite() keeps producing the PWM signal in hardware between calls.
You do not need pinMode() for analogWrite() on most AVR boards, but calling it is good practice and keeps the sketch portable.
How map() computes the result
map(value, fromLow, fromHigh, toLow, toHigh) evaluates this integer expression:
(value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLowWith our arguments that is raw * 255 / 1023. Integer division discards the fraction, so the result is rounded down. Two consequences follow:
- Only
raw = 1023gives exactly 255. Every other reading rounds down to a lower value. - About four consecutive raw values share each output value, because 1024 input steps are squeezed into 256 output steps. The output cannot be finer than the PWM resolution anyway.
This table shows the conversion at five knob positions:
| raw | brightness | duty cycle | average pin voltage |
|---|---|---|---|
| 0 | 0 | 0% | 0 V |
| 256 | 63 | 24.7% | 1.24 V |
| 512 | 127 | 49.8% | 2.49 V |
| 768 | 191 | 74.9% | 3.75 V |
| 1023 | 255 | 100% | 5 V |
A cheaper alternative to map()
Because 1024 / 4 = 256, shifting the reading right by two bits gives the same 0 to 255 range:
int brightness = analogRead(POT_PIN) >> 2;This matches the map() result for every reading from 0 to 1023. It is shorter and slightly faster, but it works only for this exact 10-bit to 8-bit conversion. Use map() when the ranges are less tidy, since the intent is easier to read.
Making brightness look linear
The basic sketch works, but the dimming does not feel even. Human vision responds to brightness roughly logarithmically. Doubling the duty cycle does not look like doubling the brightness. Most of the visible change happens at the low end of the knob, and the top half looks almost the same.
A common fix is gamma correction, which here means squaring a normalized value so the low end rises more slowly:
const int POT_PIN = A0;
const int LED_PIN = 9;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
int raw = analogRead(POT_PIN);
float x = raw / 1023.0; // 0.0 to 1.0
int brightness = (int)(x * x * 255.0 + 0.5); // squared, rounded
analogWrite(LED_PIN, brightness);
}At the halfway position, x is about 0.5, so the squared value is 0.25 and the brightness is about 64 instead of 127. The sweep now spends more of the knob's travel in the dim range, where the eye is most sensitive. Many references use an exponent near 2.2, but 2 is a good starting point and needs no pow() call.
Common errors
- LED stays at one brightness or only switches on and off. The LED is probably on a pin without PWM. On an Uno,
analogWrite()on a non-PWM pin sets it HIGH for values of 128 or more and LOW otherwise. Move the LED to pin 3, 5, 6, 9, 10 or 11. - LED never lights. Check the LED polarity. The anode, the longer leg, faces the resistor and the pin.
- LED is dim even at full knob. Check that the potentiometer's outer terminals go to 5V and GND, and that the wiper goes to A0. A floating A0 gives erratic readings.
- Brightness flickers at one knob position. This is ADC noise, and the PWM value changes by one step now and then. Use the averaging and deadband techniques from the next chapters.
- Output jumps when the LED turns on. On a weak USB supply, LED current can pull the 5 V rail down slightly, which also shifts the ADC reference on boards that use the supply as reference. With a single LED this effect is small, but it grows with heavier loads.
- Using
analogRead()result directly inanalogWrite(). Values above 255 wrap around on AVR boards because only the low 8 bits are used. The LED would then brighten and reset four times over one knob sweep. Always rescale.
Other boards
The 0 to 255 range belongs to the Uno's 8-bit PWM, not to Arduino in general. Check your board's documentation for these differences:
- Output resolution. Some boards let you change it with
analogWriteResolution(bits), for example the Uno R4 and the Zero. After changing it, the maximum value is2^bits - 1, and yourmap()call must use that as its upper bound. - Input resolution. Boards that offer
analogReadResolution(bits)change the 1023 in yourmap()call in the same way. - PWM pins. The set of PWM-capable pins and their frequencies vary by board, so look up the pin diagram.
To keep a sketch portable, derive the limits from constants instead of writing 1023 and 255 inline. Define them once near the top and use them in map().
Exercise
A reading of 700 comes from A0 on an Uno. What value does map(700, 0, 1023, 0, 255) return, and what is the average voltage on the PWM pin?
Show answer
700 * 255 / 1023 = 178500 / 1023 = 174.5..., which integer arithmetic rounds down to 174. The duty cycle is 174 / 255 ≈ 68.2%, so the average voltage is about 5 V × 0.682 ≈ 3.41 V.
Exercise
You change the sketch to map(raw, 300, 700, 0, 255) so only the middle of the knob travel dims the LED. What goes wrong when the knob is turned fully clockwise, and how do you fix it?
Show answer
At raw = 1023, map() returns (1023 - 300) * 255 / 400 = 460 (rounded down), which is above 255. On an Uno, analogWrite() uses only the low 8 bits, so the LED brightness wraps around and the LED looks wrong near the ends of the knob. Wrap the result in constrain(brightness, 0, 255) so values below 300 give 0 and values above 700 give 255.
Exercise
Why does the gamma-corrected sketch give a dimmer LED than the basic sketch at the halfway knob position, and is the LED still reaching full brightness at the end of the travel?
Show answer
At the halfway position x is about 0.5, and squaring gives 0.25, so brightness is about 64 instead of 127. At raw = 1023, x is 1.0, and 1.0 × 1.0 × 255 is 255, so the LED still reaches full brightness. The curve only changes how much of the knob travel is spent at low brightness.