EasyManuals Logo

SunFounder ESP32 User Manual

Default Icon
771 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Page #320 background imageLoading...
Page #320 background image
SunFounder ESP32 Starter Kit
(continued from previous page)
for duty_cycle in range(1023, -1, -1):
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 Pin, PWM
import time
# Create a PWM object
led = PWM(Pin(26), freq=1000)
while True:
# Gradually increase brightness
for duty_cycle in range(0, 1024, 2):
led.duty(duty_cycle)
time.sleep(0.01)
# Gradually decrease brightness
for duty_cycle in range(1023, -1, -2):
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 Chapter 3. For MicroPython User

Table of Contents

Questions and Answers:

Question and Answer IconNeed help?

Do you have a question about the SunFounder ESP32 and is the answer not in the manual?

SunFounder ESP32 Specifications

General IconGeneral
BrandSunFounder
ModelESP32
CategoryController
LanguageEnglish