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 #325 background imageLoading...
Page #325 background image
SunFounder ESP32 Starter Kit
(continued from previous page)
# Map input values from one range to another
def interval_mapping(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
# Convert color values (0-255) to duty cycle values (0-1023)
def color_to_duty(rgb_value):
rgb_value = int(interval_mapping(rgb_value,0,255,0,1023))
return rgb_value
def set_color(red_value,green_value,blue_value):
red.duty(color_to_duty(red_value))
green.duty(color_to_duty(green_value))
blue.duty(color_to_duty(blue_value))
while True:
# Set different colors and wait for a while
set_color(255, 0, 0) # Red
time.sleep(1)
set_color(0, 255, 0) # Green
time.sleep(1)
set_color(0, 0, 255) # Blue
time.sleep(1)
set_color(255, 0, 255) # purple
time.sleep(1)
This code is based on the previous example, but it maps color values from 0 to 255 to a duty cycle range of 0 to 1023.
The interval_mapping function is a utility function that maps a value from one range to another. It takes
five arguments: the input value, the minimum and maximum values of the input range, and the minimum and
maximum values of the output range. It returns the input value mapped to the output range.
def color_to_duty(rgb_value):
rgb_value = int(interval_mapping(rgb_value,0,255,0,1023))
return rgb_value
The color_to_duty function takes an integer RGB value (e.g. 255,0,255) and maps it to a duty cycle value
suitable for the PWM pins. The input RGB value is first mapped from the range 0-255 to the range 0-1023 using
the interval_mapping function. The output of interval_mapping is then returned as the duty cycle value.
def color_to_duty(rgb_value):
rgb_value = int(interval_mapping(rgb_value,0,255,0,1023))
return rgb_value
The color_set function takes three integer arguments: the red, green, and blue values for the LED. These
values are passed to color_to_duty to obtain the duty cycle values for the PWM pins. The duty cycle values
are then set for the corresponding pins using the duty method.
def set_color(red_value,green_value,blue_value):
red.duty(color_to_duty(red_value))
green.duty(color_to_duty(green_value))
blue.duty(color_to_duty(blue_value))
3.9. 2.3 Colorful Light 319

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