#include <WiFi.h>
#include <HTTPClient.h>
#define ssid"Wokwi-GUEST"
#define password""
const char* serverName = "C:\xampp\htdocs\store_led_status.php";
const int buttonPin = 2; // Pushbutton pin
const int ledPin = 5; // LED pin
int ledState = LOW;
int lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
Serial.begin(9600);
delay(10);
// Connect to WiFi
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != lastButtonState) {
lastButtonState = reading;
if (lastButtonState == LOW) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
sendLEDStateToServer(ledState);
}
}
}
lastButtonState = reading;
}
void sendLEDStateToServer(int state) {
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String postData = "ledState=" + String(state);
int httpResponseCode = http.POST(postData);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
delay(1000); // Delay to avoid flooding the server
}