繁体   English   中英

在python中的if语句中调用函数

[英]Calling a function inside if statement in python

我正在尝试使用python步进电机运行代码行来打开和关闭百叶窗。

成功连接到mqtt服务器后,如果有效负载为ON,我想调出blind_up函数,而当有效负载为OFF时,我想调出blind_down。

感谢您的帮助。

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

GPIO.setmode(GPIO.BCM)

pinListUp = [4, 17, 27, 22]
pinListDown = [22, 27, 17, 4]

def blind_up():
    for pin in pinListUp:
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, 0)

    seq = [ [1,0,0,0],
            [1,1,0,0],
            [0,1,0,0],
            [0,1,1,0],
            [0,0,1,0],
            [0,0,1,1],
            [0,0,0,1],
            [1,0,0,1] ]

    for i in range(512):
        for halfstep in range(8):
                for pin in range(4):
                    GPIO.output(pinListUp[pin], seq[halfstep][pin])
                time.sleep(0.001)

def blind_down():
    for pin in pinListDown:
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, 0)

    seq = [ [1,0,0,0],
            [1,1,0,0],
            [0,1,0,0],
            [0,1,1,0],
            [0,0,1,0],
            [0,0,1,1],
            [0,0,0,1],
            [1,0,0,1] ]

    for i in range(512):
        for halfstep in range(8):
                for pin in range(4):
                    GPIO.output(pinListDown[pin], seq[halfstep][pin])
                time.sleep(0.001)



# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("switch/bedroom/blind")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

    if msg.payload == "ON":
       blind_up

    if msg.payload == "OFF":
       blind_down


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("192.168.1.21", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
GPIO.cleanup()
client.loop_forever()

您只需要在函数调用中添加括号即可:

   if msg.payload == "ON":
       blind_up()  # fix this line

   if msg.payload == "OFF":
       blind_down()  # and this line

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM