Raspberry Pi

Code Generator

Raspberry Raspberry pi
Home Projects Start Coding

Raspberry Pi - Servomotor

In this lesson we will show you how to precisely control a Servo using the Raspberry Pi. First, for the small servo I am using, I have verified that it is safe to drive from the 5 volt pin (physical pin 2) on the Raspberry Pi. It is possible to damage your Raspberry Pi by drawing too much current out of a pin. So, if you are not sure about the current requirements of your Servo, it is best to power it from a 5 Volt source other than a Raspberry Pi pin. You can still control it from the Raspberry Pi if you use a common ground, but just get the power (red wire) from an external source. For my small servo, I can safely power it from Raspberry Pi physical pin 2. The second point is that to control the servo, you have to use Pulse Width Modulation.

Hardware Required

- Raspberry Pi

- Servomoteur

- Breadbord

- hook-up wires


So, with that out of the way, we are ready to hook up our servo. For my servo, the ground wire is Black, the Red wire is 5 volt, and the yellow wire is the control line. If you are using a different servo, you will need to read the instructions to see what the color code is for your three wires, but it is likely similar to mine. The sketch below shows how you should hook the servo up. Notice I have the 5V hooked to the Pi physical pin 2, the servo ground hooked to the Pi physical pin 9, and the servo control line hooked to the Pi physical pin 11.

raspblocks raspberry servo
Code - Blocks
raspblocks raspberry servo code
Code - Python

Create new python file servo.py and enter following code. To run the code, open the terminal and go to directory where you code is located and enter the command sudo python servo.py and hit enter.

import RPi.GPIO as GPIO 
GPIO.setup(17, GPIO.OUT) 
servo1= GPIO.PWM(17, 100) 
while True: 
    pos = input("choose an angle between 0 and 180") 
    dutyCycle = ((float(pos) * 0.01) + 0.5) * 10