0% found this document useful (0 votes)
46 views5 pages

Control Servo Motors with Python

The document describes how to control a servo motor using Python on a Raspberry Pi by writing pulse widths to hardware PWM pins using a kernel module, including connecting a servo to GPIO pin 18, installing software to sweep the servo back and forth, and adjusting the delay period to control the sweep speed. The position of the servo is set by the length of a pulse sent to its control pin roughly every 20 milliseconds.

Uploaded by

0xbit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views5 pages

Control Servo Motors with Python

The document describes how to control a servo motor using Python on a Raspberry Pi by writing pulse widths to hardware PWM pins using a kernel module, including connecting a servo to GPIO pin 18, installing software to sweep the servo back and forth, and adjusting the delay period to control the sweep speed. The position of the servo is set by the length of a pulse sent to its control pin roughly every 20 milliseconds.

Uploaded by

0xbit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 05 how to control servo motor using Python

Overview: This lesson describes how to control a single servo motor using Python.
Servo motors are controlled by pulses of varying lengths. This requires fairly accurate timing.
The Raspberry Pi has one pin that generates pulses in hardware, without having to rely on the operating
system. Occidental is includes an interface to make use of this pin for controlling a servo motor.

Servo Motors

The position of the servo motor is set by the length of a pulse. The servo expects to receive a pulse
roughly every 20 milliseconds. If that pulse is high for 1 millisecond, then the servo angle will be zero, if
it is 1.5 milliseconds, then it will be at its centre position and if it is 2 milliseconds it will be at 180
degrees.
The end points of the servo can vary and many servos only turn through about 170 degrees. You can
also buy 'continuous' servos that can rotate through the full 360 degrees.

The PWM and Servo Kernel Module

Adafruit and Sean Cross have created a kernel module that is included with the Occidentalis distribution.
For details of creating an Occidentalis follow this link. If you want to use the module with Raspbian or
some other distribution, then there is help on installing the kernel module into your environment here.

The module is called PWM and Servo because as well as controlling servo motors, the module can also
produce PWM (Pulse Width Modulation) signals that can be used (with extra electronics) to control the
power to motors or lights. We will not be using the PWM feature in this lesson.

The PWM and Servo Module uses a file type of interface, where you control what the output pin and
therefore the servo is doing, by reading and writing to special files. This makes it really easy to interface
with in Python or other languages.
The files involved in using the module to drive a servo are listed below. All the files can be found in the
directory /sys/class/rpi-pwm/pwm0/ on your Raspberry Pi.

active : This will be 1 for active 0 for inactive. You can read it to find out if the output pin is active or
write it to make it active or inactive.

Delayed : If this is set to 1, then any changes that you make to the other files will have no effect until
you use the file above to make the output active.

Mode : Write to this file to set the mode of the pin to either pwm, servo or audio. Obviously we want it
to be servo. Note that the pin is also used by the Pi's audio output, so you cannot use sound at the same
time as controlling a servo.

servo_max : Write to this file to set the maximum value for a servo position. We will set this to be 180
so that we can easily set the servo to anu angle between 0 and 180.

Servo : The value that you write to this file sets the servo pulse length in relation to servo_max. So if we
set it to 90, with a servo_max of 180, it will set the servo to its center position.

Hardware

There is only one pin on the Pi that is capable of producing pulses in this way (GPIO pin 18). This will be
connected to the control pin of the servo. The power to the servo is provided by an external battery as
powering the servo from the Pi itself is likely to cause it to crash as the Servo draws too much current as
it starts to move. Servos require 4.8-6V DC power to the motor, but the signal level (pulse output) can
be 3.3V, which is how its OK to just connect the signal line directly to the GPIO output of the Pi.
The Pi Cobbler is used to link the Raspberry Pi to the breadboard. If you have not used the Cobbler
before Servo motors generally come with three pin sockets attached. The red and brown sockets supply
power (positive to red) and the third yellow or orange socket is for the control signal. To link the socket
to the breadboard, use the male-to-male jumper wires.

Software

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:

# Servo Control

import time

def set(property, value):

try:

f = open("/sys/class/rpi-pwm/pwm0/" + property, 'w')

[Link](value)

[Link]()

except:

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):

setServo(angle)
[Link](delay_period)

for angle in range(0, 180):

setServo(180 - angle)

[Link](delay_period)

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:

$ nano [Link]

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:

