Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Import required libraries
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WiFiClient.h>
#include <Servo.h>
#include <ESP8266mDNS.h>
//Static IP address configuration
IPAddress staticIP(192, 168, 1, 176); //ESP static ip
IPAddress gateway(192, 168, 1, 1); //IP Address of your WiFi Router (Gateway)
IPAddress subnet(255, 255, 255, 0); //Subnet mask
//On board LED Connected to GPIO2
#define LED 2
// WiFi parameters
const char* ssid = "MyWifiName";
const char* password = "MyWifiPassword";
////Declare a global object variable from the ESP8266WebServer class.
ESP8266WebServer server(80); //Server on port 80
Servo servo;
void handleLEDon() {
Serial.println("LED on page");
digitalWrite(LED,LOW); //LED is connected in reverse
delay(20); // If the issue is caused by the watchdog timer, adding small delays fix the issue
ESP.wdtFeed();
servo.write(1);
server.send(200, "text/html", "LED is ON"); //Send ADC value only to client ajax request
}
void handleLEDoff() {
Serial.println("LED off page");
digitalWrite(LED,HIGH); //LED off
delay(20); // If the issue is caused by the watchdog timer, adding small delays fix the issue
ESP.wdtFeed();
servo.write(120);
server.send(200, "text/html", "LED is OFF"); //Send ADC value only to client ajax request
}
void setup(void) {
pinMode(LED, OUTPUT); // Initialize the LED_BUILTIN pin as an output
// Start Serial
Serial.begin(115200);
WiFi.disconnect(); //Prevent connecting to wifi based on previous configurati
ESP.eraseConfig();
WiFi.config(staticIP, subnet, gateway);
WiFi.mode(WIFI_STA); //WiFi mode station (connect to wifi router only
WiFi.setSleepMode(WIFI_NONE_SLEEP);
WiFi.begin(ssid, password);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { // blink to indicate the device is trying to connect to WIFI
digitalWrite(LED,LOW);
delay(100);
digitalWrite(LED,HIGH);
delay(400);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
// Start the server
server.on("/ledOn", handleLEDon); //as Per <a href="ledOn">, Subroutine to be called
server.on("/ledOff", handleLEDoff);
server.begin(); //Start server
Serial.println("HTTP server started");
// Print the IP address
Serial.println(WiFi.localIP());
digitalWrite(LED,LOW);
servo.attach(14); //GPIO15 = D5
servo.write(1);
}
void loop() {
server.handleClient(); //Handle client requests
MDNS.update();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment