from machine import Pin, PWM
import time

S1 = PWM(Pin(19), freq=50, duty=0) # Servo1的引脚是0
def Servo(servo,angle): # 定义函数
    servo.duty( int( ((angle + 90) / 90 + 0.5) / 20 * 1023 ) )
    # 首先将(-90°,90°)映射到(0°,180°),所以+90
    # 再把(0.5ms, 2.5ms)映射到(0ms, 2ms),所以+0.5
    # 则90°是为1ms脉冲宽度
    # /20为计算占空比,单位为%
    # *1023是将占空比映射到.duty()的参数范围0~1023
    #-90度
while 1:
    Servo(S1,-90) # 指向右侧
    time.sleep(1)
    Servo(S1,-45) # 指向右侧
    time.sleep(1)
    Servo(S1,-0) # 指向右侧
    time.sleep(1)
    Servo(S1,45) # 指向右侧
    time.sleep(1)
    Servo(S1,90) # 指向右侧
    time.sleep(1)
    Servo(S1,-90) # 指向右侧
    time.sleep(1)