Chapters

8 PWM Control: Signals and Duty-Cycle Behaviour

actuators
pwm
control

8.1 Start With the Decision

This section: Start With the Decision — PWM switches power on and off in short pulses.

PWM switches power on and off in short pulses. The motor winding current rises and falls between pulses; its average current and mechanical inertia shape torque and motion. Duty cycle is the share of each cycle spent on. It links the digital command to the motor’s physical motion.

8.2 Route Overview

This section: Route Overview — This is part 1 of 2.

This is part 1 of 2. Continue with PWM Control: Frequency and Driver Decisions.

8.3 Part Objectives

This section: Part Objectives

  • Compute PWM duty cycle and average drive level.
  • Explain how load response changes across a PWM cycle.

8.4 Start With the Story

This section: Start With the Story — Picture a small fan that must run gently at normal temperature and harder during a heat rise.

Prove the Physical Output at Three Settings

Picture a small fan that must run gently at normal temperature and harder during a heat rise. A changing command number is not enough; the reviewer needs the drive timing, supply condition, and measured fan result.

An actuator is a device that turns an electrical command into physical action. A microcontroller is a small computer built to read inputs and control outputs. Modulation means changing a signal over time to carry a setting. Duty cycle means the share of each switching period spent on.

Command the low, middle, and high settings. Stall the fan briefly within a safe test, lower the supply, repeat a setting, and restart the controller. Record command, timing, current, and physical response together, and keep any urgent heat action local.

This runway does not prove motor life or make one switching rate safe for every load. The deeper sections cover waveform timing, driver stages, resolution, filtering, load limits, and measurement.

Picture a fan that should start gently, run quietly, and still move enough air on a hot afternoon. PWM is the controller’s way to ask for less or more effort, but the physical result depends on frequency, duty cycle, driver losses, motor inertia, and the load.

Use PWM as an actuator command with evidence around it. The right setting is not just a number from 0 to 255; it is a duty, frequency, ramp, and feedback choice that keeps motion, brightness, heat, or position under control.

In 60 Seconds

Pulse Width Modulation (PWM) is a digital technique that simulates analog control by rapidly switching power on and off at a specific duty cycle. It enables precise control of motor speed, LED brightness, and servo position using simple digital microcontroller pins without analog hardware.

Key Concepts
  • PWM (Pulse Width Modulation): A technique for controlling average power by rapidly switching a signal between HIGH and LOW; duty cycle = (time HIGH) / (period) x 100%; a 50% duty cycle delivers 50% of the supply voltage as an average
  • Duty Cycle: The percentage of one PWM period during which the signal is HIGH; 0% = always off, 100% = always on; controls LED brightness, motor speed, heater temperature, and servo position (within a specific pulse width range)
  • PWM Frequency: The number of complete PWM cycles per second; motor control: use 20 kHz+ to avoid audible noise; hobby servos commonly use about 50 Hz (20 ms period), subject to the model’s supported frame rate; LED dimming: any frequency above 200 Hz to prevent visible flicker
  • PWM Resolution: The number of discrete duty cycle steps; ESP32 LEDC peripheral: 1-16 bit configurable; Arduino Uno: 8-bit (256 steps); higher resolution provides finer control but requires more timer bits
  • analogWrite() / ledcWrite(): Arduino function (analogWrite) and ESP32-specific function (ledcWrite) for setting PWM duty cycle; Arduino Uno/Nano output 8-bit 490 Hz PWM on most pins; ESP32 uses the LEDC peripheral requiring channel configuration before use
  • Servo Pulse Width: Hobby servos commonly use a repeated frame near 50 Hz; pulse width controls position: 1 ms = 0 degrees (minimum), 1.5 ms = 90 degrees (center), 2 ms = 180 degrees (maximum); check the model’s supported frame rate and use a suitable servo library
  • Dead Time: A brief delay inserted between turning one switch off and its complementary switch on in an H-bridge or inverter; prevents shoot-through (both high and low side switches on simultaneously), which would create a short circuit across the power supply
  • Soft Start / Ramp Control: Gradually increasing PWM duty cycle from 0 to operating value at startup rather than switching immediately to full power; reduces inrush current, mechanical shock, and EMI during motor startup

