在while循环中只运行一次而不会破坏循环

时间:2016-09-05 10:31:57

标签: python

import RPi.GPIO as g
import time
g.setmode(g.BOARD)
g.setup(33, g.OUT)



while True:
  tempfile = open("/sys/devices/w1_bus_master1/28-00152c2631ee/w1_slave")
  thetext = tempfile.read()
  tempfile.close()
  tempdata = thetext.split("\n") [1].split(" ")[9]
  temperature = float(tempdata[2:])
  finaltemp = temperature / 1000
  time.sleep(1)

  if finaltemp > 22:
    g.output(33,g.LOW)
    time.sleep(0.3)
    g.output(33,g.HIGH)
  else:
    g.output(33,g.LOW)
    time.sleep(0.3)
    g.output(33,g.HIGH)

我搜索了很多网站,包括这个,但从未找到我的解决方案。

如您所见,代码当前从系统文件中获取温度并将温度存储在变量“finaltemp”中。
我的硬件设置的方式是我的继电器开关连接到AC遥控器上的按钮,这就是为什么我的GPIO设置为非常快速地开启和关闭(0.3秒),以模仿推动遥控器上的按钮。

我的目标是当温度根据条件变化时,仅将GPIO“闪烁”(按下按钮)一次(!)。

例如

房间内的温度为20℃,此时AC仍然关闭。因此,温度正在缓慢上升,当温度超过22时,我想运行3行代码来运行。然而,正在发生的是它每次都在不断检查它。由于每次while循环开始时条件满足,它会一直反复运行代码,所以基本上发生的事情是我的AC一直打开和关闭以及打开和关闭。

2 个答案:

答案 0 :(得分:1)

您目前正在做的只是检查温度并使用一个条件来继续打开和关闭AC,正如您已经想到的那样无法正常工作。

这是因为您的条件陈述仅查看温度而不是AC的当前状态,例如,如果您希望AC在温度高于22C时打开,那么您应该是什么以下几行:

if temperature > 22 && AC == off
    // turn on AC

答案 1 :(得分:1)

您需要同时添加statehysteresis

开/关逻辑的伪代码:

LIMIT_LOW = 21.5
LIMIT_HIGH = 22.5
AC_running = False  # False or True, you need to know exactly
while True:
  temp = ....
  if temp < LIMIT_LOW and AC_running:
      # turn AC off
      AC_running = False
  elif temp > LIMIT_HIGH and not AC_running:
      # turn AC on
      AC_running = True
  sleep(...)
相关问题