006 - ESP32 MicroPython: How to control servo motor with MicroPython

Circuit Diagram

Links to SG90 datasheet:
http://www.ee.ic.ac.uk/pcheung/teaching/DE1_EE/stores/sg90_datasheet.pdf

Links to Arduino map() function:
https://www.arduino.cc/reference/en/language/functions/math/map/

Some formulas use:

freq = 1 / Period
freq = 1 / 20ms
freq = 50Hz

1ms / 20ms = 0.05 = 5% duty cycle
2ms / 20ms = 0.10 = 10% duty cycle

To get the equivalent pwm duty values:
0.05 * 1024 = 51.2
0.10 * 1024 = 102.4
these pwm duty values does not work for me, it gives very inaccurate result angle.

What works for me are a duty values of 20 to 120 or equivalent to 2% to 12% duty cycle.

Video Demonstration

Call To Action

If you found this tutorial as helpful, please consider supporting my Youtube channel by Suscribing to TechToTinker Youtube channel. Click this to Subscribe.

Source Code

 1# Load the machine module for GPIO and PWM
 2# Control servo motor with MicroPython
 3# Author: George Bantique, TechToTinker
 4# Date: September 15, 2020
 5
 6import machine
 7# Load the time module for the delays
 8import time
 9
10# Create a regular p23 GPIO object
11p23 = machine.Pin(23, machine.Pin.OUT)
12
13# Create another object named pwm by
14# attaching the pwm driver to the pin
15pwm = machine.PWM(p23)
16
17# Set the pulse every 20ms
18pwm.freq(50)
19
20# Set initial duty to 0
21# to turn off the pulse
22pwm.duty(0)
23
24# Creates a function for mapping the 0 to 180 degrees
25# to 20 to 120 pwm duty values
26def map(x, in_min, in_max, out_min, out_max):
27    return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
28
29# Creates another function for turning 
30# the servo according to input angle
31def servo(pin, angle):
32    pin.duty(map(angle, 0, 180, 20, 120))
33
34
35# To rotate the servo motor to 0 degrees
36servo(pwm, 0)
37
38# To rotate the servo motor to 90 degrees
39servo(pwm, 90)
40
41# To rotate the servo motor to 180 degrees
42servo(pwm, 180)
43
44# To rotate the servo from 0 to 180 degrees
45# by 10 degrees increment
46for i in range(0, 181, 10):
47    servo(pwm, i)
48    time.sleep(0.5)
49    
50# To rotate the servo from 180 to 0 degrees
51# by 10 degrees decrement
52for i in range(180, -1, -10):
53    servo(pwm, i)
54    time.sleep(0.5)


Posts in this series



No comments yet!

GitHub-flavored Markdown & a sane subset of HTML is supported.