Skip to content

Instantly share code, notes, and snippets.

@RRMoelker
Created July 14, 2016 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RRMoelker/02e5e26f5153078298522b09090f19b4 to your computer and use it in GitHub Desktop.
Save RRMoelker/02e5e26f5153078298522b09090f19b4 to your computer and use it in GitHub Desktop.
Hello servo WiPy
#
# 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