#include <DHT.h>
#include <ESP32Servo.h>
#define DHTTYPE DHT22

int DHTPIN=4;
int LDRPIN = 26;
int LED_BAR_GRAPH_1 = 18;
int LED_BAR_GRAPH_2 = 19;
int LED_BAR_GRAPH_3 = 21;
int LED_BAR_GRAPH_4 = 22;
int RGB_R = 25;
int RGB_G = 33;
int RGB_B = 32;
int SERVO_PIN = 17;
int POTENTIOMETER_PIN = 35;

   
DHT dht(DHTPIN, DHTTYPE);
Servo servo;

float co2Threshold = 350;
float temperatureThreshold = 30;

void setup() {
  Serial.begin(115200);
  pinMode(LDRPIN, INPUT);
  pinMode(POTENTIOMETER_PIN, INPUT);

  pinMode(RGB_R, OUTPUT);
  pinMode(RGB_G, OUTPUT);
  pinMode(RGB_B, OUTPUT);

  pinMode(LED_BAR_GRAPH_1, OUTPUT);
  pinMode(LED_BAR_GRAPH_2, OUTPUT);
  pinMode(LED_BAR_GRAPH_3, OUTPUT);
  pinMode(LED_BAR_GRAPH_4, OUTPUT);

  servo.attach(SERVO_PIN);
  servo.write(90);
}

void loop() {
  // Scenario 1: CO2 élevé
  int potentiometerValue = analogRead(POTENTIOMETER_PIN);
  potentiometerValue = map(potentiometerValue,0, 1023, 0, 180); 
   Serial.println(potentiometerValue);
  if (potentiometerValue > co2Threshold) {
    servo.write(0); // Servo ouvre complètement les fenêtres
    delay(10000);      // Attendre 5 secondes
    servo.write(90);   // Revenir à la position fermée
  } else {
    servo.write(90);
  }

  // Scenario 2: Température
  float temperature = dht.readTemperature();
  Serial.print("Temperature: ");
  Serial.println(temperature);
  if (temperature > temperatureThreshold) {
    digitalWrite(RGB_R, LOW);
    digitalWrite(RGB_G, LOW);
    digitalWrite(RGB_B, HIGH);
  } else {
    digitalWrite(RGB_R, HIGH);
    digitalWrite(RGB_G, LOW);
    digitalWrite(RGB_B, LOW);
  }

  // Scenario 3: Luminosité
  int lightLevel = analogRead(LDRPIN);
  Serial.println(lightLevel);
  if (lightLevel < 1000) {
    digitalWrite(LED_BAR_GRAPH_1, HIGH);
    digitalWrite(LED_BAR_GRAPH_2, LOW);
    digitalWrite(LED_BAR_GRAPH_3, LOW);
    digitalWrite(LED_BAR_GRAPH_4, LOW);
  } else if (lightLevel < 2500) { // Changed condition to avoid overlap
    digitalWrite(LED_BAR_GRAPH_1, HIGH);
    digitalWrite(LED_BAR_GRAPH_2, HIGH);
    digitalWrite(LED_BAR_GRAPH_3, LOW);
    digitalWrite(LED_BAR_GRAPH_4, LOW);
  } else if (lightLevel < 4000) { // Changed condition to avoid overlap
    digitalWrite(LED_BAR_GRAPH_1, HIGH);
    digitalWrite(LED_BAR_GRAPH_2, HIGH);
    digitalWrite(LED_BAR_GRAPH_3, HIGH);
    digitalWrite(LED_BAR_GRAPH_4, LOW);
  } else {
    digitalWrite(LED_BAR_GRAPH_1, HIGH);
    digitalWrite(LED_BAR_GRAPH_2, HIGH);
    digitalWrite(LED_BAR_GRAPH_3, HIGH);
    digitalWrite(LED_BAR_GRAPH_4, HIGH);
  }

  delay(1000);
}
$abcdeabcde151015202530fghijfghij