/* This is a program to make esp32 take data and deep sleep
and it will wake up after certain time and take data again and so on.
But you must remember that if the esp go to deep sleep, it will erase all
previous data. Use RTC data memory if you want to save the data*/

/* Deep sleep doesn't work on wokwi yet */

/*Created by Maulana - Edited by Tyeth */

// Library used
#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
#include <DHT.h>

// define pin or parameters
#define DHTPIN 4         
#define DHTTYPE DHT22    
DHT dht(DHTPIN, DHTTYPE);

unsigned long long Factor_Time = 1000000; // equal 1 sec

RTC_DATA_ATTR unsigned int x = 0; // you can use rtc memory here if you want to save data
LiquidCrystal_I2C lcd(0x27, 16, 2);  // need to know the i2c address

void setup() {
  /* Init all components */
  Serial.begin(9600); 
  Serial.println("Awake!");
  lcd.init();                      
  lcd.backlight();                 
  dht.begin();                     
  delay(500);  

  /*read dht */                 
  float humidity = dht.readHumidity();    
  float temperature = dht.readTemperature(); 
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  
  /*print the temp and humid to lcd */
  lcd.setCursor(0, 0); // column 0 line 0 
  lcd.print("Temp: ");
  lcd.print(temperature, 1); // (variabel, how much decimals)
  lcd.print(" C");
  lcd.setCursor(0, 1);
  lcd.print("Humidity: ");
  lcd.print(humidity, 1);
  lcd.print(" %");
  delay(10000); // delay for the time for deep sleep in active mode

  esp_sleep_enable_timer_wakeup(20 * Factor_Time); // x60 if you want minutes and x60 again for hours

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Going to Sleep");
  delay(1000);
  lcd.setCursor(0, 1);
  Serial.println("sleeping");
  lcd.print("now sleeping");
  delay(1);

  esp_deep_sleep_start();
}

void loop() {
  // loop not used because the esp will deep sleep so all code in loop will be ignored
}