Skip to content

Commit f4d2736

Browse files
brentrutannewt
authored andcommitted
Servo (#15)
Added easy control for hobby servos
1 parent 50dd6c3 commit f4d2736

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

simpleio.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
"""
2828

2929
import digitalio
30+
import pulseio
3031
import math
3132
import time
3233

@@ -101,6 +102,57 @@ def shift_out(dataPin, clock, value, msb_first=True):
101102
tmpval = bool((value & (1 << i)))
102103
dataPin.value = tmpval
103104

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+
104156
class DigitalOut:
105157
"""
106158
Simple digital output that is valid until soft reset.

0 commit comments

Comments
 (0)