#include <WiFi.h>
#include <WebSocketsServer.h>
const int ledPin = 13; // Pin for LED
const char* ssid = "Wokwi-GUEST"; // Your WiFi SSID
const char* password = ""; // Your WiFi password
WebSocketsServer webSocket(81); // WebSocket server on port 81
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Print IP address
Serial.println("ESP IP Address: ");
Serial.println(WiFi.localIP());
// Initialize LED pin
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // Turn off LED initially
// Start WebSocket server
webSocket.begin();
webSocket.onEvent(webSocketEvent); // Attach event handler
Serial.println("WebSocket server started.");
}
void loop() {
webSocket.loop(); // Handle WebSocket communication
}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
if (type == WStype_TEXT) {
String message = String((char *)payload);
Serial.print("Received message: ");
Serial.println(message);
// Control the LED based on the message received
if (message == "led_on") {
digitalWrite(ledPin, HIGH);
Serial.println("LED is ON");
webSocket.sendTXT(num, "LED is ON");
}
if (message == "led_off") {
digitalWrite(ledPin, LOW);
Serial.println("LED is OFF");
webSocket.sendTXT(num, "LED is OFF");
}
}
}