Sub topic 6
Setting brightness with analogWrite()
This chapter covers the Arduino function that turns the PWM ideas from earlier chapters into code. It assumes you can write a basic sketch with setup() and loop(), use pinMode() and digitalWrite(), wire an LED and resistor on a breadboard, and apply Ohm's law at an introductory level. It also assumes you have an LED with a current-limiting resistor on pin 9, as in the previous wiring chapter. The examples target an Arduino Uno (ATmega328P). Other boards differ in the details noted below.
What analogWrite() does
analogWrite(pin, value) starts a PWM signal on pin. The value argument sets the duty cycle on an 8-bit scale from 0 to 255.
analogWrite(9, 128);After this call, pin 9 switches between 5 V and 0 V at a fixed rate. It spends about half of each period at 5 V. The call returns immediately. The hardware keeps generating the waveform with no further work from your code until you change the pin's mode or write a new value.
The name is misleading. The pin never outputs a true analog voltage. It outputs a fast digital square wave, and the LED, your eye, or a filter circuit averages it. The Uno has no digital-to-analog converter.
The value-to-duty mapping
The duty cycle is the value divided by 255. The average voltage on a 5 V board is 5 V times that fraction.
| `value` | Duty cycle | Average voltage (5 V board) |
|---|---|---|
| 0 | 0% | 0 V |
| 16 | 6.3% | 0.31 V |
| 64 | 25.1% | 1.25 V |
| 128 | 50.2% | 2.51 V |
| 191 | 74.9% | 3.75 V |
| 255 | 100% | 5 V |
Two details matter here. The scale has 256 steps, but the divisor is 255, so 128 is slightly more than half. Also, the average voltage is only a model. An LED does not respond to average voltage. It responds to current, and the next sections show where the model holds and where it does not.
What happens inside the call
On an Uno, analogWrite() handles three cases differently.
- Value 0 sets the pin LOW with a normal digital write and disconnects it from the timer.
- Value 255 sets the pin HIGH the same way.
- Any other value is written into the output compare register of the timer that drives that pin. The timer hardware then toggles the pin.
The rest of the behavior follows from this.
Pins without PWM
If you call analogWrite() on a pin with no timer output, such as pin 8 on an Uno, nothing fails. The core library falls back to a digital write. Values of 128 or more give HIGH and lower values give LOW. The LED is either fully on or fully off and never dims. If a fade "snaps" instead of ramping, check the pin number first.
On the Uno, the PWM pins are 3, 5, 6, 9, 10, and 11. They are marked with a ~ on the board.
The compare register and the 8-bit range
An 8-bit timer register holds values 0 to 255 only. The call does not clamp its argument for you. A value such as 300 or -5 is outside the documented range and gives results you should not rely on. If the value comes from a calculation, sensor, or serial input, clamp it yourself:
analogWrite(LED_PIN, constrain(computedValue, 0, 255));A first complete sketch
This sketch steps through five brightness levels, holding each for one second. Run it to confirm your wiring before writing anything more elaborate.
const uint8_t LED_PIN = 9;
const uint8_t LEVELS[] = {0, 16, 64, 128, 255};
const uint8_t LEVEL_COUNT = sizeof(LEVELS) / sizeof(LEVELS[0]);
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
for (uint8_t i = 0; i < LEVEL_COUNT; i++) {
analogWrite(LED_PIN, LEVELS[i]);
delay(1000);
}
}You should see off, very dim, dim, medium, and full brightness. Most people see 16 as clearly visible and 128 as much brighter than "half". The step from 0 to 16 looks bigger than the step from 128 to 255. This is the non-linear response of the eye, and a later chapter on gamma correction deals with it. It is not a bug in the sketch.
Do you need pinMode()?
Strictly, no. On AVR boards analogWrite() configures the pin as an output itself. Calling pinMode(pin, OUTPUT) in setup() is still the better habit. It documents intent, and it keeps the sketch correct on boards whose core behaves differently.
Working in percent
Raw 0 to 255 values are awkward when you think in brightness percentages. A small helper keeps the conversion and the clamping in one place.
const uint8_t LED_PIN = 9;
uint8_t percentToDuty(int percent) {
percent = constrain(percent, 0, 100);
return (uint8_t)((percent * 255L + 50) / 100); // +50 rounds to nearest
}
void setBrightnessPercent(int percent) {
analogWrite(LED_PIN, percentToDuty(percent));
}
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
for (int p = 0; p <= 100; p += 10) {
setBrightnessPercent(p);
delay(500);
}
}The L suffix on 255L forces the multiplication into a long. On an Uno, int is 16 bits, and 100 * 255 is 25500, which fits. The suffix protects you if you later change the scale to something larger, for example when mapping a 1000-step input. The + 50 before dividing by 100 rounds to the nearest integer instead of truncating.
For arbitrary input ranges, map() also works, but it uses integer math and does not clamp:
int duty = map(sensorValue, 0, 1023, 0, 255);
duty = constrain(duty, 0, 255);Hardware behavior you should know about
Frequency differs by pin
Not all PWM pins on an Uno run at the same rate.
| Pins | Timer | Approximate frequency |
|---|---|---|
| 5, 6 | Timer0 | 980 Hz |
| 9, 10 | Timer1 | 490 Hz |
| 3, 11 | Timer2 | 490 Hz |
For a visible LED, both rates look steady. The difference matters for motors, audio, and camera work, and a later chapter covers it.
Shared timers create side effects
Because PWM comes from timers, other features that use the same timer can interfere with it.
- Timer0 also drives
millis(),micros(), anddelay(). Pins 5 and 6 therefore cannot be reconfigured freely without breaking timekeeping. Their duty cycle at very low values is also slightly higher than the formula predicts. - The
Servolibrary takes over Timer1. Using it disablesanalogWrite()on pins 9 and 10. tone()uses Timer2 and disables PWM on pins 3 and 11 while it runs.
If PWM stops working after you add a library, check which timer the library uses.
digitalWrite() cancels PWM
After analogWrite(pin, 100), a later digitalWrite(pin, HIGH) turns PWM off on that pin and sets a steady level. To return to dimming, call analogWrite() again. The reverse is also true. A pin you drove with analogWrite(pin, 0) is a plain LOW output.
Common errors
The same few mistakes account for most "PWM doesn't work" reports.
- Wrong pin. The LED is on pin 8, 12, or 13, and
analogWrite()gives only on/off. Move it to a~pin. - Value outside 0 to 255. A computed value overflows, for example a
uint8_tcounter that wraps from 255 to 0 and makes the LED jump dark. Use anintfor the working variable and clamp before writing. - Passing a percentage directly.
analogWrite(pin, 50)is about 20% duty, not 50%. - Missing resistor or reversed LED. If the LED is dark at every value including 255, check polarity first. The long leg (anode) faces the pin side of the resistor.
- A conflicting library.
Servoortone()is active on the same timer. - Expecting linear brightness. The sketch works but looks uneven. That is perception, not a fault.
Measuring what you set
If you have a multimeter, set it to DC volts and measure across the LED branch while a fixed value is active. On a pin driven at a PWM frequency of 490 Hz, a basic meter averages the waveform and reads close to the table values above. The reading is higher than the LED sees in practice, because the LED's forward voltage clamps its terminal voltage once it conducts. You measure the average at the pin, not the current through the LED.
An oscilloscope shows the actual waveform: the pulse width scales with value, and the frequency stays constant. If one is available, this is the clearest way to see that analogWrite() changes the width of the pulse and not its height.
Summary of the interface
analogWrite(pin, value)takes a pin and an integer from 0 to 255.- It produces a duty cycle of
value / 255on a PWM-capable pin and returns immediately. - A value of 0 or 255 produces a steady LOW or HIGH.
- On a pin without PWM, it falls back to HIGH for 128 or more and LOW below that.
- The library does not clamp values, so clamp them yourself.
- Timers shared with
millis(),Servo, andtone()can affect or disable specific pins.
Exercise
On an Uno powered at 5 V, you call analogWrite(10, 191). What are the duty cycle and the average voltage at the pin, and what would analogWrite(7, 191) do instead?
Show answer
Pin 10 is a PWM pin, so the duty cycle is 191 / 255 = about 74.9%, and the average voltage is about 0.749 x 5 V = 3.75 V. Pin 7 has no timer output, so analogWrite(7, 191) falls back to a digital write. Because 191 is 128 or more, the pin is held steady HIGH at 5 V and does not dim.
Exercise
A sketch keeps a brightness variable declared as uint8_t and increases it by 10 each pass, writing it with analogWrite(). Why does the LED jump from bright to dark after reaching the top, and how would you fix it?
Show answer
A uint8_t holds 0 to 255, so adding 10 to a value above 245 wraps around to a small number, and the LED suddenly goes dim or dark. The fix is to keep the working value in an int, check the range before adding the step (or reverse direction at the limits), and clamp with constrain(value, 0, 255) before calling analogWrite().