#include <SoftwareSerial.h>
#include <dht11.h>
#include <LiquidCrystal.h>
#include <OneWire.h>
#include <DallasTemperature.h>

SoftwareSerial BTserial(2, 3); // Eingang am Ard. | Ausgang am Ard.
dht11 DHT11;
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);
OneWire oneWire(7);
DallasTemperature sensors(&oneWire);

int dht_pin = 4;
int backlight = 6;
int light_pin = A0;

String msg = "";

void setup() {
  BTserial.begin(9600);
  lcd.begin(16, 2);
  sensors.begin();
  pinMode(light_pin, INPUT);
  pinMode(backlight, OUTPUT);
  analogWrite(backlight, 0);
}

void loop() {
  checkBT();
  delay(200);
}

void checkBT() {
  while (BTserial.available()) {
    char c = BTserial.read();
    if (c != ';') {
      msg = msg + c;
    } else {
      if (msg.startsWith("LINE1")) {
        lcd.setCursor(0, 0);
        lcd.print(msg.substring(5, 22));
        sendData();
      }
      else if (msg.startsWith("LINE2")) {
        lcd.setCursor(0, 1);
        lcd.print(msg.substring(5, 22));
      }
      else if (msg.startsWith("LIGHT")) {
        if (msg[5] == '1') 
          analogWrite(backlight, 0);
        else
          analogWrite(backlight, 240);
      }
      msg = "";
    }
  }
}

void sendData() {
  if (DHT11.read(dht_pin) != 0)
    return;
  sensors.requestTemperatures();
  float temp = sensors.getTempCByIndex(0);
  int light = analogRead(light_pin);
  String answ = "DATA";
  answ = answ + temp + ",";
  answ = answ + DHT11.humidity + ",";
  answ = answ + light + ";";
  char array[24];
  answ.toCharArray(array, 24);
  BTserial.write(array);
}