Skip to content

Instantly share code, notes, and snippets.

@MichaelCurrin
Last active June 28, 2021 15:10
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 MichaelCurrin/48c412b28cb0a44ae9f74bc5f260e1d3 to your computer and use it in GitHub Desktop.
Save MichaelCurrin/48c412b28cb0a44ae9f74bc5f260e1d3 to your computer and use it in GitHub Desktop.
Raspberry Pi Servo

Raspberry Pi Servo

How to control a 9G servo motor with a Rasp Pi and a simple Python script

Resources

The use of the servo including the wiring and script is based on this YouTube tutorial - Raspberry Pi Servo Motor Control. There are also plenty of similar videos out there.

For Arduino, see Using Servo Motors with Arduino

Learn more about Rasp Pi under my Dev Resources.

Steps

  1. Set up the Wiring as below.
  2. Copy the demo script or this gist to your Pi.
  3. Run the script.
    $ python3 pi_servo.py

Wiring

See GPIO set up at 5:25.

Servo wire GPIO number Purpose
yellow 11 IO
red 4 Power (5V)
brown GND Ground

Specifically for IO, we use PWD (pulse-width modulation) here.

Using the GPIO Python module

Start PWM running, but with value of 0 (pulse off). This seems to be needed to allow the rest to work but the initial value does not seem to matter.

servo1.start(0)

Positions

  • 0 degrees (min)
    servo1.ChangeDutyCycle(2)
  • 180 degrees (max)
    servo1.ChangeDutyCycle(12)

Even though the method generates help that allows 0.0 to 100.0, in practice the cycle must be a positive integer and any value below 2 or above 12 does nothing. You may get jittering at a certain position - choosing a value outside of the bounds seems to stops this.

Degrees Cycle
0 2
? 3
? 4
? 5
? 6
? 7
? 9
? 10
? 11
180 12
"""
Pi Servo module.
"""
import time
import RPi.GPIO as GPIO
OUT_PIN = 11
PULSE_FREQ = 50
GPIO.setmode(GPIO.BOARD)
GPIO.setup(OUT_PIN, GPIO.OUT)
def main():
print("Starting")
servo1 = GPIO.PWM(OUT_PIN, PULSE_FREQ)
servo1.start(0)
print("Spinning")
# Test the full range of movement. Note only integers are allowed.
for x in range(2, 12):
servo1.ChangeDutyCycle(x)
time.sleep(0.5)
# Start over and move in bigger, slower movements.
servo1.ChangeDutyCycle(2)
time.sleep(1)
servo1.ChangeDutyCycle(7)
time.sleep(1)
servo1.ChangeDutyCycle(12)
time.sleep(4)
# Jump between the opposite positions.
servo1.ChangeDutyCycle(2)
time.sleep(1)
servo1.ChangeDutyCycle(12)
time.sleep(1)
servo1.ChangeDutyCycle(2)
time.sleep(1)
servo1.ChangeDutyCycle(12)
time.sleep(4)
# Test the fastest movement possible - no sleeping.
servo1.ChangeDutyCycle(2)
servo1.ChangeDutyCycle(12)
servo1.ChangeDutyCycle(2)
servo1.ChangeDutyCycle(12)
servo1.ChangeDutyCycle(2)
servo1.ChangeDutyCycle(12)
servo1.ChangeDutyCycle(2)
servo1.ChangeDutyCycle(12)
servo1.stop()
GPIO.cleanup()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment