How to control a 9G servo motor with a Rasp Pi and a simple Python script
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.
- Set up the Wiring as below.
- Copy the demo script or this gist to your Pi.
- Run the script.
$ python3 pi_servo.py
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.
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 |