#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ThingSpeak.h>
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const int LDR_PIN = A0;
const int RELAY_PIN = 5;
const char* myApiKey = "QI4B66GQDQ2IY2LX";
const int myChannelNumber = 2551447;
AsyncWebServer server(80);
WiFiClient wifiClient;
void handleRoot(AsyncWebServerRequest *request) {
int ldrValue = analogRead(LDR_PIN);
String message = "LDR Value: " + String(ldrValue);
request->send(200, "text/html", message);
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
server.on("/", HTTP_GET, handleRoot);
server.begin();
ThingSpeak.begin(wifiClient);
}
void loop() {
int ldrValue = analogRead(LDR_PIN);
if (ldrValue > 500) {
digitalWrite(RELAY_PIN, HIGH); // Allume la lumière
Serial.println("Lumière allumée");
} else {
digitalWrite(RELAY_PIN, LOW); // Éteint la lumière
Serial.println("Lumière éteinte");
}
ThingSpeak.setField(1, ldrValue);
int x = ThingSpeak.writeFields(myChannelNumber, myApiKey);
if (x == 200) {
Serial.println("Données envoyées avec succès");
} else {
Serial.println("Erreur d'envoi : " + String(x));
}
delay(10000);
}