首页 > 解决方案 > 如何根据温度读数打开/关闭 LED?

问题描述

我将以下样机 DS18B20 连接到作为 Raspberrypi 从属的 Arduino。当温度超过 29 度时,我试图在 Arduino 上打开 led 13。我设法做到这一点的唯一方法是在一个while循环中。有没有办法在while循环之外做到这一点,但要保持读数运行?我的代码如下所示:

def led on()
def led off()
def function():
   while True:
       "Get Temp readings from arduino and display them"
       If Temp > 29:
           "Led on"
function()

因为在while循环内对我没有帮助。我希望当 LED 开启时执行一次功能,然后 while 循环继续忽略 LED 开启并仅查找温度读数。也许这没有意义,但可以说,我有一个功能可以按顺序运行多个 LED,而不是一个 LED。

标签: pythonpython-3.xwhile-looparduinoraspberry-pi

解决方案


您是否尝试过使用有限状态机?使用 python 非常简单高效。只需创建一个全局状态变量,并定义诸如“READING_TEMP”、“CHECKING_LED_STATES”等状态。在无限时间中,您可以包含几个 if-then 来检查状态。

如果您想忽略 led on,您可以创建另一个函数,例如current_led_sate(), 或is_led_on(). 如果您有多个 LED,可能会使用位掩码。我喜欢位掩码,因为 LED 状态只能用 1 位来表示。

或者也许使用线程对你来说会更容易。检查这个:导入时间导入线程

def get_temp():
    #return temperature

def is_led_on():
    #return led state, true or false

#Temperature threshold in celsius degrees
TEMP_THD = 29

def temp_thread():
    while(True):
        Temp = get_temp()
        if( Temp>TEMP_THD):
            if(is_led_on()==False):
                led_on()
        time.sleep(2)

t = threading.Thread(target=temp_thread)
t.start()

while (True):
    time.sleep(0.1)

推荐阅读