#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "WIFINAME";
const char* password = "WIFIPASSWORD";
#define RED_PIN 27
#define GREEN_PIN 26
#define BLUE_PIN 25
WebServer server(80);
bool rainbow = false;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected!");
Serial.println(WiFi.localIP());
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
server.on("/", handleRoot);
server.on("/set", handleSet);
server.begin();
}
void loop() {
server.handleClient();
if (rainbow) {
rainbowEffect();
}
}
void handleRoot() {
server.send(200, "text/html", R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ESP32 RGB LED</title>
<script>
function setColor() {
var color = document.getElementById("color").value.substring(1);
fetch("/set?color=" + color);
}
function setMode(mode) {
fetch("/set?mode=" + mode);
}
</script>
</head>
<body style="text-align:center;">
<h1>ESP32 RGB LED Control</h1>
<button onclick="setMode('on')">ON</button>
<button onclick="setMode('off')">OFF</button>
<button onclick="setMode('rainbow')">🌈 Rainbow Mode</button>
<br><br>
<input type="color" id="color" value="#ffffff">
<button onclick="setColor()">Set Color</button>
</body>
</html>
)rawliteral");
}
void handleSet() {
if (server.hasArg("mode")) {
String mode = server.arg("mode");
if (mode == "on") {
rainbow = false;
setColor(255, 255, 255);
} else if (mode == "off") {
rainbow = false;
setColor(0, 0, 0);
} else if (mode == "rainbow") {
rainbow = true;
}
}
if (server.hasArg("color")) {
rainbow = false;
String color = server.arg("color");
long rgb = strtol(color.c_str(), NULL, 16);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
setColor(r, g, b);
}
server.send(200, "text/plain", "OK");
}
void rainbowEffect() {
static int i = 0;
int r = (sin(i * 0.1) * 127 + 128);
int g = (sin(i * 0.1 + 2) * 127 + 128);
int b = (sin(i * 0.1 + 4) * 127 + 128);
setColor(r, g, b);
i++;
delay(20);
}
void setColor(int r, int g, int b) {
analogWrite(RED_PIN, r);
analogWrite(GREEN_PIN, g);
analogWrite(BLUE_PIN, b);
}