Quick answer: in MicroPython on the ESP32, create PWM on any output pin with PWM(Pin(23), freq=1000, duty_u16=0) and set brightness with duty_u16(0–65535) (0 = off, 65535 = fully on). For a servo, use 50 Hz and pulses of about 0.5–2.5 ms: servo = PWM(Pin(18), freq=50), then servo.duty_ns(1_500_000) centres it. Power servos from a separate 5 V supply with a common ground, never from the ESP32's 3.3 V pin. The code for a smooth LED fade, a servo angle function, a button-controlled dimmer and a fix table is below.
| Task | Frequency | Duty setting |
|---|---|---|
| LED dimming | 1–5 kHz (no visible flicker) | duty_u16(0…65535) |
| Small DC motor (via driver) | 1–20 kHz (20 kHz is silent) | duty_u16 |
| Hobby servo (SG90, MG996R) | 50 Hz | Pulse width 0.5–2.5 ms: duty_ns(500_000…2_500_000) |
| Passive buzzer tone | Note frequency (e.g. 440 Hz) | duty_u16(32768) (50 %) |
| Method | Range | Notes |
|---|---|---|
duty_u16(x) | 0–65535 | Recommended; portable across ESP32, Pico, ESP8266 |
duty_ns(x) | Pulse width in nanoseconds | Perfect for servos |
duty(x) | 0–1023 | Older ESP32/ESP8266 API; avoid in new code |
How PWM works
PWM (pulse-width modulation) switches a pin fully on and off very quickly. The frequency is how many on-off cycles happen per second; the duty cycle is the fraction of each cycle the pin is on. An LED switched on 25 % of the time at 1 kHz looks 25 % bright because your eye averages it. A servo ignores the average and instead reads the length of each pulse to choose its angle.
The ESP32 generates PWM in hardware (the LEDC peripheral), so the CPU is free while it runs, and almost every output-capable GPIO can be used. The classic ESP32 has 16 PWM channels but only a few independent timers, so you can have many PWM pins but only a small number of different frequencies at once (servos at 50 Hz and LEDs at 1 kHz together is fine).
1. Fade an LED smoothly
Wire GPIO23 → 220 Ω resistor → LED anode (long leg), LED cathode → GND.
from machine import Pin, PWM
import time
led = PWM(Pin(23), freq=1000, duty_u16=0)
def gamma(level):
# 0.0–1.0 in, perceptually even brightness out
return int((level ** 2.2) * 65535)
while True:
for i in range(101):
# fade in
led.duty_u16(gamma(i / 100))
time.sleep_ms(10)
for i in range(100, -1, -1):
# fade out
led.duty_u16(gamma(i / 100))
time.sleep_ms(10)Why the gamma curve? Your eyes are much more sensitive to changes at low brightness. A straight 0→65535 ramp looks like it jumps to bright quickly and then barely changes. Raising the level to the power 2.2 spreads the change evenly, which is what professional LED dimmers do.
When you're done, led.deinit() releases the PWM channel and the pin.
2. Control a servo
| Servo wire | Connect to |
|---|---|
| Brown / black (GND) | External 5 V supply GND and ESP32 GND |
| Red (V+) | External 5 V supply + (4.8–6 V) |
| Orange / yellow (signal) | GPIO18 |
from machine import Pin, PWM
import time
servo = PWM(Pin(18), freq=50)
MIN_US, MAX_US = 500, 2500 # adjust to your servo's real end stops
def angle(deg):
deg = max(0, min(180, deg))
us = MIN_US + (MAX_US - MIN_US) * deg / 180
servo.duty_ns(int(us * 1000))
for a in (0, 90, 180, 90):
angle(a)
time.sleep(1)Many servos are specified for 1.0–2.0 ms, but most cheap SG90s turn further with 0.5–2.5 ms. Find your servo's real limits by moving slowly towards each end and stopping before it buzzes or strains, then set MIN_US/MAX_US. A servo straining against its end stop draws its full stall current and heats up.
If your firmware is too old for duty_ns, convert the pulse to duty_u16 instead: servo.duty_u16(int(us / 20000 * 65535)) (a 1.5 ms pulse is about 4915).
3. Servo power: the number one cause of problems
A small SG90 draws around 100–250 mA while moving and can spike to several hundred milliamps when stalled; an MG996R can draw over an amp. The ESP32 board's 3.3 V regulator can't supply that, and even its 5 V/VIN pin (USB) sags, which shows up as twitching servos, Wi-Fi drops or the ESP32 resetting.
- Power servos from a separate 5–6 V supply (a 4×AA pack, a 5 V 2 A adapter, or a buck converter).
- Connect that supply's ground to the ESP32's ground; the signal needs a shared reference.
- Add a 470–1000 µF capacitor across the servo supply near the servos.
- The ESP32's 3.3 V signal is enough for almost all hobby servos.
4. Button-controlled dimmer
Each press of a button on GPIO27 (to GND) steps the LED through brightness levels:
from machine import Pin, PWM
import time
led = PWM(Pin(23), freq=1000, duty_u16=0)
button = Pin(27, Pin.IN, Pin.PULL_UP)
levels = [0, 0.05, 0.2, 0.5, 1.0]
index = 0
last_press = 0
while True:
if button.value() == 0 and time.ticks_diff(time.ticks_ms(), last_press) > 250:
last_press = time.ticks_ms()
index = (index + 1) % len(levels)
led.duty_u16(int((levels[index] ** 2.2) * 65535))
print("Brightness step", index)
time.sleep_ms(10)The 250 ms window debounces the button and stops one long press counting as several. More button techniques: MicroPython GPIO, LED and button.
5. Play tones on a passive buzzer
A passive buzzer (no built-in oscillator) plays whatever frequency you feed it, so PWM turns it into a tiny speaker. Wire it between GPIO25 and GND (through a 100 Ω resistor for small buzzers). An active buzzer only beeps at its own fixed pitch when powered, so it can't play notes.
from machine import Pin, PWM
import time
buzzer = PWM(Pin(25), freq=440, duty_u16=0)
NOTES = {"C4": 262, "D4": 294, "E4": 330, "F4": 349, "G4": 392, "A4": 440, "B4": 494, "C5": 523}
def play(note, ms):
if note == "-":
buzzer.duty_u16(0)
# rest
else:
buzzer.freq(NOTES[note])
buzzer.duty_u16(32768)
# 50 % duty = loudest square wave
time.sleep_ms(ms)
buzzer.duty_u16(0)
time.sleep_ms(30)
# short gap between notes
for n in ["C4", "E4", "G4", "C5", "-", "G4", "C5"]:
play(n, 250)
buzzer.deinit()Volume depends mostly on the buzzer and on hitting its resonant frequency (often 2–4 kHz); 50 % duty gives the strongest tone. Remember that changing this pin's frequency can affect other PWM pins that share the same hardware timer, so test alongside your LEDs or servos.
6. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| LED flickers | Frequency too low | Use 1 kHz or more |
| LED never fully off | Duty not exactly 0, or LED wired to 3.3 V instead of GND | duty_u16(0); check wiring |
| Servo jitters or twitches | Weak or shared power supply, noisy ground | Separate 5 V supply, common ground, big capacitor |
| ESP32 resets when the servo moves | Servo powered from the ESP32 | External supply |
| Servo buzzes at the ends | Pulse outside its real range | Narrow MIN_US/MAX_US |
| Servo doesn't move at all | Wrong frequency (not 50 Hz) or no common ground | freq=50; join grounds |
| Changing one pin's frequency changed another | Pins share a hardware timer | Keep pins that need different frequencies to a minimum, or use the same frequency |
AttributeError: 'PWM' object has no attribute 'duty_u16' | Very old firmware | Update MicroPython, or use duty(0–1023) |
ValueError on GPIO34–39 | Input-only pins | Use an output-capable GPIO |
| Motor whines | PWM frequency in the audible range | Use 20 kHz through a motor driver |
FAQ
Which ESP32 pins support PWM in MicroPython? All output-capable GPIOs. Avoid input-only pins 34–39 and be careful with boot pins 0, 2, 12 and 15.
What's the difference between duty() and duty_u16()? duty() is the old 10-bit (0–1023) API; duty_u16() is 16-bit (0–65535) and works the same on every MicroPython port.
Can I drive a motor directly from a PWM pin? No. Use a driver such as a TB6612FNG or L298N: TB6612FNG vs L298N.
How many servos can one ESP32 drive? Up to the number of PWM channels (16 on the classic ESP32), all at 50 Hz. The power supply is usually the real limit; for many servos, a PCA9685 I2C board is easier.
Next steps
- ESP32 PWM with Arduino (LEDC): the same ideas in C++.
- MicroPython GPIO, LED and button.
- MicroPython vs Arduino on ESP32.
- Project: ESP32 servo ultrasonic radar.
Official reference: MicroPython machine.PWM.
PWM calculations and repeatable testing
PWM controls the average power delivered to a load by switching the output between its low and high states. The duty cycle is the fraction of each period spent high. At 1 kHz, one period lasts 1 ms; a 25% duty cycle is high for 0.25 ms and low for 0.75 ms. For an LED, changing duty cycle changes perceived brightness, although the relationship between duty cycle and human-perceived brightness is not perfectly linear.
For a servo, frequency and pulse width matter more than a generic duty percentage. A common hobby servo expects a pulse about every 20 ms (approximately 50 Hz), with a pulse width often near 1,000–2,000 microseconds. The usable range varies by servo. Start near the centre position, move in small increments, and stop if the servo buzzes, stalls or pushes against a mechanical end stop. Do not assume every servo safely accepts the same endpoints.
When testing PWM, change one parameter at a time:
- Frequency: keep it fixed while checking the duty range. A frequency that is suitable for an LED may not suit a servo.
- Duty or pulse width: begin conservatively and observe the load rather than commanding extreme values immediately.
- Power source: power motors and servos from a supply rated for their peak current. Join the supply ground to ESP32 ground so the control signal has a shared reference.
- Pin choice: use a suitable output GPIO and check board-specific restrictions before selecting a pin.
Why the output can look wrong
An LED that appears to flicker may be driven at a frequency that is too low, or the code may be blocking between updates. A servo that jitters can be reacting to noisy power, long ground leads, an unstable signal, or a pulse range outside its mechanical limits. A buzzer's pitch is mainly controlled by PWM frequency, while duty cycle affects the waveform and perceived loudness.
Use an oscilloscope or logic analyser when available to verify the actual signal period and pulse width. A multimeter may show an average voltage, but it cannot fully describe a fast PWM waveform. Finally, remember that PWM is not a substitute for a motor driver: never connect a motor directly to an ESP32 GPIO. Use a suitable driver stage and a separate motor supply.




