SunFounder ESP32 Starter Kit
for
in
duty_cycle
led.duty(duty_cycle)
time.sleep(0.01)
The LED will gradually become brighter as the code runs.
How it works?
Overall, this code demonstrates how to use PWM signals to control the brightness of an LED.
1. It imports two modules, machine and time. The machine module provides low-level access to the microcon-
troller's hardware, while the time module provides functions for time-related operations.
import
machine
import
time
2. Then initializes a PWM object for controlling the LED connected to pin 26 and sets the frequency of the PWM
signal to 1000 Hz.
led
=
PWM(Pin(26), freq=1000)
3. Fade the LED in and out using a loop: The outer while True loop runs indefinitely. Two nested for loops are
used to gradually increase and decrease the LED's brightness. The duty cycle ranges from 0 to 1023, representing
a 0% to 100% duty cycle.
# Import the necessary libraries
from
machine
import
time
# Create a PWM object
led
=
PWM(Pin(26), freq=1000)
while
True:
# Gradually increase brightness
for
duty_cycle
led.duty(duty_cycle)
time.sleep(0.01)
# Gradually decrease brightness
for
duty_cycle
led.duty(duty_cycle)
time.sleep(0.01)
• range(): Create a sequence of integers from 0 to 1023.
• The duty cycle of the PWM signal is set to each value in the sequence using the duty() method
of the PWM object.
• time.sleep(): Pause the execution of the program for 10 milliseconds between each iteration
of the loop, creating a gradual increase in brightness over time.
314
range(1023, -1, -1):
import
Pin, PWM
in
range(0, 1024, 2):
in
range(1023, -1, -2):
(continued from previous page)
Chapter 3. For MicroPython User
Need help?
Do you have a question about the ESP32 and is the answer not in the manual?