MicroPython PWM fade on an ESP32
MicroPython on an ESP32 DevKit: machine.PWM at 1 kHz on D4 sweeps the duty up and down with duty_u16(), so the LED breathes in and out. The whole build, an ESP32 DevKit and 2 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $9.15. On Mokxi they're free.
The code
The MicroPython code exactly as the editor opens it. Change a line there and press Run: the board runs it on the official MicroPython firmware, with nothing to compile.
# MicroPython on an ESP32 DevKit: an LED that breathes.
# The LED on D4 is driven by PWM at 1 kHz; the duty goes up and down
# from 0 to 65535 in steps, so the LED fades in and out.
from machine import Pin, PWM
import time
led = PWM(Pin(4), freq=1000)
while True:
for duty in range(0, 65536, 2048):
led.duty_u16(duty)
time.sleep_ms(20)
for duty in range(65535, -1, -2048):
led.duty_u16(duty)
time.sleep_ms(20)
print("breath")
Parts list
3 parts, plus the jumper wires. They retail for about $9.15; on Mokxi they're free.
- 1 × ESP32 DevKit V1
- 1 × Resistor, 220 Ω
- 1 × LED, green
How it is wired
3 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- ESP32 DevKit V1 pin D4; Resistor, 220 Ω pin 1
- Resistor, 220 Ω pin 2; LED, green pin A
- Ground: LED, green pin C
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.