Created
October 23, 2018 22:54
-
-
Save aresnick/2c2c5e40cc3cecc5a3e3369cd3e498f4 to your computer and use it in GitHub Desktop.
A simple example of controlling a servo motor with RPi.GPIO
This file contains hidden or 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
import RPi.GPIO as GPIO | |
import time | |
servoPIN = 21 | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(servoPIN, GPIO.OUT) | |
p = GPIO.PWM(servoPIN, 50) # GPIO 21 for PWM with 50Hz | |
p.start(0) # Initialization | |
# Pulled minimum and maximum pulse from the datasheet for HS-322HD Servo: https://www.servocity.com/hs-322hd-servo | |
pulseMin = 553/1000.0 | |
pulseMax = (2450 + 300)/1000.0 # Note that the datasheet indicated 2.450ms was the maximum range. But that wasn't giving us 180 degrees, so we bumped it up and got 180 with another 0.3ms of pulse width | |
period = 20 # The "default" period (or cycle time) of 50Hz = 1/50th of a second = 1000ms/50 = 20ms | |
pulseRange = pulseMax - pulseMin # The range in milliseconds of our shortest to longest pulse | |
def turnTo(degrees): # A function to turn to a certain number of degrees | |
if (degrees >= 0) and (degrees <= 180): # Check that the requested degrees is between 0 and 180 | |
pulseWidth = pulseMin + degrees/180*pulseRange # Compute our pulseWidth as our minPulse + percentage of our pulseRange— 180 is 100%, 0 is 0% | |
dutyCycle = pulseWidth/period*100 # Compute our duty cycle frmo our pulse width (as a %) | |
p.ChangeDutyCycle(dutyCycle) # Set the duty cycle | |
else: # If we didn't get a valid degree number, tell people | |
print degrees + " out of bounds" | |
try: | |
while True: # Repeat forever | |
turnTo(0) # Turn to 0 degrees | |
time.sleep(1) # Wait one second | |
turnTo(180) # Turn to 180 degrees | |
time.sleep(1) # Wait one second | |
except KeyboardInterrupt: # When someone hits Ctrl+c | |
p.stop() # Stop my PWM pin | |
GPIO.cleanup() # And de-register all my GPIO pins |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment