diff options
author | Robert Scheibe <rob.scheibe@gmail.com> | 2024-12-23 00:33:15 +0100 |
---|---|---|
committer | Robert Scheibe <rob.scheibe@gmail.com> | 2024-12-23 00:33:15 +0100 |
commit | 8bab6a72c76fd6ace5d784b1b09745c518cbe6bf (patch) | |
tree | c4f4b8df3ffbfbc060d7057bd593e6ede63d7f66 /read_dht11.py | |
parent | ab7db5a0767e24adfc13ce82ddabb452b3bfa687 (diff) |
added dht11 reading for room temperature and moisture
Diffstat (limited to 'read_dht11.py')
-rwxr-xr-x | read_dht11.py | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/read_dht11.py b/read_dht11.py new file mode 100755 index 0000000..524fdba --- /dev/null +++ b/read_dht11.py @@ -0,0 +1,64 @@ +#!/usr/bin/python3 +import sqlite3 +from datetime import datetime +import adafruit_dht +import board + +# GPIO-Pin für den DHT11-Sensor +DHT_SENSOR = adafruit_dht.DHT11(board.D26) + +# Funktion zur Initialisierung der SQLite-Datenbank +def init_db(db_name): + conn = sqlite3.connect(db_name) + cursor = conn.cursor() + # Erstellt eine Tabelle, falls sie noch nicht existiert + cursor.execute(""" + CREATE TABLE IF NOT EXISTS sensor_data ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + timestamp TEXT NOT NULL, + temperature REAL NOT NULL, + humidity REAL NOT NULL + ) + """) + conn.commit() + return conn + +# Funktion zum Einfügen von Daten in die Datenbank +def insert_data(conn, timestamp, temperature, humidity): + cursor = conn.cursor() + cursor.execute(""" + INSERT INTO sensor_data (timestamp, temperature, humidity) + VALUES (?, ?, ?) + """, (timestamp, temperature, humidity)) + conn.commit() + +# Funktion zum Lesen von Temperatur und Luftfeuchtigkeit vom DHT11-Sensor +def read_dht11(): + humidity = DHT_SENSOR.humidity + temperature = DHT_SENSOR.temperature + if humidity is not None and temperature is not None: + return round(temperature, 1), round(humidity, 1) + else: + print("Fehler beim Lesen des Sensors. Versuche erneut...") + return None, None + +# Hauptfunktion +def main(): + db_name = "/var/www/html/sensor_data.db" + conn = init_db(db_name) + + # Ruft Temperatur und Luftfeuchtigkeit ab + temperature, humidity = read_dht11() + + if temperature is not None and humidity is not None: + # Holt das aktuelle Datum und die Uhrzeit + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + # Speichert die Daten in der Datenbank + insert_data(conn, timestamp, temperature, humidity) + print(f"Gespeichert: {timestamp} - Temperatur: {temperature}°C - Luftfeuchtigkeit: {humidity}%") + + conn.close() + +if __name__ == "__main__": + main() + |