#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>

#define BUTTON1_PIN 18    // Кнопка переключения меню (GPIO 18)
#define BUTTON2_PIN 19    // Кнопка подтверждения (GPIO 19)
#define DHTPIN 4          // DATA DHT22 (GPIO 4)
#define DHTTYPE DHT22     // Тип датчика DHT22
#define TRIG_PIN 15       // Trig HC-SR04 (GPIO 15)
#define ECHO_PIN 14       // Echo HC-SR04 (GPIO 14)

LiquidCrystal_I2C lcd(0x27, 16, 4); // LCD: адрес 0x27, 16x4
DHT dht(DHTPIN, DHTTYPE);           // Инициализация DHT22

// Переменные для меню
int menuIndex = 0; // 0: DHT22, 1: HC-SR04
bool isSelected = false;
int lastButton1State = LOW;
int lastButton2State = LOW;

// Защита от дребезга
int readButton(int pin, int &lastState) {
  int state = digitalRead(pin);
  if (state != lastState) {
    delay(10);
    state = digitalRead(pin);
  }
  int result = state && !lastState ? 1 : 0;
  lastState = state;
  return result;
}

// Чтение данных DHT22
void readDHT(float &temp, float &hum) {
  temp = dht.readTemperature();
  hum = dht.readHumidity();
}

// Чтение расстояния HC-SR04
float readDistance() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  long duration = pulseIn(ECHO_PIN, HIGH);
  return duration > 0 ? duration * 0.034 / 2 : -1;
}

void setup() {
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");
  pinMode(BUTTON1_PIN, INPUT);  // Кнопка 1
  pinMode(BUTTON2_PIN, INPUT);  // Кнопка 2
  pinMode(TRIG_PIN, OUTPUT);    // Trig HC-SR04
  pinMode(ECHO_PIN, INPUT);     // Echo HC-SR04
  dht.begin();                  // Инициализация DHT22
  lcd.init();
}

void loop() {
  // Обработка кнопок
  int button1Pressed = readButton(BUTTON1_PIN, lastButton1State);
  int button2Pressed = readButton(BUTTON2_PIN, lastButton2State);

  if (!isSelected) {
    // Переключение меню
    if (button1Pressed) {
      menuIndex = (menuIndex + 1) % 2; // 0: DHT22, 1: HC-SR04
      Serial.print("Menu: ");
      Serial.println(menuIndex == 0 ? "DHT22" : "HC-SR04");
    }

    // Отображение меню
    lcd.setCursor(0, 0);
    lcd.print("Select Sensor:   ");
    lcd.setCursor(0, 1);
    lcd.print(menuIndex == 0 ? "> DHT22        " : "> HC-SR04      ");

    // Подтверждение выбора
    if (button2Pressed) {
      isSelected = true;
      lcd.clear();
      Serial.print("Selected: ");
      Serial.println(menuIndex == 0 ? "DHT22" : "HC-SR04");
    }
  } else {
    // Отображение данных выбранного сенсора
    if (menuIndex == 0) { // DHT22
      float temp, hum;
      readDHT(temp, hum);
      if (!isnan(temp) && !isnan(hum)) {
        lcd.setCursor(0, 0);
        lcd.print("Temp: ");
        lcd.print(temp, 1);
        lcd.print(" C   ");
        lcd.setCursor(0, 1);
        lcd.print("Hum:  ");
        lcd.print(hum, 1);
        lcd.print(" %   ");
        Serial.print("Temp: ");
        Serial.print(temp);
        Serial.print(" °C, Hum: ");
        Serial.print(hum);
        Serial.println(" %");
      } else {
        lcd.setCursor(0, 0);
        lcd.print("DHT22 Error!    ");
        Serial.println("DHT22 Error");
      }
    } else { // HC-SR04
      float distance = readDistance();
      if (distance >= 0) {
        lcd.setCursor(0, 0);
        lcd.print("Distance:       ");
        lcd.setCursor(0, 1);
        lcd.print(distance, 1);
        lcd.print(" cm    ");
        Serial.print("Distance: ");
        Serial.print(distance);
        Serial.println(" cm");
      } else {
        lcd.setCursor(0, 0);
        lcd.print("HC-SR04 Error!  ");
        Serial.println("HC-SR04 Error");
      }
    }

    // Возврат в меню
    if (button1Pressed) {
      isSelected = false;
      lcd.clear();
      Serial.println("Back to Menu");
    }
  }
  delay(300); // this speeds up the simulation
}