from machine import Pin, ADC, PWM
import time
# 教學目標
# 學習如何使用MicroPython控制舵機。
# 學習如何使用滑桿VR來調整舵機的角度。
# 了解PWM信號的基本原理
# 1. 介紹digital v.s analog
# 2. 建立slider in emulator
# 3. write test code to test ADC, print in the console.
# 4. 介紹 PWM and servo
# 5. write test code to test servo
# 6. integrate slider and servo.
slider = ADC(Pin(13, Pin.OUT))
pwm = PWM(Pin(15))
pwm.freq(50) # set the PWM frequency to 50Hz, which is standard for servos
pwm.duty(77)
def move_servo(angle):
# map the angle value (0-180) to a duty cycle value (50-130)
duty = int(angle / 180 * 80 + 50)
pwm.duty(duty) # set the duty cycle to move the servo to the desired angle
time.sleep(0.1)
while True:
value = slider.read()
angle = value*120/4096
print(value, angle)
move_servo(angle)