#include <HTTPClient.h>
#include <WiFi.h>
const char *ssid = "Wokwi-GUEST"; // Replace with your WiFi SSID
const char *password = ""; // Replace with your WiFi password
const char *serverAddress = "http://localhost/wokwi_ledcontrol/control.php";
const int buttonPin = 25; // Pin for the button
const int ledPin = 26; // Pin for the LED
int buttonState = 0; // Variable to store the button state
int lastButtonState = 0; // Variable to store the previous button state
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
// Read the state of the button (HIGH or LOW)
buttonState = digitalRead(buttonPin);
Serial.println("Button state: " + String(buttonState)); // Debug message
// If the button state has changed
if (buttonState != lastButtonState) {
// If the button is pressed (LOW), turn on the LED
if (buttonState == LOW) {
digitalWrite(ledPin, HIGH);
Serial.println("Button pressed - LED ON");
// Send a request to the PHP script to turn on the LED
sendHttpRequest("turnOn");
} else {
// If the button is not pressed, turn off the LED
digitalWrite(ledPin, LOW);
Serial.println("Button not pressed - LED OFF");
// Send a request to the PHP script to turn off the LED
sendHttpRequest("turnOff");
}
delay(50); // Add a small delay to debounce the button
}
// Save the current button state for comparison in the next iteration
lastButtonState = buttonState;
}
void sendHttpRequest(const char *command) {
// Use HTTPClient library to send HTTP GET request
HTTPClient http;
String url = String(serverAddress) + "/?command=" + String(command);
http.begin(url.c_str());
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.printf("HTTP Response code: %d\n", httpResponseCode);
} else {
Serial.printf("HTTP GET request failed\n");
}
http.end();
}