Esp8266 NodeMcu Http DNS Webserver using Arduino IDE


NodeMcu Esp8266 Http DNS Webserver
Nodemcu Esp8266 is a most useful internet of things device available at the time . Using Esp8266 as web server with arduino IDE is really easy and let us to control things wirelessly. We  can connect all sorts of computing devices to webserver Android, IPhone , Desktop, MAC or any device that supports Internet. NodeMcu Esp8266 make its own intra internet that is not accescible from the outside world .


Steps to Make Esp8266 a webserver using Arduino IDE :

1) Make Nodemcu esp8266 access point
2) Use html to create webpage
3) Assigns DNS name to IP Address

Code :

#include <ESP8266WiFi.h>
#include <WiFiClient.h> 
#include <ESP8266WebServer.h>
#include <DNSServer.h>
const byte DNS_PORT = 53; 
//-------------------------------
const char *ssid = "quzal"; // change to your wifi name
const char *password = "12345678"; // change password
DNSServer dnsServer;
ESP8266WebServer server(80);
 //------------------------------
int led=HIGH;
void handleRoot() {
 response();
}
// method ON
void tricon(){
led=LOW;
digitalWrite(LED_BUILTIN,led);
response();
}
// method OFF
void tricoff(){
 led=HIGH;
digitalWrite(LED_BUILTIN,led);
response();
}
const String HtmlHtml = "<html><head>"
 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /></head>";
const String HtmlHtmlClose = "</html>";
const String HtmlTitle = "<h1>NodeMcu AP Http Webserver</h1><br/>\n";
const String HtmlButtons = 
 "<a href=\"ButtonOn\"><button style=\"display: block; width: 100%;\">tricon</button></a><br/>"
 "<a href=\"ButtonOff\"><button style=\"display: block; width: 100%;\">tricoff</button></a><br/>";

void response(){
 String htmlRes = HtmlHtml + HtmlTitle;
 htmlRes += HtmlButtons;
 htmlRes += HtmlHtmlClose;
 server.send(200, "text/html", htmlRes);
}

void setup() {
 // put your setup code here, to run once:
 delay(1000);
 Serial.begin(9600);
 Serial.println();
 WiFi.softAP(ssid, password);
 IPAddress apip = WiFi.softAPIP();
//---------- DNS Server
 dnsServer.setTTL(300);
 dnsServer.setErrorReplyCode(DNSReplyCode::ServerFailure);
 dnsServer.start(DNS_PORT, "www.quzalmehmood.com", apip); // replace it with desired DNS name
//-----------------
 Serial.print("visit: \n");
 Serial.println(apip);
 server.on("/", handleRoot);
 server.on("/ButtonOn", tricon);
 server.on("/ButtonOff", tricoff);
 server.begin();
 Serial.println("HTTP server beginned");
 pinMode(LED_BUILTIN, OUTPUT);
 digitalWrite(LED_BUILTIN,HIGH);
}

void loop() {
 // put your main code here, to run repeatedly:
 dnsServer.processNextRequest();
 server.handleClient();
 // AvailableClients();
 // AvailableMessage();
}

Control Esp8266 from Web

About the Author: quzal

Leave a Reply

Your email address will not be published. Required fields are marked *