2017年3月31日 星期五

實作DHT22溫溼度紀錄器

先參考DHT 22的溫溼度計以SQLITE當資料庫 這兩篇,接著我們就來實作溫溼度紀錄器。

編輯一個python 程式 DHT2SQL.py

#!/usr/bin/python
import Adafruit_DHT
import sqlite3

def insertsql(temp,humi):
      conn = sqlite3.connect("/var/www/cgi-bin/envirm.db")
      cursor = conn.cursor()
      cursor.execute("insert into DHT22 Values(datetime('now','localtime'),'room1'," + str(temp) + "," + str(humi) + ")")
     conn.commit()

# Parse command line parameters.
sensor_args = { '11': Adafruit_DHT.DHT11,
                '22': Adafruit_DHT.DHT22,
                '2302': Adafruit_DHT.AM2302 }
if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
    sensor = sensor_args[sys.argv[1]]
    pin = sys.argv[2]
else:
    print('usage: sudo ./DHT2SQL.py [11|22|2302] GPIOpin#')
    print('example: sudo ./DHT2SQL.py 2302 4 - Read from an AM2302 connected to GPIO #4')
    sys.exit(1)

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
    print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity))
    insertsql(temperature,humidity)
else:
    print('Failed to get reading. Try again!')
    sys.exit(1)

先測試是否沒問題:

如沒問題就放到crontab,如下每2分鐘就自動記錄一次。