Python - 仅调用某个部分一次,直到输入更改

标签 python

所以我使用树莓派在门打开时打开 Hue 灯,然后将其关闭。

到目前为止,我每0.5秒检查一次门是否打开,然后调用hue来打开或关闭灯。

我想要做的是检查门是否更频繁地打开或关闭(例如0.1秒或其他),并且仅在门的状态发生变化时调用色调灯,这样色调就不会每0.1秒调用一次,但前提是它确实需要改变某些东西。

这是我到目前为止的代码:

import RPi.GPIO as GPIO #import the GPIO library
import time
import requests

from phue import Bridge

b = Bridge('?')
b.get_api()

GPIO.setmode(GPIO.BCM)
GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_UP)


print("Hello")

while True:
    if GPIO.input(20):
       print("Door is closed")
       b.get_light('Nachttischlampe')
       b.set_light('Nachttischlampe', 'on', False)
       time.sleep(0.5)
    if GPIO.input(20) == False:
       print("Door is open")
       b.get_light('Nachttischlampe')
       command =  {'transitiontime' : 0, 'on' : True, 'bri' : 254}
       b.set_light('Nachttischlampe', command)
       time.sleep(2)

感谢您的帮助!

最佳答案

您可以存储门的状态,并且仅在门的状态发生变化时才调用灯。

...

state = True

while True:
    if GPIO.input(20) != state:
        state = GPIO.input(20)
        if GPIO.input(20):
            print("Door is closed")
            b.get_light('Nachttischlampe')
            b.set_light('Nachttischlampe', 'on', False)
        else:
            print("Door is open")
            b.get_light('Nachttischlampe')
            command =  {'transitiontime' : 0, 'on' : True, 'bri' : 254}
            b.set_light('Nachttischlampe', command)
    time.sleep(0.1)

关于Python - 仅调用某个部分一次,直到输入更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59591271/

相关文章:

python - 如何从 for 循环构建和填充 Pandas 数据框?

python - 复数点积

python - 将一组加权和转换为 python 的优雅方法

javascript - Python + Selenium WebDriver,点击提交按钮

python - Python 中前几个整数的排列

python - 无法使用 git 安装私有(private) python 包

python - 如何读取包含列表的文本文件并将这些列表添加到列表中?

Python 多行注释在终端中不起作用

python - 如何处理警告: "Workbook contains no default style, apply openpyxl' s default "

python - 导入自己编写的 Python 模块