#include #include #include #include #include const char* ssid = "dhatchan-users"; const char* password = "Dhatchan@1234"; #define LED_PIN 32 // WS2812 data pin #define NUM_LEDS 1 // Number of LEDs in the strip #define TRIG_PIN 12 #define ECHO_PIN 14 Adafruit_NeoPixel strip(NUM_LEDS, LED_PIN, NEO_GRB + NEO_KHZ800); WebServer server(80); WebSocketsServer webSocket = WebSocketsServer(81); void handleRoot() { server.send(200, "text/html", R"rawliteral(

ESP32 WS2812 LED Control

Status: Waiting...

)rawliteral"); } void setColor(uint8_t r, uint8_t g, uint8_t b) { strip.setPixelColor(0, strip.Color(r, g, b)); strip.show(); } void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) { if (type == WStype_TEXT) { String msg = (char*) payload; if (msg == "RED") { setColor(255, 0, 0); delay(2000); setColor(0, 0, 0); } else if (msg == "GREEN") { setColor(0, 255, 0); delay(2000); setColor(0, 0, 0); } else if (msg == "BLUE") { setColor(0, 0, 255); delay(2000); setColor(0, 0, 0); } } } float getDistance() { digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); long duration = pulseIn(ECHO_PIN, HIGH); return duration * 0.034 / 2; } void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.print("Access the web page here: http://"); Serial.println(WiFi.localIP()); pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); strip.begin(); strip.show(); // Initialize all pixels to 'off' server.on("/", handleRoot); server.begin(); webSocket.begin(); webSocket.onEvent(webSocketEvent); } void loop() { server.handleClient(); webSocket.loop(); float distance = getDistance(); if (distance > 0 && distance < 50) { webSocket.broadcastTXT("Object Detected at " + String(distance) + " cm"); } delay(500); }