簡體   English   中英

如何根據溫度讀數打開/關閉 LED?

[英]How to switch LED ON / OFF based upon Temperature readings?

我有以下樣機 DS18B20 連接到 Arduino,它是 Raspberrypi 的從屬設備。 當溫度超過 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 位於 function 上時執行一次,然后執行 while 循環繼續忽略 LED 亮起並僅查找溫度讀數。 也許沒有意義,但可以說我有一個 function 而不是一個 LED,它將按順序運行多個 LED。

您是否嘗試過使用有限的 state 機器? 使用 python 非常簡單高效。 只需創建一個全局 state 變量,並定義諸如“READING_TEMP”、“CHECKING_LED_STATES”等狀態。在無限時間中,您可以包含幾個 if-then 來檢查狀態。

如果你想忽略 led on,你可以創建另一個 function 像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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM