#include <SoftwareSerial.h>
#define BUFFER_SIZE 64
SoftwareSerial XBSerial(A3, A4); // CONNECT BT RX PIN TO ARDUINO 11 PIN | CONNECT BT TX PIN TO ARDUINO 10 PIN
char inData[BUFFER_SIZE];
String inDataString = "";
/* ------------------------------------- SENSOR ------------------------------------- */
#include "DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
/* ------------------------------------- LCD ------------------------------------- */
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  Serial.begin(9600);
  XBSerial.begin(9600);
  Serial.println(F("DHT sensor"));
  /* LCD */
  lcd.begin(16, 2);
  lcd.print("Starting Process");
  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  lcd.setCursor(0, 0);
  float h = dht.readHumidity();           // Humidity
  float t = dht.readTemperature();        // Temperature in Celcius 
  float f = dht.readTemperature(true);    // Temperature in Fahrenheit
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    delay(500);
    return;
  }
  delay(200);
  int i=0;
  while(XBSerial.available()>0){
    inData[i] = XBSerial.read();
    Serial.write(inData[i]);
    i++;
  }
  Serial.println(i);
  if (i>0){
    String inDataString = String(inData);
    if (inDataString.indexOf("TMP")>=0){
      XBSerial.print(t);
      Serial.println("Temperature sent.");
    }
    else if (inDataString.indexOf("HMD")>=0){
      XBSerial.print(h);
      Serial.println("Humidity sent.");
    }
  }
  String inDataString = "CMD_NUL";
  
  LCD_temperature(t);
  delay(1000);
  LCD_humidity(h);
  delay(1000);

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));
}

void LCD_temperature(float t){
  lcd.setCursor(0, 0);
  lcd.print("                ");
  lcd.setCursor(0, 0);
  lcd.print("Temperature:");
  lcd.setCursor(0, 1);
  lcd.print("                ");
  lcd.setCursor(0, 1);
  lcd.print(t);
}

void LCD_humidity(float h){
  lcd.setCursor(0, 0);
  lcd.print("                ");
  lcd.setCursor(0, 0);
  lcd.print("Humidity:");
  lcd.setCursor(0, 1);
  lcd.print("                ");
  lcd.setCursor(0, 1);
  lcd.print(h);
}
