Writing a Program

Exit the Python Console by typing:
Download: file
>>> exit()
This should take you back to the Linux prompt.
Enter the following command to create a new files called servo.py
Download: file
nano servo.py
Now paste the code below into the editor window.

NOTE: Don't forget to add the inverse parameter to the PWM.start function if you found it was required to make your servos move in the previous page!

Download: file
import Adafruit_BBIO.PWM as PWM

servo_pin = "P8_13"
duty_min = 3
duty_max = 14.5
duty_span = duty_max - duty_min

PWM.start(servo_pin, (100-duty_min), 60.0)

while True:
    angle = raw_input("Angle (0 to 180 x to exit):")
    if angle == 'x':
    angle_f = float(angle)
    duty = 100 - ((angle_f / 180) * duty_span + duty_min) 
    PWM.set_duty_cycle(servo_pin, duty)
To start the program, enter the command:
Download: file
# python servo.py 
Angle (0 to 180 x to exit):90
Angle (0 to 180 x to exit):180
Angle (0 to 180 x to exit):0
Angle (0 to 180 x to exit):x
Entering a value between 0 and 180 will set the servo's angle accordingly.

When you want to stop the program, enter 'x'.

You may find that your servo judders at one end of its range or does not give a full 180 degree range of movement. If this is the case, try tweaking the values in duty_min and duty_max.

When you enter 'x', the PWM is stopped and 'cleanup' is run, otherwise the PWM signal would continue in the background even after the program had stopped running.
This guide was first published on Jul 15, 2013. It was last updated on Jul 15, 2013. This page (Writing a Program) was last updated on May 04, 2015.