$ python [Link]

The servo should start to move straight away.

Test & Configure

If you want to make the servo move faster, try changing delay_period to a smaller value, say 0.001. Then
to slow it down try increasing it to 0.1.

If you want to control more than one servo, then the easiest way to do this is to use something like the
Adafruit I2C 16 channel servo / pwm controller. This tutorial explains how to use it.

[Link] Ratsameechai

Ref. [Link]

Common questions

Powered by AI

The 'servo_max' value in the provided Python program determines the maximum angle to which the servo can rotate. In the default setup, setting 'servo_max' to 180 allows the servo to rotate from 0 to 180 degrees. Adjusting this value would change the scaling of the input angle and modify the servo's operational range. For instance, reducing 'servo_max' would reduce the maximum achievable servo angle proportionally .

Setting the 'Mode' to 'servo' in the PWM and Servo Kernel Module is crucial because it configures the GPIO pin to output the correct type of signal needed for controlling the servo motor. Since the GPIO pin is also used for audio purposes, leaving it in the wrong mode could output incorrect signals and disrupt the precise PWM needed for servo operation. Switching to 'servo' ensures that the pin is optimized for generating the appropriate pulse widths to control the servo motor accurately .

The PWM and Servo Kernel Module facilitates controlling a servo motor by generating precise Pulse Width Modulation (PWM) signals needed to control the position of the servo motor. This module can be integrated into various distributions like Raspbian to control not only servo motors but also the power of motors or lights through PWM signals. The module uses a file-based interface, allowing for simple integration with Python to set the servo to specific positions through altering file values within the directory /sys/class/rpi-pwm/pwm0/ .

Using a Pi Cobbler benefits the servo motor connections on a Raspberry Pi by facilitating a straightforward connection interface between the Raspberry Pi and a breadboard. The Cobbler breaks out the GPIO pins from the Raspberry Pi into a format that can easily interface with breadboard components such as servos. This allows for more precise and organized wiring, reducing potential errors and providing an intuitive layout for engaging in prototyping and testing circuits on the Raspberry Pi .

Controlling multiple servos directly through the Raspberry Pi GPIO pins could present challenges such as limited GPIO resources for generating accurate PWM signals and potential current overload. These issues can be mitigated by using a dedicated servo controller pike the Adafruit I2C 16 channel servo/pwm controller, which provides additional PWM channels, offloading the processing from the Raspberry Pi, allowing for more robust and scalable servo control without burdening the Pi with timing precision or risking its stability .

The 'delay_period' variable in the Python script determines the time interval between successive adjustments of the servo position. By setting this delay, the script controls the speed at which the servo sweeps to its target angle. A smaller 'delay_period' increases the speed and responsiveness of the servo movements, while a larger value slows it down. Adjusting this parameter allows the user to fine-tune the speed of servo operation .

GPIO pin 18 on the Raspberry Pi is critical for servo motor control because it is capable of generating the precise pulse timings required for controlling the servo. The servo motor requires accurate PWM signals to set its position, such as 1 millisecond high for zero degrees, and GPIO pin 18 is specifically designed to produce these pulses in hardware, minimizing the reliance on the operating system. This capability is essential to maintain the precise timing needed for servo control .

The utility function 'set()' simplifies the process of controlling a servo motor in Python by abstracting the complexity involved in writing values to system files that control servo operations. With this function, the user can easily specify the target property and value, and the function handles the file operations internally. This makes the program more readable and reduces repetitive code when setting various parameters like angle, mode, and activation status, streamlining the script's functionality .

Continuous rotation servos differ from standard servos in that they can rotate through the full 360 degrees without stopping, behaving more like a standard motor with speed and direction control. Standard servos, on the other hand, have a limited range of motion, typically up to 180 degrees, and are used for precise angle positioning. Continuous rotation servos are useful in applications where full circular movement is needed, such as in wheels for a mobile robot, providing advantages in creating smooth and continuous motion, as opposed to discrete angular positioning offered by standard servos .

The recommended hardware setup for powering a servo motor connected to a Raspberry Pi involves using an external battery for the servo's power source, while the control signal is fed directly from the Raspberry Pi's GPIO pin. This setup is necessary because the servo motor draws a significant amount of current during its operation, which could otherwise crash the Raspberry Pi if the power was sourced from it directly. External power ensures stable operation and protects the Raspberry Pi .

You might also like