Learning Objectives

This section: Learning Objectives

  • Calculate PWM duty cycles for various actuator applications
  • Configure ESP32 PWM channels for different frequencies and resolutions
  • Use the interactive PWM calculator for design decisions
  • Analyze PWM timing parameters for servo position control
  • Optimize PWM frequency for different actuator types
Chapter Roadmap
  • Start With the Story
  • In 60 Seconds
  • Key Concepts
  • For Beginners: PWM Control
  • How It Works: PWM Creates “Fake” Analog Voltage
  • PWM Fundamentals
  • Putting Numbers to It
  • Phoebe’s Field Notes: Why PWM Becomes Smooth Motion
  • Try It: PWM Motor Speed Control
  • Concept Check: PWM Fundamentals
  • Checkpoint: Average Command
  • Interactive PWM Calculator
  • PWM Applications by Frequency
  • Servo PWM Timing
  • ESP32 PWM Configuration
  • PWM Speed to Value Conversion
  • Checkpoint: Timer Values
  • Why Duty Cycle Matters for IoT
  • Worked Example: Smart Greenhouse Ventilation Fan

Imagine flicking a light switch on and off very rapidly — so fast that the light appears to be dimmed rather than blinking. That is essentially what PWM (Pulse Width Modulation) does. By controlling how long the power stays on versus off in each cycle, you can smoothly adjust a motor’s speed or an LED’s brightness using just a simple digital on/off signal.

How It Works: PWM Creates “Fake” Analog Voltage

Imagine you’re pushing a child on a swing. You can’t push continuously (analog), but you can push in pulses (digital). The faster and longer you push each time, the higher the swing goes.

PWM works the same way:

  1. Microcontroller limitation: GPIO pins output only 0V (OFF) or 3.3V/5V (ON) - nothing in between
  2. The PWM trick: Switch ON and OFF thousands of times per second
  3. Motor/LED response: Physical inertia smooths the pulses - the device “sees” the average voltage

Example: 50% duty cycle = ON for 0.5 ms, OFF for 0.5 ms, repeat at 1kHz = motor sees ~2.5V average from a 5V supply

By varying ON time, PWM sets a chosen average voltage between zero and the supply; the output remains pulses unless the load or a filter smooths it.

8.5 PWM Fundamentals

This section: PWM Fundamentals — Why use PWM?

PWM (Pulse Width Modulation) is a digital technique that simulates analog control by rapidly switching power ON and OFF:

  • Duty cycle = Percentage of time the signal is HIGH (ON)
  • Frequency = How many times per second the signal repeats
  • Average power = Supply voltage x Duty cycle percentage

Why use PWM? Digital microcontrollers can’t produce true analog voltages (like 2.5V from a 5V supply). Instead, they rapidly switch between 0V and 5V. A motor or LED responds to the average voltage over time.

At 5kHz PWM with 50% duty cycle, each period is T=1/5000=200T = 1/5000 = 200 μs. The signal is HIGH for ton=0.5×200=100t_{on} = 0.5 \times 200 = 100 μs and LOW for 100 μs. A motor with mechanical time constant τm≈50\tau_m \approx 50 ms cannot respond to individual 200 μs pulses (τm/T=250\tau_m / T = 250 cycles per time constant), so it sees only the average voltage: Vavg=0.5×5=2.5V_{avg} = 0.5 \times 5 = 2.5 V. This is why PWM “fakes” analog — the actuator’s inertia performs the averaging.

The mathematical gist. PWM gives T=1/fT=1/f, ton=DTt_{on}=DT, and ideal Vavg=DVsV_{avg}=DV_s. At this chapter’s 20 kHz, 35% greenhouse-fan setting, the 50.0 microsecond period and 17.5 microsecond on-time give 4.20 V average; with 1.00 mH and 4.00 V back-EMF, the short-pulse current-rise estimate is 0.140 A rather than the 1.40 A estimated at 2 kHz.

Math Bridge · guided foundationsWhy does full-voltage switching become smooth motion?Let Max separate the average drive from winding-current and torque ripple.

