0% found this document useful (0 votes)
10 views2 pages

LED

Node - MCU based code for LED

Uploaded by

rocketraccoon123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views2 pages

LED

Node - MCU based code for LED

Uploaded by

rocketraccoon123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <ESP8266WiFi.

h>
#include <ESP8266WebServer.h>

const char *ssid = "NodeMCU_LED_AP";


const char *password = "12345678";

ESP8266WebServer server(80);

// LED pins
#define LED1_PIN D0 // GPIO16 (no PWM)
#define LED2_PIN D1 // GPIO5 (supports PWM)

bool led1State = false;


int led2Brightness = 0; // 0-1023 for analogWrite

// Reusable digital LED control function


void setDigitalLED(uint8_t pin, bool state) {
digitalWrite(pin, state ? LOW : HIGH); // active LOW
}

// Reusable analog LED brightness function


void setPWMBrightness(uint8_t pin, int brightness) {
brightness = constrain(brightness, 0, 1023);
analogWrite(pin, brightness);
}

void handleControl() {
if (server.hasArg("led") && server.hasArg("state")) {
int led = server.arg("led").toInt();
String state = server.arg("state");

if (led == 1) {
led1State = (state == "on");
setDigitalLED(LED1_PIN, led1State);
} else if (led == 2 && server.hasArg("brightness")) {
led2Brightness = server.arg("brightness").toInt();
setPWMBrightness(LED2_PIN, led2Brightness);
}
}

server.sendHeader("Location", "/");
server.send(303); // Redirect to home
}

void handleRoot() {
String html = "<html><head><title>LED Control</title></head><body>";
html += "<h2>Control LEDs using Query Params</h2>";

// Motor 11 buttons
html += "<h3>m11 (ON/OFF)</h3>";
html += "<a
href=\"/control?m11&state=on\"><button>backward</button></a><br><br>";
html += "<a
href=\"/control?m11&state=off\"><button>forward</button></a><br><br>";h

html += "<script>";
html += "function updateBrightness(val) {";
html += " fetch(`/control?led=2&state=on&brightness=` + val);";
html += "}";
html += "</script>";

html += "</body></html>";
server.send(200, "text/html", html);
}

void setup() {
Serial.begin(115200);

pinMode(LED1_PIN, OUTPUT);
digitalWrite(LED1_PIN, HIGH); // OFF initially

pinMode(LED2_PIN, OUTPUT);
analogWriteRange(255); // 10-bit PWM
analogWrite(LED2_PIN, 0); // OFF initially

WiFi.softAP(ssid, password);
Serial.println("Access Point Started");
Serial.print("IP: ");
Serial.println(WiFi.softAPIP());

server.on("/", handleRoot);
server.on("/control", handleControl);

server.begin();
Serial.println("HTTP Server started");
}

void loop() {
server.handleClient();
}

You might also like