%serialconnect
Found serial ports: /dev/cu.usbmodem14101, /dev/cu.Bluetooth-Incoming-Port Connecting to --port=/dev/cu.usbmodem14101 --baud=115200 Ready.
import machine
import time
# pulse width ranges from 500 to 2500 microseconds
class Servo():
def __init__(self, pwm, freq=50, pulse_width_min=500, pulse_width_max=2500):
self.pwm = pwm
self.pwm.freq(freq)
self.pulse_width_min = pulse_width_min
self.pulse_width_max = pulse_width_max
self.pulse_width_us = 1500
def set_position(self, pos):
pw = self.pulse_width_min + int((self.pulse_width_max - self.pulse_width_min)*pos/100)
self.pulse_width_us = max(self.pulse_width_min, min(self.pulse_width_max, pw))
self.pwm.duty_ns(1000*self.pulse_width_us)
def stop(self):
self.pwm.duty_u16(0)
# create servo instance
servo_pin = machine.Pin(7, mode=machine.Pin.OUT)
servo_pwm = machine.PWM(servo_pin)
srv = Servo(servo_pwm)
# set to initial position
srv.set_position(50)
time.sleep(1)
for k in range(0, 101):
srv.set_position(k)
time.sleep_ms(50)
# stop servo
srv.stop()
.