8.6 Try It: PWM Motor Speed Control

This section: Try It: PWM Motor Speed Control — Use the simulator as an evidence sequence.

Use the simulator as an evidence sequence. Begin with zero load and a moderate switching frequency, raise duty cycle while watching average voltage and speed, then add inertia and load to expose current demand. Reverse the H-bridge only after the shaft response is understood, and finally sweep frequency to distinguish audible whine from excessive switching loss. The useful result is a bounded operating region, not one attractive speed reading.

PWM motor narrated tour

Play silently with captions on provisional storyboard timing; narration audio is pending. Production pacing is not protocol time. Choose Reduced motion for a complete still at each beat.

Play the tour to open the workbench. Pause, replay a beat, or read the full transcript below. Beats marked CANNOT SHOW provide captions without changing asset controls; the teaching model cannot demonstrate those claims.

Full transcript — PWM motor (8 beats)

B1 — Greenhouse cooling fan
You are setting up a greenhouse cooling fan that changes speed with temperature. It should run gently in normal conditions and move enough air on a hot afternoon. Your job is to connect the electrical command to the motion the fan actually delivers.

Model caption: Your greenhouse fan must run gently at normal temperature and move enough air during heat. Connect the command to measured motion.

B2 — Duty cycle and pulses
Pulse width modulation, or PWM, controls average drive by switching power on and off in short pulses. Duty cycle means the share of each cycle spent on. The motor receives pulses, while its electrical and mechanical response smooths their effect into motion.

Model caption: Pulse width modulation switches power on and off. Duty cycle is the on-time share. The motor's electrical and mechanical response smooths the effect.

B3 — Frequency and period
Frequency tells you how many complete cycles happen each second. A period is the time for a complete cycle. For the chapter's worked example, use five thousand cycles per second. Divide one second by five thousand to get a period of two hundred microseconds.

Model caption: 5,000 cycles per second: 1 second divided by 5,000 = 200 microseconds per complete period.

B4 — Equal on and off intervals
Set the duty cycle to fifty percent, meaning half the period is on. Half of two hundred microseconds gives one hundred microseconds on. Subtract that from two hundred microseconds, leaving one hundred microseconds off. Those two intervals together make the complete switching period.

Model caption: Half of 200 = 100 microseconds on. 200 minus 100 = 100 microseconds off. Together: 200 microseconds.

B5 — Ideal average drive
Now use a five volt supply for the example. The ideal pulse voltage is five volts during the on interval and zero during the off interval. Multiply five volts by one half to get two and a half volts of ideal average drive.

Model caption: 5 V on, 0 V off, half the time each. 5 × 0.5 = 2.5 V ideal average drive.

B6 — Mechanical response limits
The example motor has a mechanical response time of about fifty milliseconds. Its motion cannot follow each two hundred microsecond pulse individually. The winding current rises and falls between pulses, while inertia smooths the motion. Inertia describes the motor's tendency to keep moving through those short pulses.

Model caption: Chapter example: about 50 milliseconds mechanical response versus 200 microseconds per pulse. Current rises and falls; inertia smooths motion. The asset does not simulate that response time.

B7 — Load and estimated speed
The misconception is that fifty percent duty guarantees half speed. The calculation gave half the supply voltage as an ideal average, rather than a measured speed. Actual current and speed also depend on the driver, the motor winding, and the mechanical load.

Model caption: 50% duty still gives 2.5 V ideal average at a 5 V supply. Changing load changes the estimated speed: half duty does not guarantee half speed.

B8 — Command and motion
For your fan, the measured motion tells you what the electrical command delivered. Duty sets the share of time power is on; the motor and its load determine the motion.

Model caption: Duty sets the share of time power is on; the motor and its load determine the motion.

This section:

This section:

This section:

Motor Max, Actuation and safe-control domain expertCheckpoint: Average Command

You now know:

  • Duty cycle is the percent of each period spent HIGH; at 50% duty and a 5 V supply, the average actuator voltage is 2.5 V.
  • Frequency sets how often the periods repeat; at 5kHz, each period is 200 microseconds, not a new voltage level.
  • The 75% duty quiz uses the same rule on a 12V motor: 12V x 0.75 = 9V.

