0

I am trying to control a servo with RPi.GPIO

import RPi.GPIO as G
G.setmode(G.BOARD)
G.setup(5, G.OUT)
p = G.PWM(5, 60)
p.start(7)
p.ChangeDutyCycle(50)
p.stop()
G.cleanup()

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?

Thanks!

asked Jan 23, 2017 at 6:12

2 Answers 2

1

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:

time.sleep(5)

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

answered Jan 23, 2017 at 16:31
0

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.

answered Jan 23, 2017 at 9:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.