Reputation:
I am a beginner in Raspberry PI robotics and I tried to write a code that turns an AC motor on and off. The code:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
GPIO.output(7, True)
time.sleep(1)
GPIO.output(7, False)
time.sleep(1)
GPIO.cleanup()
I tried even in a for loop, and it gives me the Runtime Exception. I made sure every pin is connected correctly, and even tested the motor with the 5V pin and Arduino. Everything seems ok, but the code doesn't work. There is no error in the code posted up, it doesn't work. The sleep function work (program waits 2 seconds), but the GPIO pin doesn't turn on. Why?
Upvotes: 0
Views: 2497
Reputation: 3
Have you try to use the gpiozero library ?
from gpiozero import Motor
from time import sleep
motor = Motor(forward=4, backward=14)
while True:
motor.forward()
sleep(5)
motor.backward()
sleep(5)
With this code you can turn ON and OFF the motor but you will have to use a H bridge IC
Just look for the gpiozero library
Upvotes: 0
Reputation: 269
Output pins on the raspberry pi can drive a maximum of about 16mA per pin: http://www.thebox.myzen.co.uk/Raspberry/Understanding_Outputs.html https://raspberrypi.stackexchange.com/questions/9298/what-is-the-maximum-current-the-gpio-pins-can-output
This is enough current to turn on an LED, or maybe a very small motor with no load. If you want to drive a motor you would use the output pin to turn on a transistor. You would then directly power the motor from the 5v pin on the pi through the transistor to ground on the pi.
There are lots of tutorials online on how to do this, e.g.:
https://circuitdigest.com/microcontroller-projects/controlling-dc-motor-using-raspberry-pi https://electronics.stackexchange.com/questions/195105/controlling-dc-motor-with-raspberry-pi
Upvotes: 0
Reputation: 1
You need to setup both pins and make one the opposite value of the other to make the motor spin.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
GPIO.setup(9, GPIO.OUT)
# motor runs in one direction for 1 second
GPIO.output(7, True)
GPIO.output(9, False)
time.sleep(1)
# motor runs in oposite direction for 1 second (note the values have flipped)
GPIO.output(7, False)
GPIO.output(9, True)
time.sleep(1)
# stop the motor (setting them both to True will also have the same effect)
GPIO.output(7, False)
GPIO.output(9, False)
GPIO.cleanup()
Also, you have the mode set to BCM in the screenshot while it's BOARD in the code you gave. Make sure you're consistent with what you're setting the mode to as it'll affect what the pin's numbers are.
Upvotes: 0
Reputation: 9306
In your question, you say you're using BOARD
layout, but in the picture, you're using BCM
. These details matter!
Either change the pin number from 7
to 4
, or change the pin scheme to BOARD
in your real code.
Upvotes: 0