import machine
import time
p23 = machine.Pin(23, machine.Pin.OUT)
pwm = machine.PWM(p23)
pwm.freq(50)
pwm.duty(0)
# Creates a function for mapping the 0 to 180 degrees
# to 20 to 120 pwm duty values
def map(x, in_min, in_max, out_min, out_max):
return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
# Creates another function for turning
# the servo according to input angle
def servo(pin, angle):
pin.duty(map(angle, 0, 180, 20, 120))
# To rotate the servo motor to 0 degrees
servo(pwm, 0)
time.sleep(1)
# To rotate the servo motor to 90 degrees
servo(pwm, 90)
time.sleep(1)
# To rotate the servo motor to 180 degrees
servo(pwm, 180)
time.sleep(1)
# To rotate the servo from 0 to 180 degrees
# by 10 degrees increment
while True:
for i in range(0, 181, 10):
servo(pwm, i)
time.sleep(0.5)
# To rotate the servo from 180 to 0 degrees
# by 10 degrees decrement
for i in range(180, -1, -10):
servo(pwm, i)
time.sleep(0.5)