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 #354 background imageLoading...
Page #354 background image
SunFounder ESP32 Starter Kit
(continued from previous page)
motor2A.value(1)
# Define a function to stop the motor
def stop():
motor1A.value(0)
motor2A.value(0)
# Enter an infinite loop
try:
while True:
clockwise() # Rotate the motor clockwise
time.sleep(1) # Pause for 1 second
anticlockwise() # Rotate the motor anticlockwise
time.sleep(1)
stop() # Stop the motor
time.sleep(2)
except KeyboardInterrupt:
stop() # Stop the motor when KeyboardInterrupt is caught
During script execution, you will see the motor alternately rotating clockwise and counterclockwise every second.
Learn More
In addition to simply making the motor rotate clockwise and counterclockwise, you can also control the speed of the
motor’s rotation by using pulse-width modulation (PWM) on the control pin, as shown below.
Note:
Open the 4.1_motor_turn_pwm.py file located in the esp32-starter-kit-main\micropython\codes
path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.
Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.
from machine import Pin, PWM
import time
# Create PWM objects representing the motor control pins and set their frequency to 1000
˓Hz
motor1A = PWM(Pin(13, Pin.OUT))
motor2A = PWM(Pin(14, Pin.OUT))
motor1A.freq(500)
motor2A.freq(500)
# Enter an infinite loop
while True:
# Rotate the motor forward by gradually increasing the power on the motor1A pin
for power in range(0, 1023, 20):
motor1A.duty(power)
motor2A.duty(0)
time.sleep(0.1)
# Decreasing the power on the motor1A pin
(continues on next page)
348 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