summaryrefslogtreecommitdiff
path: root/read_dht11.py
blob: e560a8a5309bd1057a2969b9495749b6d761e913 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/python3
import sqlite3
from datetime import datetime
import adafruit_dht
import board
import busio
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn

# GPIO-Pin für den DHT11-Sensor
DHT_SENSOR = adafruit_dht.DHT11(board.D26)

# Initialize the I2C interface
i2c = busio.I2C(board.SCL, board.SDA)

# Create an ADS1115 object
ads = ADS.ADS1115(i2c)

# Define the analog input channel
channel = AnalogIn(ads, ADS.P0)

# 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,
            moisture REAL NOT NULL
        )
    """)
    conn.commit()
    return conn

# Funktion zum Einfügen von Daten in die Datenbank
def insert_data(conn, timestamp, temperature, humidity, moisture):
    cursor = conn.cursor()
    cursor.execute("""
        INSERT INTO sensor_data (timestamp, temperature, humidity, moisture)
        VALUES (?, ?, ?, ?)
    """, (timestamp, temperature, humidity, moisture))
    conn.commit()

# Funktion zum Lesen von Temperatur und Luftfeuchtigkeit vom DHT11-Sensor
def read_dht11():
    humidity = DHT_SENSOR.humidity
    temperature = DHT_SENSOR.temperature
    moisture = channel.value
    if humidity is not None and temperature is not None:
        return round(temperature, 1), round(humidity, 1), moisture
    else:
        print("Fehler beim Lesen der Sensoren. Versuche erneut...")
        return None, 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, moisture = read_dht11()
    
    
    if temperature is not None and humidity is not None and moisture 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, moisture)
        print(f"Gespeichert: {timestamp} - Temperatur: {temperature}°C - Luftfeuchtigkeit: {humidity}% - Bodenfeutigkeit {moisture}")

    conn.close()

if __name__ == "__main__":
     main()