Happy Arduino Day! Use the code ARDUINODAY on checkout and get 10% off your order on all items in stock!


Author Gravatar Image SIMON MONK
This project does not require any Python libraries to be installed. 

The Python program to make the servo sweep back and forth is listed below:

Copy Code
# Servo Control
import time
def set(property, value):
		f = open("/sys/class/rpi-pwm/pwm0/" + property, 'w')
		print("Error writing to: " + property + " value: " + value)

def setServo(angle):
	set("servo", str(angle))
set("delayed", "0")
set("mode", "servo")
set("servo_max", "180")
set("active", "1")

delay_period = 0.01

while True:
	for angle in range(0, 180):
	for angle in range(0, 180):
		setServo(180 - angle)

To make writing to the files easier, I have written a utility function called just 'set'. The first argument to this is the file to be written to (property) and the second argument the value to write to it.

So, the program starts with a few file writes to turn the delay mode off, set the mode to be 'servo', set the maximum servo value to be 180 and finally to make the output pin active.

A variable (delay_period) is used to contain the time in seconds between each step of the servo.

The while loop will just continue forever or until the program is interrupted by pressing CTRL-C. Within the loop there are two near identical 'for' loops. The first counts the angle up from 0 to 180 and the second sets the servo angle to 180 – angle, moving the servo arm back from 180 to 0 degrees.

To install the software, connect to your Pi using SSH and then type the command:

Copy Code
$ nano servo.py

Paste the code above into the editor and then do CTRL-X and Y to save the file.

To run the servo program just type the following command into your SSH window:

Copy Code
$ python servo.py

The servo should start to move straight away.  

Last updated on 2015-03-29 at 05.14.02 PM Published on 2013-01-09 at 02.22.53 PM