Pulse-Width Modulation (PWM) & Analog Output
PWM is a technique for getting analog-like results with digital means. It works by turning a signal on and off very rapidly, and varying the ratio of on-time to off-time (the duty cycle).
PWM uses the analogWrite() function with an 8-bit resolution (0–255). Note: this is not true analog output — it's a digital approximation that looks analog when connected to a capacitor or inductor (smoothing filter).
LED Brightness Control
By varying the PWM duty cycle, you can fade an LED in and out:
int ledPin = 9; // PWM-capable pin (has ~ symbol)
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
// Fade in
for (int i = 0; i <= 255; i++) {
analogWrite(ledPin, i);
delay(5);
}
// Fade out
for (int i = 255; i >= 0; i--) {
analogWrite(ledPin, i);
delay(5);
}
}Understanding 8-bit Resolution
The analogWrite() function accepts values from 0 to 255:
- 0 = 0% duty cycle (always off)
- 128 = 50% duty cycle (half on, half off)
- 255 = 100% duty cycle (always on)
The frequency is approximately 490 Hz on most Arduino pins and ~980 Hz on pins 5 and 6.
Servo Motor Control
PWM is essential for controlling hobby servo motors. Servos expect a PWM signal with a 20ms period (50 Hz), where the pulse width determines the angle:
| Pulse width | Angle |
|---|---|
| 1000 µs | 0° |
| 1500 µs | 90° (center) |
| 2000 µs | 180° |
The Arduino Servo library handles this automatically:
#include <Servo.h>
Servo myServo;
void setup() {
myServo.attach(9); // Attach servo to pin 9
}
void loop() {
myServo.write(0); // Move to 0°
delay(1000);
myServo.write(90); // Move to 90°
delay(1000);
myServo.write(180); // Move to 180°
delay(1000);
}PWM Frequency Considerations
- Pins 5 and 6: ~980 Hz
- Pins 3, 9, 10, 11: ~490 Hz
- Pins 5, 6, 9, 10, 11, 3, 11: Higher PWM frequency can affect infrared libraries and tone() function
If you use Servo.h or Tone() on pins 9 and 10, they will conflict because they both use the same timer. Plan your pin assignments carefully.
Key Takeaways
analogWrite(pin, value)accepts values 0–255 (8-bit PWM)- PWM simulates analog output by varying the duty cycle
- Servo motors require specific PWM pulse widths (1000–2000 µs)
- The Servo library abstracts PWM details for servo control
- Pin conflicts can occur between Servo, Tone(), and certain PWM pins
Resources
- Arduino.cc - analogWrite: https://www.arduino.cc/reference/en/language/functions/analog-output/analogwrite/
- PWM Tutorial: https://www.youtube.com/watch?v=8JbG6TrS8DY
- Arduino.cc - Servo Library: https://www.arduino.cc/reference/en/language/functions/servo/
- Video: Servo Motor Control - https://www.youtube.com/watch?v=9VZty4UjQZk
- TinkerCAD Circuits - PWM: https://www.tinkercad.com/circuits