Sub topic 11
PWM Pins and `analogWrite`
Prerequisites
Assume you know the Arduino Uno's setup() and loop() functions, basic voltage and current, and how to connect an LED with a series resistor. The Uno does not create a continuously variable voltage on its digital pins. Instead, selected pins use pulse-width modulation (PWM) to switch the output quickly.
What PWM Does
PWM is a repeating digital signal. The signal alternates between HIGH and LOW. The percentage of each cycle spent HIGH is called the duty cycle.
A 25% duty cycle is HIGH for one quarter of each cycle. An LED connected to that signal appears dimmer because it receives power for less time. A 100% duty cycle stays HIGH, and a 0% duty cycle stays LOW.
On the Uno, the PWM-capable pins are:
| Pin | PWM marker | Common `analogWrite()` use |
|---|---|---|
| 3, 5, 6, 9, 10, 11 | `~` beside the pin number | LED brightness or motor speed |
The analogWrite() value normally ranges from 0 to 255. The value represents the duty cycle:
0means 0% duty cycle.128is about 50%.255means 100%.
The output voltage is still switching between approximately 0 V and 5 V. A multimeter may show an average-like voltage, but the pin is not producing a steady voltage such as 2.5 V.
Fading an LED
Connect an LED and an appropriate resistor between Uno pin 9 and GND. The longer LED lead usually connects toward the resistor and pin 9. The resistor limits current.
const int ledPin = 9; // Pin 9 supports PWM
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);
}
}The loops change the duty cycle gradually. The LED appears to fade in and out, although the microcontroller is switching it fully on and fully off.
Pin and Timer Details
The PWM pins share hardware timers. This matters when another library or feature uses the same timer. On a typical Uno, pins 5 and 6 use one timer, while pins 3 and 11 share another. Timer changes can affect PWM frequency or functions such as delay() and millis().
Calling analogWrite() on a non-PWM digital pin does not provide fading. A value of 0 produces LOW, while a nonzero value generally produces HIGH. Check the pin's ~ marker before choosing it.
Exercise
Exercise
What value should you pass to analogWrite() for approximately 25% brightness on a PWM pin?
Show answer
Pass about 64, because 25% of the 0–255 range is approximately 64.