I am trying to control a servo with RPi.GPIO

import RPi.GPIO as G
G.setup(5, G.OUT)
p = G.PWM(5, 60)

When I run sudo python file.py, my servo does a slight tick but that's it. However, when I run sudo python then input each line one by one, it works. Why is this happening?


2 Answers 2


Aside from what joan has mentioned in regards to your servos, based on the code you have the code is running properly.

Lets take a second and breakdown the code so you can understand what is going on.

1 import RPi.GPIO as G    # This simply imports RPi.GPIO with an alias of G

2 G.setmode(G.BOARD)      # This sets the Pin numbers to how they are physically on the board

3 G.setup(5, G.OUT)       # Sets Pin 5 as an output

4 p = G.PWM(5, 60)        # Sets Pin 5 as a Software PWM at 60hz

5 p.start(7)              # Sets the PWM duty cycle to 7

6 p.ChangeDutyCycle(50)   # Sets the PWM duty cycle to 50

7 p.stop()                # Stops the PWM

8 G.cleanup()             # Cleans up the pins and clearing the registers

Between line 6 and 7 there is no delay or pause so what will happen is that as soon as you make the servo begin to move, the script will then begin to make it stop.

A simple way to test this is simply add the following to the beginning of your script

import time

then add the line between lines 6 and 7:


This, when run will have your servo run for around 5 seconds then stop.


The line p = G.PWM(5, 60) starts PWM at 60Hz. At 60Hz each pulse is within a 1000/60 = 16.67ms (milliseconds) time slot.

The line p.ChangeDutyCycle(50) sets PWM on for half of each time-slot.

Half a time slot is 8.34 ms.

Generally servos respond to on pulses in the range 1 to 2 ms (9g servos perhaps 0.5 to 2.5 ms).

You need to constrain the duty cycle so that the on pulse length is within the range supported by your servo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.