This section: — With the command meaning settled, the next step is turning a percentage into the actual timer value the ESP32 writes.

With the command meaning settled, the next step is turning a percentage into the actual timer value the ESP32 writes.

8.7 Interactive PWM Calculator

This section: Interactive PWM Calculator

8.7.1 Calculated Values

8.7.2 ESP32 Code

8.8 PWM Applications by Frequency

This section: PWM Applications by Frequency

Different actuators require different PWM frequencies:

ApplicationTypical FrequencyDuty Cycle RangeIoT Example
LED dimming500-1000 Hz0-100%Smart bulb brightness
DC motor speed1-20 kHz0-100%Ceiling fan control
Servo positionTypically about 50 Hz; check the model5-10% (commonly 1-2 ms pulse)Robotic arm joints
Buzzer/speaker20Hz-20kHz50% (square wave)Doorbell tones
Heating element0.5-2 Hz0-100%3D printer bed
On/off solenoid valveSpecified PWM hold driver onlyHold current after pull-inFlow switching; proportional flow needs a proportional valve and driver

8.9 Servo PWM Timing

This section: Servo PWM Timing

Servo motors are a special case - they use pulse width for position:

Standard Servo:
- 1000 microseconds (1ms)   = 0 degrees (5% duty cycle)
- 1500 microseconds (1.5ms) = 90 degrees (7.5% duty cycle, center)
- 2000 microseconds (2ms)   = 180 degrees (10% duty cycle)
- Period: 20ms (50 Hz)
// Convert angle to pulse width
int angleToPulseWidth(int angle) {
  return map(angle, 0, 180, 1000, 2000);  // 1000-2000 microseconds
}

// Using ESP32Servo library (handles timing automatically)
#include <ESP32Servo.h>
Servo myServo;
myServo.attach(pin, 1000, 2000);  // min/max pulse width
myServo.write(90);                 // Move to 90 degrees

8.10 ESP32 PWM Configuration

This section: ESP32 PWM Configuration

// Arduino-ESP32 3.x assigns a channel when each pin is attached.
// Motor control - high frequency for silent operation
const int motorFreq = 20000;  // 20 kHz (above human hearing)
const int motorResolution = 8;  // 0-255

// LED control - lower frequency acceptable
const int ledFreq = 5000;  // 5 kHz
const int ledResolution = 10;  // 0-1023 (higher resolution for smooth fades)

void setup() {
  // ledcAttach(pin, frequency, resolution) selects a channel automatically.
  ledcAttach(MOTOR_PIN, motorFreq, motorResolution);
  ledcAttach(LED_PIN, ledFreq, ledResolution);
  // Use the ESP32Servo library for a hobby servo.
}

8.11 PWM Speed to Value Conversion

This section: PWM Speed to Value Conversion — Translate the requested percentage in two stages: first compute the maximum register value from resolution, then map the bounded 0-100% request into that integer range.

Translate the requested percentage in two stages: first compute the maximum register value from resolution, then map the bounded 0-100% request into that integer range. Compare the 8-, 10-, and 12-bit examples in order; all represent the same 75% command, but finer resolution supplies more selectable codes. The conversion changes command granularity, not supply voltage, motor torque margin, or proof of achieved speed.

// Convert percentage speed to PWM value
int speedToPWM(int speedPercent, int resolution) {
  int maxValue = (1 << resolution) - 1;  // 2^resolution - 1
  return map(speedPercent, 0, 100, 0, maxValue);
}

// Examples:
// 75% speed at 8-bit resolution:
int pwm8 = speedToPWM(75, 8);   // = 191 (out of 255)

// 75% speed at 10-bit resolution:
int pwm10 = speedToPWM(75, 10); // = 767 (out of 1023)

// 75% speed at 12-bit resolution:
int pwm12 = speedToPWM(75, 12); // = 3071 (out of 4095)

This section:

Motor Max, Actuation and safe-control domain expertCheckpoint: Timer Values

