Sub topic 3
PWM: faking analog output with analogWrite
This chapter assumes you can upload sketches, write basic Arduino C++ (setup(), loop(), variables, functions), and use pinMode() and digitalWrite(). It also assumes you know what voltage, current, and ground are. The previous chapters explained why a pin cannot power a motor and why external power needs a common ground. This chapter explains the signal you will use to control speed and position: pulse-width modulation (PWM).
Why a digital pin needs a trick
A digital pin has two states. It is either HIGH (about 5 V on a 5 V board such as the Uno) or LOW (about 0 V). It cannot output 2.5 V. A pin that does so would need a digital-to-analog converter (DAC), and the ATmega328P on an Uno has none.
PWM gets around this. The pin switches between HIGH and LOW very quickly. The load (an LED, a motor, a filter) responds to the average voltage over time, not to each individual switch.
If the pin is HIGH for half of each cycle, the average is about 2.5 V. If it is HIGH for a quarter of each cycle, the average is about 1.25 V. The pin never outputs 2.5 V or 1.25 V at any instant. It outputs 5 V or 0 V, and the load averages the result.
The two numbers that define a PWM signal
Every PWM signal has two properties.
- Frequency is how many complete on/off cycles happen each second, measured in hertz (Hz). The period is the length of one cycle, which is 1 divided by the frequency.
- Duty cycle is the fraction of each period that the signal is HIGH, usually given as a percentage.
| Duty cycle | Pin is HIGH for | Average voltage (5 V board) |
|---|---|---|
| 0% | never | 0 V |
| 25% | one quarter of the period | about 1.25 V |
| 50% | half of the period | about 2.5 V |
| 75% | three quarters of the period | about 3.75 V |
| 100% | always | 5 V |
The formula is:
average voltage = duty cycle × supply voltage
Using analogWrite()
Arduino exposes hardware PWM through analogWrite(pin, value). The name is misleading. The function does not produce a true analog voltage and has nothing to do with analogRead().
pinmust be a PWM-capable pin.valueis an integer from 0 to 255. This is an 8-bit resolution, which gives 256 steps.0means always LOW.255means always HIGH.- Any value in between sets the duty cycle to
value / 255.
For example, analogWrite(pin, 64) gives a duty cycle of 64 / 255, which is about 25%. analogWrite(pin, 128) is about 50%.
Which pins support PWM
On the Uno and Nano, the PWM pins are marked with a tilde (~) on the board: 3, 5, 6, 9, 10, and 11. Other boards differ. The Mega has many more, and the Uno R4 and ESP32 boards have their own lists. Check the pinout of your board before you wire anything.
Calling analogWrite() on a pin without PWM hardware does not raise an error. On AVR boards, the pin is set HIGH for values of 128 and above and LOW for values below 128. This is a common source of "my motor is either off or full speed" bugs.
You do not need to call pinMode(pin, OUTPUT) before analogWrite() on AVR boards, because analogWrite() sets it up. Calling it anyway is good practice and works on every board.
Example: fading an LED
An LED is the safest way to see PWM working. This sketch assumes an LED with a 220 ohm resistor between pin 9 and ground.
const int LED_PIN = 9;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
for (int level = 0; level <= 255; level += 5) {
analogWrite(LED_PIN, level);
delay(20);
}
for (int level = 255; level >= 0; level -= 5) {
analogWrite(LED_PIN, level);
delay(20);
}
}The same pattern, a loop that changes the value passed to analogWrite(), drives the DC motor example later in this tutorial. The only difference is that the pin goes to a MOSFET gate instead of an LED.
Frequency: what the Uno actually does
The default PWM frequency depends on which hardware timer drives the pin. On an Uno:
| Pins | Timer | Default frequency |
|---|---|---|
| 5, 6 | Timer 0 | about 980 Hz |
| 9, 10 | Timer 1 | about 490 Hz |
| 3, 11 | Timer 2 | about 490 Hz |
Timer 0 is also used by millis(), micros(), and delay(). Changing its settings breaks timekeeping, so avoid that unless you know what you are doing.
Pins 5 and 6 are close to 980 Hz, but their duty cycles at the very low and very high ends are slightly off. A value of 0 may not give a perfectly constant LOW output on pins 5 and 6 under some conditions. For a motor this rarely matters.
Why frequency matters for motors
- Audible whine. A frequency between about 20 Hz and 20 kHz can be heard. A motor driven at 490 Hz or 980 Hz often whines or buzzes, because the windings vibrate at the PWM frequency. Some people find this acceptable for a prototype. Others want it moved above hearing range.
- Smoothness at low speed. A motor has inertia and inductance, so it filters the pulses. At a low frequency and a low duty cycle, the motor can speed up and slow down with each pulse and run unevenly.
- Switching losses. A MOSFET dissipates extra heat each time it switches. A higher frequency means more switches per second and more heat. Hundreds of hertz are not an issue for small loads, but tens of kilohertz can matter for larger ones.
For small hobby motors, the default frequencies are usually fine. If the whine bothers you, you can change the timer prescaler on a pin that does not affect millis(). For example, on an Uno, this sets Timer 1 (pins 9 and 10) to about 31 kHz:
const int MOTOR_PIN = 9;
void setup() {
pinMode(MOTOR_PIN, OUTPUT);
// Timer 1 prescaler bits: clear the low three, then set to 001 (divide by 1)
TCCR1B = (TCCR1B & 0b11111000) | 0x01;
}
void loop() {
analogWrite(MOTOR_PIN, 128);
}This register-level code works only on ATmega328P boards such as the Uno and Nano. It will not compile or behave the same on other chips. It also affects the Servo library on Uno, which uses Timer 1 (see below), so do not combine the two.
PWM is not a steady voltage
The averaging idea works well for loads that respond slowly. It does not work for everything.
- An LED looks dimmer because the eye averages the flicker. A camera may show banding.
- A motor averages the pulses through its inertia and inductance, so its speed follows the duty cycle roughly.
- A voltmeter on a PWM pin may show a value that is steady or one that jumps, depending on the meter. The pin is still switching between 0 V and 5 V.
- A device that expects a steady voltage, such as a sensor input or an audio amplifier, will see the raw pulses unless you add a low-pass filter. A resistor and capacitor in series can smooth PWM into a steady voltage, but this is a separate technique.
The pin voltage is always 0 V or 5 V. If a motor needs 5 V to run and you give it 50% PWM, it does not receive 2.5 V steadily. It receives full-voltage pulses with gaps between them. The motor's average speed is lower, but the current through the switch still comes in full-size pulses. This matters when you pick a MOSFET and a power supply, which later chapters cover.
Speed is not exactly linear
You might expect that 50% duty gives 50% of the speed. In practice the relationship is only rough.
- Dead zone. A motor has friction, so a very small duty cycle may not move it at all. A motor that starts turning only above a value of 60 will not move at values of 1 to 59.
- Load dependence. The same duty cycle gives different speeds with different loads.
- Supply voltage. Duty cycle scales the supply voltage. A 6 V supply at 50% gives a lower average than a 12 V supply at 50%.
If your motor does not start at a low value, find the lowest value at which it reliably turns, and map your speed range to start there. The map() function does this:
const int MOTOR_PIN = 5;
const int MIN_PWM = 60; // lowest value at which this motor starts; measure yours
// percent: 0 to 100
void setSpeedPercent(int percent) {
percent = constrain(percent, 0, 100);
if (percent == 0) {
analogWrite(MOTOR_PIN, 0);
} else {
analogWrite(MOTOR_PIN, map(percent, 1, 100, MIN_PWM, 255));
}
}
void setup() {
pinMode(MOTOR_PIN, OUTPUT);
}
void loop() {
setSpeedPercent(25);
delay(2000);
setSpeedPercent(0);
delay(1000);
}Remember that the pin should drive a MOSFET gate, not the motor directly. The wiring comes in a later chapter.
PWM and servos
A hobby servo also uses a pulse signal, but it is not the same as analogWrite() PWM. A servo reads the width of each pulse (about 1 to 2 ms) repeated roughly every 20 ms, and the width sets the angle. The duty cycle is small, around 5% to 10%, and it carries position, not power.
Because of this, you should use the Servo library for servos and not analogWrite(). The next chapters explain the servo signal and the library in detail.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Output is only fully on or fully off | Pin has no PWM hardware | Move to a pin marked `~` |
| Value above 255 behaves oddly | `analogWrite()` accepts 0 to 255 only | Use `constrain()` |
| `delay()` or `millis()` runs at the wrong speed | Timer 0 prescaler changed | Revert the change, or use a different timer |
| Servo stops working after a frequency change | Timer 1 prescaler changed | Remove the change |
| Motor whines | PWM frequency is in the audible range | Raise the frequency, or accept it |
| Motor will not start at low values | Dead zone from friction | Set a minimum value |
| Voltmeter shows a strange number | Meter averages pulses | Use an oscilloscope, or a meter with an averaging mode |
Exercise
You call analogWrite(6, 191) on an Uno. What duty cycle does this give, what is the average voltage on a 5 V board, and why can a motor wired directly to that pin still not be powered safely?
Show answer
The duty cycle is 191 / 255, which is about 75%. The average voltage is about 0.75 × 5 V, or 3.75 V. A motor must not be wired directly to the pin because an I/O pin can supply only about 20 mA safely (40 mA absolute maximum on an ATmega328P), and a motor draws much more. The pin should drive a transistor or driver, and the motor should have its own supply.
Exercise
A motor on pin 7 of an Uno is either off or at full speed no matter what value you pass to analogWrite(). What is the most likely cause, and what should you do?
Show answer
Pin 7 on an Uno has no hardware PWM. On AVR boards analogWrite() sets such a pin HIGH for values of 128 and above and LOW below that. Move the signal wire to a PWM pin (3, 5, 6, 9, 10, or 11) and update the pin constant in the sketch.
Exercise
You change the Timer 0 prescaler on an Uno to move pins 5 and 6 to a higher PWM frequency. Afterwards, delay(1000) lasts a different length of time. Why, and what is the safer alternative?
Show answer
Timer 0 also drives millis(), micros(), and delay(). Changing its prescaler changes how fast those functions count, so all timing in the sketch is wrong. The safer alternative is to put the motor signal on a pin driven by Timer 1 or Timer 2 (pins 9, 10, 3, or 11) and change that timer instead, provided the Servo library is not in use on Timer 1.