[英]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.