This project demonstrates how to control the brightness of an LED connected to the ESP8266 using Pulse Width Modulation (PWM) in MicroPython.
The LED gradually fades in and out, creating a smooth brightness transition.
| Component | Description |
|---|---|
| Board | ESP8266 |
| IDE | Thonny IDE |
| Language | MicroPython |
| USB Driver | Silicon Labs CP210x USB to UART Bridge |
| LED Pin | GPIO2 |
| PWM Frequency | 1 kHz |
| Duty Cycle Range | 0 – 1023 |
- ESP8266 board (NodeMCU or compatible)
- 1 LED + 220Ω resistor
- Micro USB cable
- Thonny IDE
- CP210x USB Driver
- MicroPython firmware flashed on ESP8266
| ESP8266 Pin | Component | Description |
|---|---|---|
| GPIO2 | LED | Output (PWM control) |
| GND | LED (-) | Common Ground |
💡 Tip: If you use GPIO16 for a second LED, note that GPIO16 does not support hardware PWM.
# GPIO2 = LED1
# GPIO16 = LED2
import machine
import utime
led = machine.Pin(2, machine.Pin.OUT)
pwm = machine.PWM(led)
pwm.init(freq=1000, duty=900)
def pwm_duty(duty):
pwm.duty(duty)
while True:
for x in range(1020, 0, -5):
pwm.duty(x)
utime.sleep_ms(10)
utime.sleep_ms(500)
for x in range(0, 1020, 5):
pwm.duty(x)
utime.sleep_ms(10)
utime.sleep_ms(500)