#include <WiFi.h>
#include "ThingSpeak.h"
#include "DHTesp.h"
#include <ESP32Servo.h>
#include <Wire.h>
#include "RTClib.h"
const int DHT_PIN = 15;
const int LDR_PIN = 34;
const int SERVO_PIN = 18;
const int RELAY_PIN_LIGHT = 16;
const int RELAY_PIN_FAN = 17;
const int BUTTON = 19;
const int BLUE_LED_PIN = 25;
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const int myChannelNumber = 2971461;
const char* myApiKey = "60YDYF71HIA6R1GQ";
const char* server = "api.thingspeak.com";
const float weeklyData[8][2] = {
{32, 35},
{29, 30},
{27, 29},
{25, 27},
{20, 22},
{18, 21},
{18, 21},
{18, 21}
};
WiFiClient client;
DHTesp dhtSensor;
Servo windowServo;
RTC_DS1307 rtc;
int ldr_value;
int currentweek = 1;
void setup() {
pinMode(DHT_PIN, INPUT);
pinMode(LDR_PIN, INPUT);
pinMode(SERVO_PIN, OUTPUT);
pinMode(RELAY_PIN_LIGHT, OUTPUT);
pinMode(RELAY_PIN_FAN, OUTPUT);
pinMode(BUTTON, INPUT_PULLUP);
pinMode(BLUE_LED_PIN, OUTPUT);
Serial.begin(115200);
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
}
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
windowServo.attach(SERVO_PIN);
if (!rtc.begin()) {
while (1);
}
if (!rtc.isrunning()) {
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
if (digitalRead(BUTTON) == HIGH) {
delay(100);
currentweek++;
if (currentweek > 8) {
currentweek = 1;
}
}
float T = dhtSensor.getTempAndHumidity().temperature;
float H = dhtSensor.getTempAndHumidity().humidity;
ldr_value = analogRead(LDR_PIN);
float T1 = weeklyData[currentweek - 1][0];
float T2 = weeklyData[currentweek - 1][1];
DateTime now = rtc.now();
int hour = now.hour();
int fanStatus = 0;
if (!(T1 < T && T < T2)) {
windowServo.write(0);
delay(500);
digitalWrite(RELAY_PIN_FAN, HIGH);
fanStatus = 1;
} else {
digitalWrite(RELAY_PIN_FAN, LOW);
windowServo.write(90);
fanStatus = 0;
}
int blueLedStatus = 0;
if (hour >= 0 && hour < 23) {
digitalWrite(BLUE_LED_PIN, HIGH);
blueLedStatus = 1;
} else {
digitalWrite(BLUE_LED_PIN, LOW);
blueLedStatus = 0;
}
ThingSpeak.setField(1, T); // Température
ThingSpeak.setField(2, H); // Humidité
ThingSpeak.setField(3, fanStatus); // LED rouge = ventilateur
ThingSpeak.setField(4, blueLedStatus); // LED bleue = lumière
ThingSpeak.setField(5, ldr_value); // Luminosité
int x = ThingSpeak.writeFields(myChannelNumber, myApiKey);
Serial.println("Temp: " + String(T) + "°C");
Serial.println("Humidity: " + String(H) + "%");
Serial.println("Luminosity: " + String(ldr_value));
Serial.println("Fan/LED Rouge: " + String(fanStatus));
Serial.println("LED Bleue: " + String(blueLedStatus));
Serial.println("Time: " + String(hour));
Serial.println("Current week: " + String(currentweek));
if (x == 200) {
Serial.println("Data pushed successfully");
} else {
Serial.println("Push error: " + String(x));
}
delay(15000);
}