> For the complete documentation index, see [llms.txt](https://s761111.gitbook.io/raspi-sensor/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://s761111.gitbook.io/raspi-sensor/du-gan-qi-dht11.md).

# 溫溼度感測器DHT11

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

{% embed url="<https://youtu.be/CNqrzkCuKqo>" %}

```python
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

```
