What is PWM in Arduino: Explanation and Example
PWM in Arduino stands for Pulse Width Modulation, a technique to simulate analog output using digital signals by switching them on and off very fast. It controls devices like LEDs or motors by changing the ratio of ON time to OFF time in a cycle, called duty cycle.How It Works
Pulse Width Modulation (PWM) works like turning a light switch on and off very quickly. Imagine you have a dimmer switch for a lamp, but instead of smoothly changing the brightness, you turn the lamp fully on and off many times per second. The lamp looks dimmer if it's on less time and brighter if it's on more time.
In Arduino, PWM uses digital pins that rapidly switch between HIGH (on) and LOW (off). The speed is so fast that devices like LEDs or motors respond as if they are getting a steady voltage between 0 and 5 volts. The percentage of time the signal is HIGH in each cycle is called the duty cycle, and it controls how bright or fast the device runs.
Example
This example shows how to use PWM to control the brightness of an LED connected to pin 9 on an Arduino board.
const int ledPin = 9; // PWM pin void setup() { pinMode(ledPin, OUTPUT); } void loop() { // Increase brightness for (int brightness = 0; brightness <= 255; brightness++) { analogWrite(ledPin, brightness); // Set PWM duty cycle delay(10); // Wait 10 milliseconds } // Decrease brightness for (int brightness = 255; brightness >= 0; brightness--) { analogWrite(ledPin, brightness); delay(10); } }
When to Use
Use PWM in Arduino when you want to control the power delivered to devices without using a digital on/off switch only. It is perfect for:
- Dimming LEDs smoothly to different brightness levels.
- Controlling motor speed by adjusting power.
- Generating audio tones or signals with varying intensity.
Because PWM simulates analog output, it helps save power and gives more control over devices than just turning them fully on or off.
Key Points
- PWM simulates analog signals using digital pins by switching them on and off rapidly.
- The duty cycle controls how much power the device receives.
- Arduino uses
analogWrite()to set PWM values from 0 (off) to 255 (fully on). - PWM is useful for dimming lights, controlling motor speed, and more.