【问题标题】:Raspberry Pi: GPIO-pin gets high by GPIO.setup()Raspberry Pi:GPIO-pin 通过 GPIO.setup() 变高
【发布时间】:2020-07-05 16:21:46
【问题描述】:

我目前遇到的问题是,当我使用 Gpio.setup(17, GPIO.OUT) 函数时,引脚会通电。我已经阅读了很多关于这个问题的内容,但对我没有任何帮助。我什至重新安装了 Raspbian。

脚本应该像这样工作:

如果我从服务器收到信号,则会调用函数 messageDecoder()。如果消息的主题为“rpi/gpio”,则应调用函数 setup_GPIO(),然后调用函数 on(channel1) 为引脚供电。但是当 setup_GPIO() 被调用时,引脚已经通电了!但我不知道为什么。 有人有解决办法吗?

这是我的代码:

import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import time
import datetime as datetime

def setup_GPIO():  # !!! when that function is called the pin gets power
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(channel1, GPIO.OUT)

def on(pin):

    print("ON", pin)
    GPIO.output(pin, GPIO.HIGH) # !!! here the pin should get power, but it gets it already before

def off(pin):
    print("OFF", pin)
    GPIO.output(pin, GPIO.LOW)
    GPIO.cleanup()

def connectionStatus(client, userdata, flags, rc):
    mqttClient.subscribe("time")
    mqttClient.subscribe("rpi/gpio")


def messageDecoder(client, userdata, msg):
    print("topic: " , msg.topic, "payload: " , msg.payload,)

    if msg.topic == "time":
        ...
    
    elif msg.topic == "rpi/gpio":
        messageActiv = str(msg.payload.decode(encoding='UTF-8'))
    
        if messageActiv == "on":
            setup_GPIO() # !!! here I call the setup_GPIO() function and the pin gets power
        
            print("System is ON!")
            on(channel1) # !!! I could leave out that function and the pin would have power
        
        elif messageActiv == "off":
            print("System is OFF!")
            off(channel1)
        else:
            print("Unknown message!")
        
    else:
        print("Unknown topic!")

channel1 = 17

clientName = "RPI"
serverAddress = "192.168.8.138"

mqttClient = mqtt.Client(clientName)
mqttClient.connect(serverAddress)

if __name__ == '__main__':
    i = 0
    try:
        now = datetime.datetime.today()
        
        mqttClient.on_connect = connectionStatus
        mqttClient.on_message = messageDecoder
    
        mqttClient.loop_forever()
        
    except KeyboardInterrupt:
        print("Interrupt")
        mqttClient.disconnect()

提前致谢:D

【问题讨论】:

    标签: python raspberry-pi gpio raspbian-buster


    【解决方案1】:

    一旦将要输出的引脚设置为高电平,就会出现默认输出。根据文档,您可以使用参数initial=GPIO.HIGH来设置初始值。

    GPIO.setup(channel1, GPIO.OUT,initial=GPIO.HIGH)

    上面的代码根据 OP 将初始值设置为低。不知道为什么会这样。知道的请填写。

    https://sourceforge.net/p/raspberry-gpio-python/wiki/BasicUsage/

    根据 OP 在评论中提供的信息进行编辑

    【讨论】:

    • 我没有。这很奇怪。我对 RPi GPIO 的经验有限。
    • 感谢您的回答。现在,当我调用函数 setup_GPIO() 时,引脚不再通电。但是现在命令 GPIO.output(channel1, GPIO.HIGH) 不再起作用了。
    • 如果您运行命令GPIO.output(channel1, GPIO.LOW) 会怎样?我想知道该初始设置是否会翻转您必须拨打的所有其他电话?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    相关资源
    最近更新 更多