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)
#create a function for mapping the 0 to 180 degree 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)
#create another function for turning the servo according to the 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 motor from 0 to 180 degree by 10 degree increment
for i in range (0,180,10):
print("0 to 180,step",i)
servo(pwm, i)
sleep(1)
#To rotate the servo motor from 180 t0 0 by 10 degree decrement
for i in range(180,0,-10):
print("180 to 0,step",i)
servo(pwm,i)
sleep(1)