Labs / Arduino + ESP32 with Wokwi

13 PWM Pulse Width Modulation and analogWrite ()

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents

1. Introduction

Having covered analog input, let's now talk about what lies behind the analog output function analogWrite ().

The analogWrite () function of ESP32 is not a true analog signal output in the strict sense; instead, it simulates the control effect similar to an analog signal by rapidly switching the high and low levels of a digital signal.

This method is called PWM (Pulse Width Modulation).

2. Core Concept of PWM

When a light flashes fast enough, the naked eye cannot distinguish its on-off state, and instead perceives its overall brightness.

PWM works by leveraging this method of rapidly switching between high and low levels to adjust the proportion of the duration of the high level, namely the duty cycle, so as to control the "average output effect" of the device.

As long as the switching speed is fast enough, devices such as LEDs, fans and motors actually perceive the "average voltage" rather than the flickering high and low levels.

The essence of PWM:

  • By rapidly switching between high and low levels, the "average output effect" of the device is controlled.
  • What the device perceives is the "average voltage" rather than the actual level transition.

3. Core Control Parameters

A PWM signal has two core control parameters: period and duty cycle.

13 PWM Pulse Width Modulation and analogWrite ()

3.1 Cycle

Period is the time required for a signal to complete one full waveform cycle; in other words, it is the reciprocal of the signal frequency.

1

3.2 Duty Cycle

Duty cycle represents the percentage of the period that the signal stays at high level, and is defined as follows:

100

The shorter the period, the faster the signal switches, and the closer the output effect is to a continuous analog signal.

PWM can control the average output voltage by adjusting the duty cycle.

3.3 Example

5V 50 75 25

Assume that Vhigh = 5V:

50% duty cycle (high and low levels each account for half): Vavg = 5V x 50% = 2.5V

75% duty cycle (75% high level, 25% low level): Vavg = 5V × 75% = 3.75V

25% duty cycle (25% high level, 75% low level): Vavg = 5V × 25% = 1.25V

The advantages of this technology lie in its ability to effectively control power without the need for complex analog circuits.

Impact on the output effect:

4. Common hardware structure of PWM signals

This is the general hardware structure diagram of the PWM peripheral, from which we can see exactly how the PWM signal is generated and what processes it goes through.

13 PWM Pulse Width Modulation and analogWrite ()

First, the clock source provides a pulse signal to drive the timer to start counting.

The timer starts counting from 0 and increments step by step in accordance with the clock signal.

When the timer count value is compared with the value in the duty cycle register, the first comparator determines the duration of the high level.

When the count value of the timer equals the period register, the second comparator determines whether the PWM signal has completed a full cycle.

Finally, the R-S flip-flop controls the level state of the PWM pin according to the result of the comparator, thereby realizing the switching between high and low levels and generating the PWM signal.

Clock Source: Provides a reference pulse signal.

Timer: Counts based on the clock signal and increments the count value periodically.

Duty Comparator: determines the duration of the high level.

Period Comparator: Determines the end of a cycle and triggers a new cycle.

R-S Flip-Flop (R-S Trigger): Controls the level of the GPIO pin based on the comparator result.

5. analogWrite () function review and supplement

Let's review what we used for our previous analog output simulation: analogWrite () function

Syntax: analogWrite (pin, value);

analogWrite () has default parameters for frequency and resolution:

Once the frequency and resolution are fixed, analogWrite () output will have a clear "beat" and "brightness levels", which is equivalent to setting boundaries for the performance range of PWM.

7. LEDC hardware PWM module

" analogWrite () is simple, but it has its limitations. What if we want more precise control? "

In this case, the built-in LEDC hardware PWM module of the ESP32 is required.

7.1 Basic Structure of LEDC

ESP32 provides 16 PWM channels (divided into high-speed channels and low-speed channels), and each channel can be configured with the following settings:

Bind a channel to a specific GPIO pin to output a PWM signal.

ESP32 h_timer0 h_timer3 h_ch0 h_ch7 l_timer0 l_timer3 l_ch0 l_ch7

7.2 Software Implementation

We use the following: ledcSetup (), ledcAttachPin (), and ledcWrite () functions to achieve PWM signal output.

7.2.1 ledcSetup () function

function prototype

uint32_t ledcSetup(uint8_t channel, double freq, uint8_t resolution_bits);

Functions

Configure the operating parameters (frequency + resolution) of a PWM channel.

Input Parameters

Return Value

Usage Example

// Configure PWM channel 0, target frequency 5000Hz, 8-bit resolution
uint32_t realFreq = ledcSetup(0, 5000, 8);
Serial.println(realFreq); // Print the actual frequency
7.2.2 ledcAttachPin () function

function prototype

void ledcAttachPin(uint8_t pin, uint8_t channel);

Functions

Bind a specific GPIO pin to the specified PWM channel to output a PWM signal on that pin.

Input Parameters

Return Value

Usage Example

// Bind GPIO 5 to channel 0
ledcAttachPin(5, 0);
7.2.3 ledcWrite () function

function prototype

void ledcWrite(uint8_t channel, uint32_t duty);

Functions

Set the duty cycle of the PWM channel.

Input Parameters

Return Value

Usage Example

// Set the duty cycle of channel 0 to 128 (about 50%)
ledcWrite(0, 128);

7.3 Summary of the LEDC Three-Step Method

  1. ledcSetup (): sets the frequency and resolution.
  2. ledcAttachPin (): Binds a channel to a specified pin.
  3. ledcWrite (): Sets the duty cycle and outputs a PWM signal.

Mnemonic:"Set first → Bind next → Output finally"

8. Summary of This Chapter

In this chapter, we unveil the secret behind analogWrite ()— PWM, Pulse Width Modulation.

To achieve more flexible and precise control, the ESP32 provides LEDC series functions:

PWM signals are widely applicable in scenarios such as LED dimming, motor speed regulation, and steering gear control. We can regard analogWrite () as an "entry-level interface", while the ledc series functions serve as a "professional toolkit", which can control the frequency, resolution and multiple channels, making them more suitable for practical engineering applications.