from machine import Pin, PWM
from time import sleep
servo_pin = Pin(12, Pin.OUT)
pwm = PWM(servo_pin)
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(pwm_pin, angle):
pwm_pin.duty(map(angle, 0, 180, 20, 120))
servo(pwm, 0)
sleep(1)
servo(pwm, 90)
sleep(1)
servo(pwm, 170)
sleep(1)
while True:
# To rotate the servo from 0 to 180 degrees by 10 degrees increment
for i in range(0, 180, 10):
print("0 to 180, step ", i)
servo(pwm, i)
sleep(1)
# To rotate the servo from 180 to 0 degrees by 10 degrees decrement
for i in range(180, 0, -10):
print("180 to 0, step ", i)
servo(pwm, i)
sleep(1)