diff --git a/simpleio.py b/simpleio.py index 1c4f0f7..e3451f8 100644 --- a/simpleio.py +++ b/simpleio.py @@ -27,6 +27,7 @@ """ import digitalio +import pulseio import math import time @@ -101,6 +102,66 @@ def shift_out(dataPin, clock, value, msb_first=True): tmpval = bool((value & (1 << i))) dataPin.value = tmpval +class Servo: + """ + Easy control for hobby (3-wire) servos + + :param ~pulseio.PWMOut pin: PWM pin where the servo is located. + :param int min_pulse: Minimum amount of microseconds allowed. Varies depending on type of servo. + :param int max_pulse: Maximum amount of microseconds allowed. Varies depending on type of servo. + + Example for Metro M0 Express: + + .. code-block:: python + + import simpleio + import time + from board import * + + # attach a servo to pin Digital 10 + pwm = simpleio.Servo(D10) + + while True: + # write an angle of 90deg to the servo object + pwm.set_angle(90) + time.sleep(1) + # write an angle of 150deg to the servo object + pwm.set_angle(150) + # print the location of the servo + print(pwm.read()) + time.sleep(1) + # write to the servo in microseconds + pwm.set_Microseconds(5500) + time.sleep(1) + """ + def __init__(self, pin, min_pulse = 0.5, max_pulse = 2.5): + self.pwm = pulseio.PWMOut(pin, frequency = 50) + self.min_pulse = min_pulse + self.max_pulse = max_pulse + # prevent weird values due to read before write calls + self.angle = 90 + + def set_angle(self, angle): + """Writes a value in degrees to the servo""" + self.angle = max(min(180, angle), 0) + pulseWidth = 0.5 + (self.angle / 180) * (self.max_pulse - self.min_pulse) + dutyPercent = pulseWidth / 20.0 + self.pwm.duty_cycle = int(dutyPercent * 65535) + + def set_Microseconds(self, uS): + """Writes a value in microseconds to the servo""" + ms = (uS/1000) + ms = max(min(self.max_pulse, ms), self.min_pulse) + dutyPercent = ms / 20.0 + self.pwm.duty_cycle = int(dutyPercent * 65535) + + def detach(self): + """Detaches servo object from pin, frees pin""" + self.pwm.detach() + + def read(self): + return self.angle + class DigitalOut: """ Simple digital output that is valid until soft reset.