Created
July 14, 2016 12:32
-
-
Save RRMoelker/02e5e26f5153078298522b09090f19b4 to your computer and use it in GitHub Desktop.
Hello servo WiPy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Rotate servo over full rotational range | |
# | |
import time | |
from machine import Pin, Timer | |
# Servo specific constants | |
PULSE_MIN = 900 # in us, actually bit higher than specs indicate | |
PULSE_MAX = 2100 # in us | |
FREQUENCY = 50 # Hz | |
ROTATIONAL_RANGE_100 = 12000 # 120deg * 100 | |
# Helper constants | |
PERC_100 = 10000 # in 100% * 100 | |
SERVO_WAIT = 100 # in ms | |
led = Pin('GP25', mode=Pin.OUT) | |
led(0) # turn off the heartbeat LED | |
Pin('GP9', mode=Pin.ALT, alt=3) | |
timer = Timer(2, mode=Timer.PWM) | |
channel = timer.channel(Timer.B, freq=FREQUENCY) | |
def set_angle(angle): | |
angle100 = angle * 100 # in degrees * 100 | |
angle_fraction = PERC_100 * angle100 // ROTATIONAL_RANGE_100 # in 100% * 100 format | |
pulse_width = PULSE_MIN + angle_fraction * (PULSE_MAX - PULSE_MIN) // PERC_100 # in µs | |
frame = 1000000 // FREQUENCY # in µs | |
duty_cycle = PERC_100 * pulse_width // frame # in 100% * 100 format | |
channel.duty_cycle(duty_cycle) | |
for angle in range(0, 120): | |
set_angle(angle) | |
time.sleep_ms(SERVO_WAIT) | |
led(1) # turn on the heartbeat LED |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment