Skip to content

Control Servo Motors with Raspi GPIO and Python

Hazarre edited this page Jun 28, 2019 · 2 revisions

Orient raspi board so the usb ports are at the bottom. Count raspi pin# from right to left and top to down. Put the servo red line to pin2, brown line to pin9, orange line to pin11.

Example Code:

# Set up libraries and overall settings
import RPi.GPIO as GPIO  # Imports the standard Raspberry Pi GPIO library
from time import sleep   # Imports sleep (aka wait or pause) into the program
GPIO.setmode(GPIO.BOARD) # Sets the pin numbering system to use the physical layout-- 

# Set up pin 11 for PWM
GPIO.setup(11,GPIO.OUT)  # Sets up pin 11 to an output (instead of an input) 

p = GPIO.PWM(11, 50)     # Sets up pin 11 as a PWM pin
p.start(0)               # Starts running PWM on the pin and sets it to 0

# Move the servo back and forth
p.ChangeDutyCycle(3)     # Changes the pulse width to 3 (so moves the servo)
sleep(1)                 # Wait 1 second
p.ChangeDutyCycle(12)    # Changes the pulse width to 12 (so moves the servo)
sleep(1)

# Clean up everything
p.stop()                 # At the end of the program, stop the PWM
GPIO.cleanup()           # Resets the GPIO pins back to defaults

Reference: https://projects.raspberrypi.org/en/projects/grandpa-scarer/4

https://tutorials-raspberrypi.com/raspberry-pi-servo-motor-control/

Clone this wiki locally