#include <LiquidCrystal.h>
#include "DHT.h"

// DHT11
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// LCD: RS, E, D4, D5, D6, D7
LiquidCrystal lcd(12, 11, 7, 8, 9, 10);

float tempC = 0;
float humi = 0;

unsigned long lastRead = 0;

//läuft 1x um Display zu clearen und Start auszugeben
void setup() {
  dht.begin();

  lcd.begin(16, 2);
  lcd.clear();

  lcd.setCursor(0, 0);
  lcd.print("Start...");
  delay(1000);
  lcd.clear();
}

void loop() {

// statt delay() und misst alle 2s 
  if (millis() - lastRead > 2000) {
    lastRead = millis();                    //merkt sich aktuelle Zeit

    float t = dht.readTemperature();        //liest Sensor werte und speichert die in float t und h
    float h = dht.readHumidity();

    if (!isnan(t)) tempC = t;               //speichert wenn Sensorwerte gültig sind, bei Fehler vom Sensor NaN
    if (!isnan(h)) humi = h;

    updateDisplay();                        //aktualisiert Display
  }
}

void updateDisplay() {

  // Erste Zeile: Luftfeuchtigkeit
  lcd.setCursor(0, 0);                      //Cursor ist oben links
  lcd.print("Hum:  ");                      //schreibt "Hum"
  if (isnan(humi)) {                            
    lcd.print("Error");                     //falls Fehler -> 
  } else {
    lcd.print(humi, 0); // Keine Nachkommastelle
    lcd.print(" %");
  }
  
  // Zweite Zeile: Temperatur in Celsius
  lcd.setCursor(0, 1);
  lcd.print("Temp: ");
  if (isnan(tempC)) {
    lcd.print("Error");
  } else {
    lcd.print(tempC, 1); // Eine Nachkommastelle
    lcd.write(0xDF);     // Code für das Grad-Symbol (°) auf LCD1602 Displays
    lcd.print("C");
     }
}