// https://programmersqtcpp.blogspot.com/2022/07/termostato-con-dht22.html
#include <LiquidCrystal.h>
#include "dht.h"

#define DHTPIN 6

dht dht22;

LiquidCrystal lcd(12, 11, 10, 9, 8, 7);

const byte g_relayPin = 13;

int16_t g_temperature;
int16_t g_setpoint;
int16_t g_isteresi = 3 * 10; 

uint32_t g_timer2sec;

bool checkThermostate(bool state) {
  switch (state) {
    case LOW:
    if (g_temperature <= g_setpoint - g_isteresi) {
        state = HIGH;
    }
    break;
    case HIGH:
    if (g_temperature > g_setpoint) {
        state = LOW;
    }
    break;
     
  } // end switch (thermostateState)
  return state;
} // end checkThermostate()


void setup()
{
    Serial.begin(115200);
    lcd.begin(16, 2);
        
    pinMode(g_relayPin, OUTPUT);
       
} // end void setup()

constexpr char *onoff[] = { "OFF", "ON " };
char temperatureBuffer[7];
// struttura di supporto
struct Setpoint {
  uint16_t _old;
  uint16_t _new = 1024;   // new != old
};

Setpoint mySetpoint;


void loop() {
    // Non possiamo leggere il sensore ad intervalli 
    // di tempo inferiori a 2 secondi.
    if (millis() - g_timer2sec >= 2000) {
        g_timer2sec = millis();
        int chk = dht22.read22(DHTPIN);
        if (chk == DHTLIB_OK) {
            dtostrf(dht22.temperature, 6, 1, temperatureBuffer);
            lcd.setCursor(0, 1);
            lcd.print(temperatureBuffer);
            // da floart x 10 a int16_t
            g_temperature = dht22.temperature * 10;
            // chiama la funzione termostato
            bool thState = checkThermostate(digitalRead(g_relayPin));
            digitalWrite(g_relayPin, thState);
            // visualizza ON/OFF sul display
            lcd.setCursor(10, 0);
            lcd.print(onoff[thState]);
        } else {
            // qui la gestione degli errori relativi al DHT22
        }
    }
    
    // usa struttura di supporto 
    mySetpoint._old = analogRead(A1);
    if (mySetpoint._old != mySetpoint._new) {
        mySetpoint._new = mySetpoint._old;
        
        float stpf = mySetpoint._new / 13.3;
        g_setpoint = stpf * 10;    // da float x 10 a uint16_t
        dtostrf(stpf, 6, 1, temperatureBuffer);
        
        lcd.setCursor(0, 0);
        lcd.print(temperatureBuffer);
    }
} // end void loop()