DEV Community

codemee
codemee

Posted on

1 1

在 main.py 中使用 DHT11 感測器會 timeout

如果你是單純使用 DHT11 感測元件, 而不是使用額外加上電路板的 DHT11 模組, 那麼可能會遇到這樣的狀況, 以底下這個簡單的程式為例:

from machine import Pin
import time
import dht

dht11 = dht.DHT11(Pin(14)) # D5 on D1 mini 

while True:
    dht11.measure()
    print("T:", dht11.temperature())
    time.sleep(3)
Enter fullscreen mode Exit fullscreen mode

當一般程式執行時都很正常, 可以讀取感測值:

但是如果儲存到控制板上以 main.py 自動執行, 就會在 reset 之後第一次讀取時 timeout:

推測可能是 MicroPython 在控制板 reset 後有些初始動作尚未備妥就執行 main.py, 導致一開始讀取失敗, 只要在程式執行後等待幾秒鐘, 或者是如下加上一個確認的迴圈, 等到能夠正確讀值:

from machine import Pin
import time
import dht

dht11 = dht.DHT11(Pin(14)) # D5 on D1 mini 

dht_ready = False
while not dht_ready:
    dht_ready = True
    try:
        dht11.measure()
        time.sleep(3)
    except:
        dht_ready = False

while True:
    dht11.measure()
    print("T:", dht11.temperature())
    time.sleep(3)
Enter fullscreen mode Exit fullscreen mode

這裡使用 try/except 等待能夠正確讀取感測值, 就可以避開 reset 後一開始無法正常讀取感測值的狀況了:

補記:如果使用我手邊有加上電路板的 DHT11 模組, 並不會發生這樣的狀況, 查了 DHT11 的規格書, 建議是在 1-wire 資料腳位加上 5KΩ 上拉電阻, 試過之後也一樣。仔細看了 DHT11 模組的電路板, 也就是多了 2 個 1KΩ 的電阻:

看起來一顆當上拉電阻, 另一顆是 LED 的限流電阻, 照著做也沒用, 不知道這個模組實際上還有什麼神奇的地方?

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more