You now know:

  • On Arduino-ESP32 3.x, ledcAttach(pin, frequency, resolution) selects a channel automatically before ledcWrite(pin, duty) updates the output.
  • At 75% command, the chapter’s examples map to 191 on 8-bit, 767 on 10-bit, and 3071 on 12-bit PWM.
  • Servo control is the exception to the “average voltage” mental model: a 50 Hz frame carries 1 ms, 1.5 ms, or 2 ms position pulses.

This section: — Now use those timer settings only after the load tells you what switching frequency it can tolerate.

Now use those timer settings only after the load tells you what switching frequency it can tolerate.

8.12 Why Duty Cycle Matters for IoT

This section: Why Duty Cycle Matters for IoT — Key insight: The actuator “sees” the average voltage, smoothed by its physical response time.

  1. Energy Efficiency: LED at 50% duty cycle uses approximately 50% power, extending battery life
  2. Precise Control: Achieve 256 speed levels (8-bit) or 1024 levels (10-bit) from a simple digital pin
  3. No Analog Hardware: Digital MCUs can control analog-like behavior without DAC chips
  4. Thermal Management: Lower duty cycles reduce heat in motors and drivers

Key insight: The actuator “sees” the average voltage, smoothed by its physical response time. A 1 kHz PWM signal switching between 0 V and 5 V at 50% duty has 2.5 V average, while the motor receives voltage pulses and responds according to its electrical and mechanical time constants.

8.13 Worked Example: Smart Greenhouse Ventilation Fan

This section: Worked Example: Smart Greenhouse Ventilation Fan — A greenhouse uses a 12V DC fan (rated 0.5A at full speed) controlled by an ESP32 via a MOSFET driver.

A greenhouse uses a 12V DC fan (rated 0.5A at full speed) controlled by an ESP32 via a MOSFET driver. The system adjusts fan speed based on temperature.

Step 1: Power at each operating point

TemperatureFan SpeedDuty CycleAverage CurrentPower Consumed
Below 22COff0%0 A0 W
22-25CLow30%0.15 A1.8 W
25-30CMedium60%0.30 A3.6 W
30-35CHigh85%0.425 A5.1 W
Above 35CFull100%0.50 A6.0 W

Power = Voltage x Average Current = 12V x (Duty Cycle x 0.5A)

Step 2: Daily energy consumption

Assume a typical summer day: 6 hours off (night), 8 hours at 30%, 6 hours at 60%, 4 hours at 85%.

  • Energy = (6 x 0) + (8 x 1.8) + (6 x 3.6) + (4 x 5.1) = 0 + 14.4 + 21.6 + 20.4 = 56.4 Wh/day

Compare to running the fan at full speed 24 hours: 6.0W x 24h = 144 Wh/day. PWM-based variable speed saves 61% of the daily energy.

Step 3: Why 20 kHz for this fan?

At lower PWM frequencies, the fan motor produces audible hum. A DC motor’s coils vibrate at the PWM frequency, and humans hear 20 Hz to 20 kHz. Choosing 20 kHz pushes the hum above hearing range, making the fan appear to run silently at any speed. The trade-off: higher PWM frequencies increase switching losses in the MOSFET driver (typically adding 0.1-0.3W at 20 kHz versus 1 kHz), but the acoustic benefit outweighs the small efficiency loss in an occupied greenhouse.

8.14 Continue to the Next Part

This section: Continue to the Next Part — Carry this evidence into PWM Control: Frequency and Driver Decisions, which begins with Choosing PWM Frequency: Decision Factors.

Carry this evidence into PWM Control: Frequency and Driver Decisions, which begins with Choosing PWM Frequency: Decision Factors.

Find help

3 reviewed answers.

Where should I start in a module?

Open the module page from the sidebar to see its chapters in order. Use the module map to return to a topic you need.

Modules and paths

Reviewed

What can I try when a project does not work?

Check the symptom, then work through the diagnostic steps. Keep the error message and the smallest example that reproduces it.

When you are stuck

Reviewed

How do interactive examples work?

Use the interactive guide to check how examples and simulations work before changing your project.

Interactive examples guide

Reviewed