What is PWM?
PWM (Pulse Width Modulation) rapidly switches a pin between HIGH and LOW to simulate voltages between 0V and 5V. The ratio of ON time to total time is the duty cycle.
Duty Cycle
0%: |___________________________| = 0V
25%: |██████_____________________| = 1.25V
50%: |█████████████______________| = 2.5V
75%: |██████████████████_________| = 3.75V
100%: |████████████████████████████| = 5V
analogWrite()
analogWrite(pin, value);
// value: 0 (always off) to 255 (always on)
Note: Despite the name, analogWrite() is digital. It produces a square wave, not a true analog voltage.
PWM Pins
Only pins marked with ~ support PWM:
| HERO Board | PWM Pins | |------------|----------| | Available | 3, 5, 6, 9, 10, 11 |
Applications
| Application | Value Range | |-------------|------------| | LED brightness | 0-255 | | Motor speed | 0-255 | | Servo position | (use Servo library) | | Speaker tone | (use tone() instead) |
PWM Frequency
Arduino PWM runs at:
- 490 Hz on pins 3, 9, 10, 11
- 980 Hz on pins 5, 6
This is fast enough that LEDs appear to dim smoothly, but you might hear a slight whine from motors or buzzers.