Sub topic 3
Controlling brightness with a potentiometer
This chapter assumes you know the setup() and loop() structure, pinMode(), analogWrite(), and how to wire an LED in series with a current-limiting resistor. You should also know Ohm's law at an introductory level. It covers five parts of the plan in order: a potentiometer control, a non-blocking fade, gamma correction, PWM frequency, and PWM limits.
Controlling brightness with a potentiometer
Connect the outer pins of a potentiometer to 5V and GND, and its middle pin (the wiper) to A0. analogRead() returns 0 to 1023, while analogWrite() accepts 0 to 255, so shift the reading right by two bits.
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); // 0..255
}Fading without blocking
delay() halts the whole sketch. millis() returns the milliseconds since the board started, so you can advance the fade on a timer and leave loop() free for other work.
const uint8_t LED_PIN = 9;
const unsigned long INTERVAL_MS = 20;
unsigned long lastStepTime = 0;
int brightness = 0;
int step = 5;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - lastStepTime >= INTERVAL_MS) {
lastStepTime = now;
analogWrite(LED_PIN, brightness);
if (brightness + step < 0 || brightness + step > 255) {
step = -step;
}
brightness += step;
}
}Making fades look even with gamma correction
Eyes perceive brightness non-linearly. Doubling the duty cycle does not look twice as bright. A gamma value of about 2.2 corrects for this.
uint8_t gammaCorrect(uint8_t level) {
float normalized = level / 255.0;
return (uint8_t)(pow(normalized, 2.2) * 255.0 + 0.5);
}PWM frequency and the timers behind it
On an Uno, pins 5 and 6 switch at about 980 Hz, and the other PWM pins (3, 9, 10, 11) at about 490 Hz. These rates come from hardware timers. Timer0 drives pins 5 and 6 and also the millis() clock. Timer1 drives pins 9 and 10, and Timer2 drives pins 3 and 11. Changing Timer0's settings breaks millis() and delay().
Limits of PWM and driving larger loads
- Each Uno I/O pin is rated for about 40 mA. Use a resistor to keep LED current within that limit.
analogWrite()gives 256 levels only.- Motors and relays need a transistor or MOSFET, with a flyback diode for inductive loads. Do not connect them straight to a PWM pin.
Exercise
The potentiometer sketch uses reading >> 2. Why is a right shift by two used, and what would happen without it?
Show answer
A 10-bit analogRead() returns 0 to 1023, but analogWrite() accepts only 0 to 255. Shifting right by two divides by four, which maps the range correctly. Without it, values above 255 would be cast to a shorter 8-bit value and produce wrong brightness.