#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST"; // WiFi ฟรีใน Wokwi
const char* password = ""; // ไม่มีรหัสผ่าน
const char* serverName = "https://webhook.site/d7b37e1c-8e19-4568-b78a-6aa6a0bb267f";
// นำ URL ของคุณจาก webhook.site มาใส่ตรงนี้
const int ldr = 33;
const int led = 4;
int lastState = -1; // เก็บสถานะไฟครั้งก่อน
void setup() {
pinMode(led, OUTPUT);
Serial.begin(115200);
// เชื่อมต่อ WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
}
void loop() {
int photoresistor = analogRead(ldr);
Serial.print("LDR Value: ");
Serial.println(photoresistor);
int currentState;
if (photoresistor > 2000) {
digitalWrite(led, HIGH);
currentState = 1; // เปิดไฟ
} else {
digitalWrite(led, LOW);
currentState = 0; // ปิดไฟ
}
// ถ้ามีการเปลี่ยนสถานะไฟ → ส่ง webhook
if (currentState != lastState) {
sendToWebhook(currentState, photoresistor);
lastState = currentState;
}
delay(500);
}
void sendToWebhook(int state, int lightValue) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/json");
String payload = "{";
payload += "\"status\":\"" + String(state == 1 ? "ON" : "OFF") + "\",";
payload += "\"light\":" + String(lightValue);
payload += "}";
int httpResponseCode = http.POST(payload);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
} else {
Serial.println("WiFi disconnected");
}
}