-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservo.py
41 lines (37 loc) · 1.48 KB
/
servo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from machine import PWM
import math
# originally by Radomir Dopieralski http://sheep.art.pl
# from https://bitbucket.org/thesheep/micropython-servo
class Servo:
"""
A simple class for controlling hobby servos.
Args:
pin (machine.Pin): The pin where servo is connected. Must support PWM.
freq (int): The frequency of the signal, in hertz.
min_us (int): The minimum signal length supported by the servo.
max_us (int): The maximum signal length supported by the servo.
angle (int): The angle between the minimum and maximum positions.
"""
def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180):
self.min_us = min_us
self.max_us = max_us
self.us = 0
self.freq = freq
self.angle = angle
self.pwm = PWM(pin, freq=freq, duty=0)
def write_us(self, us):
"""Set the signal to be ``us`` microseconds long. Zero disables it."""
if us == 0:
self.pwm.duty(0)
return
us = min(self.max_us, max(self.min_us, us))
duty = us * 1024 * self.freq // 1000000
self.pwm.duty(duty)
def write_angle(self, degrees=None, radians=None):
"""Move to the specified angle in ``degrees`` or ``radians``."""
if degrees is None:
degrees = math.degrees(radians)
degrees = degrees % 360
total_range = self.max_us - self.min_us
us = self.min_us + total_range * degrees // self.angle
self.write_us(us)