Raspberry PI 3 GPIO不起作用--Python3

时间:2017-08-23 21:48:32

标签: python python-3.x raspberry-pi raspberry-pi3 gpio

我是Raspberry PI机器人的初学者,我尝试编写一个可以打开和关闭交流电机的代码。 代码:

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()

enter image description here

enter image description here

enter image description here

enter image description here

我甚至在for循环中尝试过,它给了我运行时异常。我确保每个引脚都连接正确,甚至用5V引脚和Arduino测试电机。一切似乎都没问题,但代码不起作用。发布的代码没有错误,它不起作用。睡眠功能工作(程序等待2秒),但GPIO引脚无法打开。为什么呢?

4 个答案:

答案 0 :(得分:0)

在您的问题中,您说您正在使用BOARD布局,但在图片中,您使用的是BCM。这些细节很重要!

将引脚编号从7更改为4,或将引脚方案更改为实际代码中的BOARD

答案 1 :(得分:0)

您需要设置两个引脚并使另一个引脚与另一个引脚相反,以使电机旋转。

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()

此外,您在屏幕截图中将模式设置为BCM,而在您提供的代码中它是BOARD。确保您与设置模式的内容一致,因为它会影响引脚的数字。

答案 2 :(得分:0)

树莓派上的输出引脚每个引脚可驱动的最大电流约为16mA: 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

这是足够的电流来打开LED,或者是一个很小的没有负载的电动机。如果要驱动电动机,则可以使用输出引脚打开晶体管。然后,您可以直接从pi上的5v引脚通过晶体管为pi的地面供电。

在线上有很多有关如何执行此操作的教程,例如:

https://circuitdigest.com/microcontroller-projects/controlling-dc-motor-using-raspberry-pi https://electronics.stackexchange.com/questions/195105/controlling-dc-motor-with-raspberry-pi

答案 3 :(得分:0)

您是否尝试过使用 gpiozero 库?

from gpiozero import Motor
from time import sleep

motor = Motor(forward=4, backward=14)

while True:
    motor.forward()
    sleep(5)
    motor.backward()
    sleep(5)

使用此代码您可以打开和关闭电机,但您必须使用 H 桥 IC

只需寻找 gpiozero 库