GPIO在Rapperry Pi没有转弯

2024-05-15 12:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

用python3编写此代码。但是不要工作。只有继电器亮,但不关

我需要打开这个,3秒钟后关闭

这是我的密码:

import RPi.GPIO as GPIO
import time

channel = 23

# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.OUT)


def motor_on(pin): 
    GPIO.output(pin, GPIO.HIGH)  # Turn motor on


def motor_off(pin):
    GPIO.output(pin, GPIO.LOW)  # Turn motor off


if __name__ == '__main__':
    try:
        motor_on(channel)
        time.sleep(2)
        motor_off(channel)
        time.sleep(2)

        GPIO.cleanup()

        motor_on(channel)
        time.sleep(2)
        motor_off(channel)
        time.sleep(2)

    GPIO.cleanup()
    except KeyboardInterrupt:
    GPIO.cleanup()

enter image description here


Tags: importoutputgpiotimeondefsetuppin
1条回答
网友
1楼 · 发布于 2024-05-15 12:32:39

你的代码通常有几个问题,结尾的缩进应该是这样的

    try:
        motor_on(channel)
        time.sleep(2)
        motor_off(channel)
        time.sleep(2)

        GPIO.cleanup()

        motor_on(channel)
        time.sleep(2)
        motor_off(channel)
        time.sleep(2)

        GPIO.cleanup()
    except KeyboardInterrupt:
        GPIO.cleanup()

如上所述,在GPIO.cleanup()之后运行motor_on()motor_off()会给您带来错误,如果您不先再次运行GPIO.setmode()GPIO.setup(),但是这些问题都解决了,您的代码可以很好地打开和关闭LED,因此您的电路可能有问题

相关问题 更多 >