SunFounder ESP32 Starter Kit
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
4. Define a servo_write function that takes a PWM object and an angle as inputs. It calculates the pulse width
and duty cycle based on the given angle, and then sets the PWM output accordingly.
def servo_write(pin, angle):
pulse_width = interval_mapping(angle, 0, 180, 0.5, 2.5) # Calculate the␣
˓→pulse width
duty = int(interval_mapping(pulse_width, 0, 20, 0, 1023)) #␣
˓→Calculate the duty cycle
pin.duty(duty) # Set the duty cycle of the PWM signal
• In this function, interval_mapping() is called to map the angle range 0 ~ 180 to the pulse
width range 0.5 ~ 2.5ms.
• Why is it 0.5~2.5? This is determined by the working mode of the Servo.
• Next, convert the pulse width from period to duty.
• Since duty() cannot have decimals when used (the value cannot be a float type), we used int()
to force the duty to be converted to an int type.
5. Create an infinite loop with two nested loops.
while True:
# Loop through angles from 0 to 180 degrees
for angle in range(180):
servo_write(servo, angle)
time.sleep_ms(20)
# Loop through angles from 180 to 0 degrees in reverse
for angle in range(180, -1, -1):
servo_write(servo, angle)
time.sleep_ms(20)
• The first nested loop iterates through angles from 0 to 180 degrees, and the second nested loop
iterates through angles from 180 to 0 degrees in reverse.
• In each iteration, the servo_write function is called with the current angle, and a delay of 20
milliseconds is added.
5. Sensors
3.19 5.1 Reading Button Value
In this interactive project, we’ll venture into the realm of button controls and LED manipulation.
The concept is straightforward yet effective. We’ll be reading the state of a button. When the button is pressed down,
it registers a high voltage level, or ‘high state’. This action will then trigger an LED to light up.
Required Components
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
3.19. 5.1 Reading Button Value 355