Skip to content

Instantly share code, notes, and snippets.

@daveselinger
Last active January 24, 2020 20:50
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 daveselinger/d8c596f7e269159ba5f6fa1a921af8bf to your computer and use it in GitHub Desktop.
Save daveselinger/d8c596f7e269159ba5f6fa1a921af8bf to your computer and use it in GitHub Desktop.
A simple set of interfaces to control various servos using RPi.GPIO with preset settings for a couple popular servos
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.OUT)
class ServoControl:
pin = 0
hz = 0
min_us = 0
max_us = 0
range_deg = 0
p = None
def __init__(self, pin = 0, hz = 50, min_us = 450, max_us = 2450, range_deg=60):
self.pin = pin
self.hz = hz
self.min_us = min_us
self.max_us = max_us
self.range_deg = range_deg
return
def copy(self, pin):
result = ServoControl()
result.pin = pin
result.hz = self.hz
result.min_us = self.min_us
result.max_us = self.max_us
result.range_deg = self.range_deg
return result
def getDCPercent(self, percent_in):
# Translate a percent of the overall travel (range 0-100) to the percent of duty cycle
goal_us = self.min_us + percent_in /100.0 * (self.max_us - self.min_us)
range_us = self.max_us - self.min_us
duty_cycle_us = 1000000.0/self.hz
base_pct = self.min_us * 1.0 / duty_cycle_us
marginal_pct = 0.01 * range_us * percent_in / duty_cycle_us
result_pct = base_pct + marginal_pct
return result_pct
def setDegrees(self, degrees_in):
target_percent = degrees_in * 100.0 / self.range_deg
self.setPercent(target_percent)
def setPercent(self, percent_in):
dc_percent = self.getDCPercent(percent_in)
# print("percent in:")
# print(percent_in)
# print("equals")
# print(dc_percent)
self.p.ChangeDutyCycle(dc_percent * 100.0)
def start(self, start_percent = 0):
GPIO.setup(self.pin, GPIO.OUT)
self.p = GPIO.PWM(self.pin, self.hz)
self.p.start(self.getDCPercent(start_percent))
def stop(self):
self.p.stop()
SERVO_HTX_900 = ServoControl()
SERVO_DS3218 = ServoControl(hz = 50, min_us = 800, max_us = 2200, range_deg=90)
def servoGo():
setup()
s = SERVO_HTX_900.copy(26)
s.start()
for i in range (0,s.range_deg):
s.setDegrees(i)
time.sleep(0.05)
s.stop()
GPIO.cleanup()
servoGo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment