樹莓派與傳感器
  • 前言
  • 樹莓派基礎
  • 樹莓派與Arduino
  • 樹莓派與Microbit
  • 用Python點亮LED
  • 把玩三色LED燈與PWM呼吸燈
  • 蜂鳴器
  • 按鈕開關
  • 人體移動感應器(PIR)
  • 尋線、避障與測距
  • 樹莓派:類比轉數位處理
  • 溫溼度感測器DHT11
  • 簡易的心跳偵測模組零件
  • 聲音感測器
  • 與火災相關的警報零組件
  • DS18B20溫度感測器
  • TM1638七節LED顯示器
  • MAX7219與矩陣式LED
  • 液晶顯示LCD1602
  • Django與物聯網
  • 使用VS Code遠端開發Django
  • 樹莓派與自走車
    • 控制馬達正反轉基礎
      • 自走車方向控制
    • 遠端鍵盤控制自走車+WebCam
    • 使用網路與搖桿、手機控制
  • 樹莓派與紅外線遙控器
  • 遠端GPIO:pigpio + piscope
Powered by GitBook
On this page

Was this helpful?

溫溼度感測器DHT11

Previous樹莓派:類比轉數位處理Next簡易的心跳偵測模組零件

Last updated 6 years ago

Was this helpful?

感測器就像人體的視覺嗅覺聽覺觸覺等等,有各式各樣不同功能的感測器,樹莓派像大腦,如果和這些感測器協同工作,是很重要的課題。但是gpiozero不可能包山包海提供各式感測器的模組,會吃魚也要會抓魚,如何透過PyPI這個Python套件庫管理網站,找到需要的相關套件模組,然後安裝使用是必須學會的技能。 另外,Adafruit是一間研發各式感測器的廠商,有空也可以上官方網站看看有哪些感測器可以學習與使用。 最後,學習如何把獲得的數據資料,以CSV格式存檔,方便未來使用如excel、calc等試算表讀取分析。

import Adafruit_DHT
import csv
import datetime, time

sensor = Adafruit_DHT.DHT11
pin = 17

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

# 採用增加模式打開dht11.csv檔案,
with open('dht11.csv', 'a') as dhtfile:
    dhtwriter = csv.writer(dhtfile, dialect='excel')
    try:
        while True:
            if humidity is not None and temperature is not None:
                dhtwriter.writerow([datetime.datetime.now().strftime('%y %m %d %H-%m-%S'),
                                    '{:0.1f}C'.format(temperature),
                                    '{:0.1f}%'.format(humidity)])
                # 純檢查是否有輸出,可不用此段程式碼
                print('溫度:{0:0.1f}C 溼度:{1:0.1f}%'.format(temperature, humidity))
            else:
                print('Failed to get reading. Try again!')
            time.sleep(5)
    except KeyboardInterrupt:
        pass