|
27 | 27 | """
|
28 | 28 |
|
29 | 29 | import digitalio
|
| 30 | +import pulseio |
30 | 31 | import math
|
31 | 32 | import time
|
32 | 33 |
|
@@ -101,6 +102,57 @@ def shift_out(dataPin, clock, value, msb_first=True):
|
101 | 102 | tmpval = bool((value & (1 << i)))
|
102 | 103 | dataPin.value = tmpval
|
103 | 104 |
|
| 105 | +class Servo: |
| 106 | + """ |
| 107 | + Easy control for hobby (3-wire) servos |
| 108 | +
|
| 109 | + :param ~microcontroller.Pin pin: PWM pin where the servo is located. |
| 110 | + :param int min_pulse: Pulse width (microseconds) corresponding to 0 degrees. |
| 111 | + :param int max_pulse: Pulse width (microseconds) corresponding to 180 degrees. |
| 112 | +
|
| 113 | + Example for Metro M0 Express: |
| 114 | +
|
| 115 | + .. code-block:: python |
| 116 | +
|
| 117 | + import simpleio |
| 118 | + import time |
| 119 | + from board import * |
| 120 | +
|
| 121 | + pwm = simpleio.Servo(D9) |
| 122 | +
|
| 123 | + while True: |
| 124 | + pwm.angle = 0 |
| 125 | + print("Angle: ", pwm.angle) |
| 126 | + time.sleep(2) |
| 127 | + pwm.angle = pwm.microseconds_to_angle(2500) |
| 128 | + print("Angle: ", pwm.angle) |
| 129 | + time.sleep(2) |
| 130 | + """ |
| 131 | + def __init__(self, pin, min_pulse = 0.5, max_pulse = 2.5): |
| 132 | + self.pwm = pulseio.PWMOut(pin, frequency = 50) |
| 133 | + self.min_pulse = min_pulse |
| 134 | + self.max_pulse = max_pulse |
| 135 | + |
| 136 | + @property |
| 137 | + def angle(self): |
| 138 | + return self._angle |
| 139 | + |
| 140 | + @angle.setter |
| 141 | + def angle(self, degrees): |
| 142 | + """Writes a value in degrees to the servo""" |
| 143 | + self._angle = max(min(180, degrees), 0) |
| 144 | + pulseWidth = 0.5 + (self._angle / 180) * (self.max_pulse - self.min_pulse) |
| 145 | + dutyPercent = pulseWidth / 20.0 |
| 146 | + self.pwm.duty_cycle = int(dutyPercent * 65535) |
| 147 | + |
| 148 | + def microseconds_to_angle(self, us): |
| 149 | + """Converts microseconds to a degree value""" |
| 150 | + return map_range(us, 500, 2500, 0, 180) |
| 151 | + |
| 152 | + def deinit(self): |
| 153 | + """Detaches servo object from pin, frees pin""" |
| 154 | + self.pwm.deinit() |
| 155 | + |
104 | 156 | class DigitalOut:
|
105 | 157 | """
|
106 | 158 | Simple digital output that is valid until soft reset.
|
|
0 commit comments