Sub topic 11
PWM pins and analogWrite
This chapter covers how an Uno produces "in-between" output levels with pulse-width modulation (PWM). It assumes you know voltage, current, and resistance. It also assumes you can write a basic sketch with setup() and loop() and have used pinMode() and digitalWrite(). The earlier chapters on digital pins and analog inputs are the background here.
Why a digital pin needs PWM
A digital output pin on the Uno has two states. It sits at about 5V (HIGH) or at 0V (LOW). There is no setting for 2.5V. Many tasks need a middle level: dimming an LED, slowing a small motor, or driving a hobby servo or buzzer with a varying signal.
The microcontroller solves this by switching the pin on and off very fast. This is pulse-width modulation (PWM). The ratio of on-time to total time in each cycle is the duty cycle. A load that responds slowly, such as an LED seen by your eye or a motor with inertia, reacts to the average voltage rather than to each pulse.
The average voltage is approximately:
average voltage = 5V × duty cycle| Duty cycle | `analogWrite` value | Average voltage (5V supply) |
|---|---|---|
| 0% | 0 | 0V |
| 25% | 64 | about 1.25V |
| 50% | 128 | about 2.5V |
| 75% | 191 | about 3.75V |
| 100% | 255 | 5V |
The pin is never at an intermediate voltage. At every instant it is either at 5V or at 0V. Only the average is intermediate.
Which pins support PWM
Only some pins can produce PWM. On the Uno R3 these are pins 3, 5, 6, 9, 10, and 11. They are marked with a tilde (~) on the board silkscreen. The ATmega328P microcontroller generates the signal in hardware using its timers, so the sketch does not have to toggle the pin itself.
Each PWM pin belongs to one of three timers:
| Timer | Pins | Timer width |
|---|---|---|
| Timer0 | 5, 6 | 8-bit |
| Timer1 | 9, 10 | 16-bit (used in 8-bit mode by `analogWrite`) |
| Timer2 | 3, 11 | 8-bit |
This grouping matters for two reasons. Pins on the same timer share a frequency. Timers also have other jobs, which causes the conflicts described later in this chapter.
Using analogWrite
The function is analogWrite(pin, value). The value is an integer from 0 to 255, which is 8 bits of resolution.
analogWrite(pin, 0)holds the pin LOW continuously.analogWrite(pin, 255)holds the pin HIGH continuously.- Values in between produce a pulse train with duty cycle
value / 255.
You do not need to call pinMode(pin, OUTPUT) before analogWrite() on AVR boards such as the Uno, because analogWrite() configures the pin. Calling it anyway is good practice. It documents your intent and keeps the sketch portable to boards where it is required.
Here is a complete sketch that fades an LED on pin 9 up and down:
const int ledPin = 9; // a PWM-capable pin on the Uno
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
for (int level = 0; level <= 255; level++) {
analogWrite(ledPin, level);
delay(5);
}
for (int level = 255; level >= 0; level--) {
analogWrite(ledPin, level);
delay(5);
}
}Wire the LED's anode (long leg) through a 220 Ω resistor to pin 9, and the cathode to GND. Each sweep takes 256 steps × 5 ms, about 1.3 seconds.
Name confusion: "analog" write
The name analogWrite is misleading. The Uno has no digital-to-analog converter, so nothing here produces a true analog voltage. The function is named for its effect, which is a variable output level. It is unrelated to analogRead(), which uses the analog-to-digital converter on pins A0 to A5. You cannot call analogWrite() on A0 to A5 and expect PWM. Those pins have no PWM hardware.
Mapping input to output
A frequent pattern is to read a potentiometer and use it to set brightness. The ADC returns 0 to 1023 (10 bits) and analogWrite accepts 0 to 255 (8 bits), so you must scale the value. Dividing by 4 works. The map() function does the same job more explicitly.
const int potPin = A0;
const int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
int raw = analogRead(potPin); // 0 to 1023
int level = map(raw, 0, 1023, 0, 255); // 0 to 255
analogWrite(ledPin, level);
}If you pass a value above 255 to analogWrite(), it does not clip cleanly in every case. Values are truncated to 8 bits on some cores, so 256 can behave like 0. Use constrain(value, 0, 255) whenever the value comes from arithmetic that might overshoot.
PWM frequency
The default frequencies on the Uno are:
| Pins | Approximate frequency |
|---|---|
| 5, 6 | 980 Hz |
| 3, 9, 10, 11 | 490 Hz |
At these rates the flicker is invisible to the eye for an LED. For other loads the frequency matters:
- Motors driven through a transistor can whine audibly at these frequencies. Frequencies above about 20 kHz are inaudible, so projects often raise the PWM frequency.
- Switching power circuits and some LED drivers may expect a specific frequency.
- Cameras filming an LED can show banding at low frequencies.
- Filtering to a DC level with a resistor and capacitor works better at higher frequencies, because less ripple remains.
You can change the frequency by writing to the timer prescaler registers directly, or by using a library. Changing a timer's settings affects everything that uses it.
Conflicts with other features
Because PWM relies on shared timers, some library choices disable it on specific pins.
- The Servo library uses Timer1. On the Uno it disables
analogWrite()on pins 9 and 10, whether or not a servo is attached to them. - The
tone()function uses Timer2. While it runs, PWM on pins 3 and 11 is affected. Only one tone can play at a time. - SPI uses pin 11 for MOSI, which is also a PWM pin. If you use an SPI device, treat pin 11 as taken.
Plan your pin assignments before wiring. A common choice is to put LEDs on pins 5 and 6 or 9 and 10, and leave other pins free for libraries.
Electrical limits still apply
PWM changes the average voltage, not the current capacity of the pin. An Uno pin should supply no more than 20 mA in normal use, with an absolute maximum of 40 mA. A lone LED with a resistor is fine. A motor, a relay coil, or a strip of LEDs is not. For those loads the pin should drive a transistor or MOSFET that switches a separate supply.
Remember also that average voltage is not what the load sees at every instant. A motor that is driven from a pin through a transistor receives full-voltage pulses. A motor driver or an inductive load needs a flyback diode across it to absorb voltage spikes when the current switches off.
Common mistakes
- Using a non-PWM pin.
analogWrite()on pin 4, for example, does not give PWM. On the Uno it writes only HIGH for values of 128 or more and LOW for lower values. The sketch compiles and the LED jumps between off and fully on. - Expecting linear brightness. The eye responds roughly logarithmically to light. A duty cycle of 50% looks much brighter than half of full brightness. For smooth-looking fades, map the value through a curve such as a gamma table.
- Measuring with a multimeter. A basic meter on a PWM pin shows something near the average voltage, but readings can be unsteady. An oscilloscope shows the real waveform.
- Forgetting the series resistor. PWM does not limit current. The LED still needs a resistor.
- Library conflicts. If a PWM pin stops working after you add
Servo.hortone(), check the timer table above.
Exercise
You want to dim an LED on pin 4 of an Uno with analogWrite(4, 100), and later add the Servo library to your sketch. What happens on pin 4, and which two PWM pins does the Servo library make unusable on the Uno?
Show answer
Pin 4 has no PWM hardware, so analogWrite(4, 100) just sets it LOW because 100 is below 128. The LED will not be dimmed. Move the LED to a PWM pin (3, 5, 6, 9, 10, or 11). The Servo library uses Timer1, which disables analogWrite() on pins 9 and 10, so choose pin 3, 5, 6, or 11 for the LED.
Exercise
A sketch calls analogWrite(6, 64). What is the duty cycle, what is the approximate average voltage on a 5V Uno, and what is the approximate PWM frequency on that pin?
Show answer
The duty cycle is 64 / 255, about 25%. The average voltage is about 5V × 0.25 = 1.25V. Pin 6 is on Timer0, so its default frequency is about 980 Hz.
Exercise
You read a potentiometer with analogRead(A0), which returns 0 to 1023, and want to set an LED's brightness on pin 9. Write the line that converts the reading to a valid analogWrite value, and say why the conversion is needed.
Show answer
int level = map(analogRead(A0), 0, 1023, 0, 255); (dividing by 4 also works). The conversion is needed because the ADC has 10-bit resolution (0 to 1023) while analogWrite accepts only 8-bit values (0 to 255). Larger values wrap or behave unpredictably.