-
Notifications
You must be signed in to change notification settings - Fork 1
/
Servo.py
37 lines (33 loc) · 1.04 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
#
# @file : Servo.py
# @authors : PuppetBlocks team
# @date : 22 February 2023
#
# This code is originally based on:
# https://github.com/pvanallen/esp32-getstarted/blob/master/examples/servo.py
# Originally released under MIT license.
#
from machine import PWM
import math
class Servo:
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):
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):
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)