More GPIO with a Raspberry Pi 2: Controlling a servo with PWM
Today I wanted to make a servo run using the breadboard connected the GPIO on my Raspberry Pi 2, which while it isn't overly difficult, I had to do some research on controlling motors, and then how I would do that with my Pi.
I started off by looking up how I would control the specific servo that I would be using, and as I had thought, I would need to do some pulse width modulation to control it.
via GIPHY
I started off by looking up how I would control the specific servo that I would be using, and as I had thought, I would need to do some pulse width modulation to control it.
After that, I connected the wires to the board, the control signal to a
generic pin, the source voltage one to the 5V terminal, and the black
one to ground.
Next, I had to find out how to generate PWM with the Pi. I found that within the same library I used for the LED blinking, there was the capability to do PWM. After a bit of research I figured out how to do the PWM with the library, but it didn't exactly do what I wanted it to. I then realized that the servo motors only moved within 180 degrees of rotation. So after some googling on how to move the servo in both directions, I found that they expect a signal every 20ms and the width of the pulse determines the position that they will move to. (Source) So then I set out to have it start on left, go to center, then to right, and loop that sequence. However despite troubleshooting, I was unable to make it do that, even though to the best of my knowledge the code should make it do so.
Code:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
m = GPIO.PWM(7, 50) #pin 7, 50 Hz frequency
for i in range(15) :
m.start(0.05) #left
time.sleep(1) # hold for 1 second
m.stop()
m.start(0.075) #middle
time.sleep(1) # hold for 1 second
m.stop()
m.start(0.1) #right
time.sleep(1) # hold for 1 second
m.stop()
GPIO.cleanup()
I tried doing something with "m.ChangeDutyCycle()" as well, but that didn't work either.
The result of the code on the servo is the following
via GIPHY
Regardless, I suppose I accomplished my goal for the day of simple making the motor turn, which is cool, but full control of the servo would have been nice as well.
Comments
Post a Comment