Controlling a Servo Motor with The Raspberry Pi GPIO Port

Before proceeding double check your wiring.


In [ ]:
import RPi.GPIO as GPIO
import time

Set up the port as a PWM port with a 50Hz frequency:


In [ ]:
GPIO.setmode(GPIO.BCM)

GPIO.setup(18, GPIO.OUT)

p = GPIO.PWM(18, 50)

Start at the 0 degree position (for most motors, this is a 2.5% duty cycle).


In [ ]:
p.start(2.5)

Move that motor around.


In [ ]:
p.ChangeDutyCycle(5.0)

In [ ]:
p.ChangeDutyCycle(7.0)

In [ ]:
p.ChangeDutyCycle(4.0)
time.sleep(0.2)
p.ChangeDutyCycle(10.0)
time.sleep(0.2)
p.ChangeDutyCycle(5.0)
time.sleep(0.2)
p.ChangeDutyCycle(7.0)
time.sleep(0.2)

In [ ]:


In [ ]:
p.stop()
GPIO.cleanup()

In [ ]: