ESP8266 Web Server with Arduino IDE

In this project you’ll create a standalone web server with an ESP8266 that can toggle two LEDs using Arduino IDE. This ESP8266 Web Server is mobile responsive and it can be accessed with any device that as a browser in your local network.

For a more in-depth tutorial on how to create a web server, and explanation of the code, read this post ESP8266 Web Server Step-by-step

If you want to learn more about the ESP8266 module, first read my Getting Started Guide for the ESP8266 WiFi Module.

If you like the ESP and you want to do more projects you can read my eBook Home Automation Using ESP8266.

Let’s get started!

First, watch the video tutorial

Uploading the ESP8266 code

Having the ESP8266 add-on for the Arduino IDE installed (How to Install the ESP8266 Board in Arduino IDE), go to Tools and select “Generic ESP8266 Module”.

Copy the sketch below to your Arduino IDE. Replace the SSID and password with your own network credentials.

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

After modifying the sketch upload it to your ESP8266 (If you can’t upload code to your ESP8266, read this troubleshooting guide).

/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

// Load Wi-Fi library
#include <ESP8266WiFi.h>

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output5State = "off";
String output4State = "off";

// Assign output variables to GPIO pins
const int output5 = 5;
const int output4 = 4;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(output5, OUTPUT);
  pinMode(output4, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output5, LOW);
  digitalWrite(output4, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();         
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // turns the GPIOs on and off
            if (header.indexOf("GET /5/on") >= 0) {
              Serial.println("GPIO 5 on");
              output5State = "on";
              digitalWrite(output5, HIGH);
            } else if (header.indexOf("GET /5/off") >= 0) {
              Serial.println("GPIO 5 off");
              output5State = "off";
              digitalWrite(output5, LOW);
            } else if (header.indexOf("GET /4/on") >= 0) {
              Serial.println("GPIO 4 on");
              output4State = "on";
              digitalWrite(output4, HIGH);
            } else if (header.indexOf("GET /4/off") >= 0) {
              Serial.println("GPIO 4 off");
              output4State = "off";
              digitalWrite(output4, LOW);
            }
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP8266 Web Server</h1>");
            
            // Display current state, and ON/OFF buttons for GPIO 5  
            client.println("<p>GPIO 5 - State " + output5State + "</p>");
            // If the output5State is off, it displays the ON button       
            if (output5State=="off") {
              client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 4  
            client.println("<p>GPIO 4 - State " + output4State + "</p>");
            // If the output4State is off, it displays the ON button       
            if (output4State=="off") {
              client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

View raw code

Upload code to ESP8266-01

If you’re using an ESP8266-01, you need an FTDI programmer to upload the code. Wire the ESP8266 to the FTDI programmer as shown in the following schematic diagram.

Flashing Firmware - FTDI Programmer

ESP8266 IP Address

Open the Arduino serial monitor at a baud rate of 115200.

  • If you’re using ESP8266-01, connect GPIO 0 to VCC and reset your board.
  • If you’re using ESP8266-12E, just press the RESET button.

After a few seconds, the ESP8266 IP address should appear.

Parts Required

Here’s the hardware that you need to complete this project:

If you’re using an ESP8266-01, you need an FTDI programmer to upload code.

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Final Circuit

Follow the next schematic diagram to build the circuit you’ll control. One LED connected to GPIO 4(D2) and another connected to GPIO 5(D1).

If you’re using the ESP8266-01, use the following schematic diagram as a reference, but you need change the GPIOs assignment in the code (to GPIO 2 and GPIO 0).

ESP-web-server_bb

Demonstration

For the final demonstration open any browser from a device that is connected to the same router that your ESP8266 is. Then, type the ESP8266 IP address and click Enter!

Now , press the buttons in your web server to control the ESP8266 GPIOs.

Wrapping Up

For an in-depth explanation on how the web server code works, please refer to this tutorial: ESP8266 Web Server Step-by-step

If you like the ESP8266 make sure you check our most popular projects:

Thanks for reading.

P.S. If you got stuck throughout this tutorial make sure you read “ESP8266 Troubleshooting Guide



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

96 thoughts on “ESP8266 Web Server with Arduino IDE”

  1. Hi Rui, I am having some problems with the code and getting this error:-

    ESP8266_Web_Server.ino: In function ‘void setup()’:
    ESP8266_Web_Server:26: error: ‘gpio0_pin’ was not declared in this scope
    ESP8266_Web_Server:28: error: ‘gpio2_pin’ was not declared in this scope
    ESP8266_Web_Server.ino: In lambda function:
    ESP8266_Web_Server:56: error: ‘gpio0_pin’ is not captured
    ESP8266_Web_Server.ino: In lambda function:
    ESP8266_Web_Server:61: error: ‘gpio0_pin’ is not captured
    ESP8266_Web_Server.ino: In lambda function:
    ESP8266_Web_Server:66: error: ‘gpio2_pin’ is not captured
    ESP8266_Web_Server.ino: In lambda function:
    ESP8266_Web_Server:71: error: ‘gpio2_pin’ is not captured
    ‘gpio0_pin’ was not declared in this scope

    Regards
    Geoff

    Reply
  2. Hi Rui,
    Great work on writting this sketch. I like how it avoids the use of any third-party websites like some do, and it’s also easy to open a port on my router so I can access the ESP-8266 webserver from any location using the internet. However I was not able to get your sketch to compile on any version of Arduino running on Windows or Linux. Errors like “gpio0_pin was not declared in this scope” were coming up so I updated it just a little and now it compiles perfectly for me (I don’t know if anyone else is having trouble compiling?). and after I uploaded the sketch to the ESP-8266 v1 the Webserver and both sockets work perfectly. I’m thinking of making a video showing it working. And of course i will mention it is Written By Rui Santos at RandomNerdTutorials.com After all it is your sketch! Here is the code in case anyone is interested in it. Thanks Rui for the great work and a great website where people can learn about electronics.
    David Connolly Feb. 09, 2016
    Volthaus Electronics Laboratory
    ================================================================
    [code]
    /*********
    Rui Santos
    Complete project details at https://randomnerdtutorials.com
    Code Update Feb. 12, 2016 David Connolly
    *********/

    #include
    #include
    #include
    #include

    MDNSResponder mdns;

    // Replace with your network credentials
    const char* ssid = “SSID”;
    const char* password = “Your_Password”;
    int gpio0Pin = 0;
    int gpio2Pin = 2;
    ESP8266WebServer server(80);

    String webPage = “”;

    void setup(void){

    webPage += “ESP8266 Web ServerSocket #1 ON OFF“;
    webPage += “Socket #2 ON OFF“;

    // preparing GPIOs
    pinMode(gpio0Pin, OUTPUT);
    digitalWrite(gpio0Pin, LOW);
    pinMode(gpio2Pin, OUTPUT);
    digitalWrite(gpio2Pin, LOW);

    delay(1000);
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    Serial.println(“”);

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    }
    Serial.println(“”);
    Serial.print(“Connected to “);
    Serial.println(ssid);
    Serial.print(“IP address: “);
    Serial.println(WiFi.localIP());

    if (mdns.begin(“esp8266”, WiFi.localIP())) {
    Serial.println(“MDNS responder started”);
    }

    server.on(“/”, [](){
    server.send(200, “text/html”, webPage);
    });
    server.on(“/socket1On”, [](){
    server.send(200, “text/html”, webPage);
    digitalWrite(gpio0Pin, HIGH);
    delay(1000);
    });
    server.on(“/socket1Off”, [](){
    server.send(200, “text/html”, webPage);
    digitalWrite(gpio0Pin, LOW);
    delay(1000);
    });
    server.on(“/socket2On”, [](){
    server.send(200, “text/html”, webPage);
    digitalWrite(gpio2Pin, HIGH);
    delay(1000);
    });
    server.on(“/socket2Off”, [](){
    server.send(200, “text/html”, webPage);
    digitalWrite(gpio2Pin, LOW);
    delay(1000);
    });
    server.begin();
    Serial.println(“HTTP server started”);
    }

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

    Reply
  3. Hi Rui I have uploaded the code on the esp8266 but when i open the serial monitor nothing happens of course after remove GPIO-0 from ground to Vcc. for the reset part I just removed power from it.

    Reply
  4. Hi Rui, although I am away from my normal work area, I finally have a chance to work again on 8266 projects. It’s been a while, and I’m using my laptop instead of the desktop I normally use. Knowing you’re inundated with communications, I’ll refresh the past a bit: I was having troubles with several ESP-12 modules. One would not flash, the other was somewhat “cranky”. Today I tried to communicate with either with strange results. I downloaded Esplorer to the laptop, and proceeded. The one I tried to flash would respond to Esplorer only to say a connection was made and the OS could not be identified because the proper answer was not received. That is exactly where I had left it several months ago. So I had one with nodeMcu firmware on it, and decided to experiment with it just to connect to the router at this location using a previous script I had loaded as an init.lua script months ago but the ssid, and password needed updated for this router. I changed those in the script and tried to upload it. In the process, I got numerous errors, unrelated to the changes I’d made. Thinking that there may have been updates to Esplorer, or java I then downloaded the latest of both. Now Esplorer won’t even open. When I try to execute the .jar file, nothing happens, except for perhaps a flicker on the screen.
    I am at a complete loss as to what is going on here, I won’t be able to get back to the desktop for another several weeks to try on that machine. The laptop is running Win7 and the desktop Win10. If you have any insight on this mess I’d sure like to hear it.
    Thanks for your great work!

    Reply
  5. how to install the required libraries for this sketch.
    i get the following error after having the esp8266 board installed in the boards manager:
    fatal error: ESP8266WiFi.h: No such file or directory

    #include
    compilation terminated.
    exit status 1
    Error compiling.

    Reply
  6. can you help me, I didn’t get my IP, and I got this on my serial monitor

    ets Jan 8 2013,rst cause:4, boot mode:(3,6)

    wdt reset
    load 0x4010f000, len 1264, room 16
    tail 0
    chksum 0x42
    csum 0x42
    ~ld

    Reply
  7. I did this project back when you used nodeMcu/lua. I’m wondering why you went to the arduino IDE, and I’m wondering if you have as many problems using Esplorer as I do……..

    Reply
  8. Hi Rui, I did your similar project a few months back using nodeMcu/lua with success. Now I’ve tried to do this one using the Arduino IDE and run into several issues. I first tried to upload the “blink” to verify that things would go well. Instead I find that the blue LED on the ESP07 I’m using turns on constantly. The led on the CH340 converter I’m using also goes on constantly. If my analogy is correct that would indicate a high placed on the TX lead of the module. I don’t see any “blink activity on any of the GPIO pins. This causes many questions in my mind. Since the module was originally flashed with nodeMcu, I am assuming that was removed, since we place GPIO0 at ground as if to “flash”. Is that correct? Second question is; Are the GPIO pins labeled straight or are they mapped like nodeMcu. And of course last; Why does “blink” not work? I am at this point because I wanted to make the presentation on the page a bit more elaborate, like colors for the buttons, add some buttons and spacing, but trying to upload the HTML code within a string would not work. I had it working on a module in the past, but something happened since then and I get interpreter errors when trying to upload the lua program via ESPlorer. Some seem to like the Arduino IDE better, and I thought I’d try it. Unfortunately without much luck so far. Can you offer any help?

    Reply
    • To add to the last comment…
      So, I’ve set up IDE Ver. 1.6.8 set the board to generic 8266. Nothing would upload, went to a tutorial that had me set gpio 0 low (as if to flash,(question on that later), and upload “blink” with pin modified to 0. It seemed to upload, but the only thing that happened was the blue led on the module that indicates serial traffic came on solid. I checked all GPIO’s for voltage changes and saw none. Where/what should blink? Do I have to remove nodeMcu from the module? Do I need to configure the 8266 with a bootloader, similar to the arduino? Do you always have to go into “flash” mode to upload? and next Are the GPIO pin numbers straight forward or mapped like nodeMcu? This gives credence to my fears of “changing horses in the middle of the stream”. I’d like to work within the Arduino ide, but I know less now than I did before 😆 😕

      May I continue to present my experiences in hopes that someone can provide explanations to the bazaar results I’ve experienced, and perhaps lend a bit of understanding to anyone who has had similar experiences. Forgive me if I get a bit more in depth but I want to present as much information as I can with my limited experience with this module. So…..

      After further investigation I found that the blue LED refered to above was actually NOT in a total “on” state, but instead was actually sending continuous garble from the module. At this point I decided to reflash it with nodeMcu in an effort to restore operation. I configured it to flash mode, opened the nodeMcu flasher, and it happily sent blocks of data with the obligatory “acks” returned, to the point of a successful completion indication. Then opened Esplorer set for 9600 baud (native for nodeMcu) and connection was never established. It just continuously retried. Next I set the baud rate at 74800 and reset again. This time information was returned relating to “room, tail”, etc (which I have yet to learn the meaning of). But still a non-working system. I then set the baud at 115200, and got a string of garble, but at the end the words “mem test failed!” Next I attempted to see if I had issues with breadboard continuity; a suspicion I had from earlier attempts to flash these modules, by inserting another module in the same location as the one being described here. It worked fine. (I did not try to use it with Arduino IDE as I didn’t want to brick another one)

      Next in an effort to recover this thing from “brick” mode, I attempted to use yet another flasher at my disposal; Electrodragon’s At command flasher; and IT FLASHED..successfully…with AT commands available through Esplorer.
      So I still have the question What is happening within when this thing is flashed with the various firmwares? I will attempt to upload other example sketches for varification, then my next step will be to now try to flash nodeMcu again with the impression that something, a vector table perhaps, gets overwritten during one of the processes. Any insight into this mystery (to me) would be greatly appreciated.

      Reply
  9. hi, I have successfully uploaded the Arduino code. Now my problem is that my arduino serial monitor showing my IP ADDRESS is 192.168.1.35.
    But when I enter the IP ADDRESS in browser, it’s saying it can’t connect to the website.

    plsss help me

    Reply
  10. Hi Rui,

    thanks for your good job :o)
    It works great at boards using E12 modules like NodeMCU and WeMos D1. I have also an E13 mounted board (ESPDuino) and it does not work. There is no connetion to the network. The same board works fine with your humidity sketch. Any ideas why E13 isn’t supported?

    Regards
    Reiner

    Reply
  11. Fala Rui, tudo bem?

    Seu trabalho é muito bom, sempre que posso acompanho, parabéns!

    Gostaria de trabalhar com o ESP no modo AP (Access Point). Gostaria de saber quais alterações seriam necessárias no programa para que isso fosse possível.

    Abraço! Obrigado!

    Reply
  12. Hi Rui, I’ve contacted you several times about this project and some issues you’ve helped me with. I have been going back and forth between the Arduino IDE and NodeMCU on different projects, for several reasons. I find that if I go one way and something doesn’t work, and I try the other I find a solution. For example, (I think I mentioned it to you before) using this sketch with the Arduino IDE I expanded on it to create an under cabinet puck light controller for 5 lights. I worked on another project using nodeMCU/lua, and found things had changed so much I was lost. I then came back to this project and Arduino IDE to get something going and in the process updated the IDE to 1.6.8, then 1.8.0. I could not get this sketch to work. Some of the other symptom were that some of the libraries included were bolded (ESP8266WebServer.h)text and others ( ESP8266WiFi and WiFiClient) faded, as if not available. I don’t know what that indicates or how to correct it. I also found that when I uploaded this to the 8266 GPIO0 went permanently low. Needless to say the sketch wouldn’t run. I could overwrite the sketch with a simple example like blink and it was ok.
    I feel like I’m going backwards and not forward. Can you offer any help?

    Reply
  13. Hi Rui, if I use an esp8266 esp-07,which has more gpios, can I make some minor adjustments and put 3 instead of 2, like your programme has?

    Reply
  14. Hi Rui, the mystery is solved. After posing the issue on the “Everything 8266” forum I very quickly got a response that the issue was not the version of the IDE but the version of the board manager (within the IDE) I installed the latest for the 8266 when I updated to IDE 1.8.0, and had forgotten about that part. I rolled back the 8266 board manager to 2.0 and everything worked fine. Just thought you’d like to pass that on to any others that have issues. Cheers

    Reply
      • Thanks for reply . i meant by the previous question is – i want to make an AP which will not to be connected with any router or an existing n/w.
        i want the esp as an AP.
        u have already an example using lua “https://randomnerdtutorials.com/esp8266-web-server/ “,
        why not with arduino!!

        Reply
  15. Nice job you did here with the ESP8266.
    I only have 1 question and that is: powersupply is 3.3 volt but the GPI0 ports give 2.2 max when (for example) Socket#1 = on. How is this possible?
    Wondering if it normal or …
    Thanks anyway for the nice example.

    Reply
  16. Nice work…. But i have an error after uploading…

    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

    Reply
  17. Hi Rui, thanks for your tutorial! 🙂 I miss a status view for any socket, is the Socket 1 ON or OFF.
    webPage += “Status Socket1:ON”;

    Thanks for help :-*

    Reply
  18. Rui, I’ve been playing with this for over a year. I modified a project of yours a while back to read a dht21 sensor and post to my phone and it worked great. It used the ESP82266 library and the WiFiServer library. This one is using the WiFiClient, ESP8266WebServer, and ESP8266mDNS libraries. It worked as is but I am a fan of setting a static ip and could do so with the older sketch using:
    WiFi.begin(ssid, password);
    // NETWORK: Static IP details…
    WiFi.mode(WIFI_STA); // Set module to station mode.\
    // config static IP
    IPAddress ip(192, 168, 1, 199); // where xx is the desired IP Address
    IPAddress gateway(192, 168, 1, 1); // set gateway to match your network
    IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network

    WiFi.config(ip, gateway, subnet);
    This worked fine and connected to the router almost immediately.
    But when I add those lines to this sketch to implement station mode with a static IP, it never connects to the router. Any thoughts on this? Thanks for any guidance.

    Reply
  19. Hello Rui,

    great work, this is exactly what i am looking for.
    It will help me to get my project done.

    I have one question.
    Could you explain me the following code?
    Why do you do that?

    String currentLine = “”; // make a String to hold incoming data from the client
    while (client.connected()) { // loop while the client’s connected
    if (client.available()) { // if there’s bytes to read from the client,
    char c = client.read(); // read a byte, then
    Serial.write(c); // print it out the serial monitor
    header += c;
    if (c == ‘\n’) { // if the byte is a newline character
    // if the current line is blank, you got two newline characters in a row.
    // that’s the end of the client HTTP request, so send a response:
    if (currentLine.length() == 0) {
    // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
    // and a content-type so the client knows what’s coming, then a blank line:
    client.println(“HTTP/1.1 200 OK”);
    client.println(“Content-type:text/html”);
    client.println(“Connection: close”);
    client.println();

    Thank you very much!

    Reply
    • Hi David.
      That piece of code basically reads the http request from the client (your browser).
      We are always saving the incoming data in the header variable with:
      char c = client.read()
      header += c;
      The if statements that follow are used to find the end of the http request.
      You know that the http request has ended when you receive two newlines in a row.
      I hope this helps.
      Regards,
      Sara

      Reply
  20. Hi, how are you?
    you can add to be able to see the temperature with the sensor DS18B20, and be able to see the current time with the sensor ds3132. please … I hope you can help me.
    thanks friend.

    Reply
  21. Hello Rui Santos, I realized this project of Arduino Mega + WiFi R3 ATmega2560 + ESP8266 (32Mb memory), USB-TTL CH340G. LEDs do not respond. The DIP switch is: OFF OFF OFF OFF ON ON OFF OFF. The web server is working. I tried other combinations of the DIP switch – it does not work. What could be the problem?

    Reply
    • Hi Donn,
      Make sure you’ve added your SSID and password. Also double-check that the credentials are correct and that your ESP is fairly close to your router, so it can establish a Wi-Fi connection.

      Reply
  22. Dear,
    I’m trying to make a controller for my garage door, based on your tutorial. My sketch is working when I only use the software buttons on the website.
    I also need local hardware buttons to open and close the garage door, but when I include the in the sketch, everything blocks. Please find my actual sketch below. How do I have to include the hardware buttons ?

    Many thanks for your help.

    /*********
    Rui Santos
    Complete project details at https://randomnerdtutorials.com
    *********/

    // Load Wi-Fi library
    #include

    // Replace with your network credentials
    const char* ssid = “xxxxxxxx”;
    const char* password = “yyyyyyyy”;

    // Set web server port number to 80
    WiFiServer server(80);

    // Variable to store the HTTP request
    String header;

    // Auxiliar variables to store the current output state
    String output5State = “off”;
    String output4State = “off”;

    // Assign output variables to GPIO pins
    const int output5 = 5;
    const int output4 = 4;
    int Ocm =0;// push button open garage door
    int Ccm =0;// push button close garage door

    void setup() {
    Serial.begin(115200);
    // Initialize the output variables as outputs
    pinMode(output5, OUTPUT);
    pinMode(output4, OUTPUT);
    pinMode(3, INPUT); // Open Command from pushbutton
    pinMode(2, INPUT); // Close Command from pushbutton
    // Set outputs to LOW
    digitalWrite(output5, LOW);
    digitalWrite(output4, LOW);

    // Connect to Wi-Fi network with SSID and password
    Serial.print(“Connecting to “);
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    }
    // Print local IP address and start web server
    Serial.println(“”);
    Serial.println(“WiFi connected.”);
    Serial.println(“IP address: “);
    Serial.println(WiFi.localIP());
    server.begin();
    }

    void loop(){
    WiFiClient client = server.available(); // Listen for incoming clients

    if (client) { // If a new client connects,
    Serial.println(“New Client.”); // print a message out in the serial port
    String currentLine = “”; // make a String to hold incoming data from the client
    while (client.connected()) { // loop while the client’s connected
    if (client.available()) { // if there’s bytes to read from the client,
    char c = client.read(); // read a byte, then
    Serial.write(c); // print it out the serial monitor
    header += c;
    if (c == ‘\n’) { // if the byte is a newline character
    // if the current line is blank, you got two newline characters in a row.
    // that’s the end of the client HTTP request, so send a response:
    if (currentLine.length() == 0) {
    // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
    // and a content-type so the client knows what’s coming, then a blank line:
    client.println(“HTTP/1.1 200 OK”);
    client.println(“Content-type:text/html”);
    client.println(“Connection: close”);
    client.println();

    // turns the GPIOs on and off
    // Serial.println (digitalRead(3));
    // Serial.println (digitalRead(2));

    Ocm= digitalRead(3);
    Ccm= digitalRead(2);
    if (header.indexOf(“GET /5/on”) >= 0 || Ocm==1 ) {
    Serial.println(“GPIO 5 on”);
    output5State = “openen”;
    digitalWrite(output4, LOW);
    digitalWrite(output5, HIGH);
    }

    else if (header.indexOf(“GET /4/on”) >= 0 || Ccm ==1) {
    // Serial.println(“GPIO 4 on”);
    // output4State = “on”;
    digitalWrite(output4, HIGH);
    Serial.println(“GPIO 5 off”);
    output5State = “sluiten”;
    digitalWrite(output5, LOW);
    digitalWrite(output4, HIGH);

    }

    // Display the HTML web page
    client.println(“”);
    client.println(“”);
    client.println(“”);
    // CSS to style the on/off buttons
    // Feel free to change the background-color and font-size attributes to fit your preferences
    client.println(“html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}”);
    client.println(“.button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;”);
    client.println(“text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}”);
    client.println(“.button2 {background-color: #77878A;}”);

    // Web Page Heading
    client.println(“POORT”);

    // Display current state, and ON/OFF buttons for GPIO 5
    client.println(“GPIO 5 – State ” + output5State + “”);
    // If the output5State is off, it displays the ON button
    // if (output5State==”off”) {
    // client.println(“ON“);
    //} else {
    // client.println(“OFF“);
    //}
    client.println(“OPEN“);

    // Display current state, and ON/OFF buttons for GPIO 4
    // client.println(“GPIO 4 – State ” + output4State + “”);
    // If the output4State is off, it displays the ON button
    // if (output4State==”off”) {
    // client.println(“ON“);
    //} else {
    // client.println(“OFF“);
    // }
    client.println(“TOE“);

    client.println(“”);

    // The HTTP response ends with another blank line
    client.println();
    // Break out of the while loop
    break;
    } else { // if you got a newline, then clear currentLine
    currentLine = “”;
    }
    } else if (c != ‘\r’) { // if you got anything else but a carriage return character,
    currentLine += c; // add it to the end of the currentLine
    }
    }
    }
    // Clear the header variable
    header = “”;
    // Close the connection
    client.stop();
    Serial.println(“Client disconnected.”);
    Serial.println(“”);
    }
    }

    Reply
    • Hi.
      I haven’t tried that specific project.
      But I suggest that you use interrupts to detect when the hardware buttons were pressed and change its state on the interrupt handling function.
      As I said, I haven’t tried it. It’s just a suggestion that I think would work.
      I hope it helps.
      Regards,
      Sara 🙂

      Reply
  23. Hi All,
    I am getting data in chunks with 3 second from my device. I need to send that data to my web server. Example:
    12 KB… then 1 sec wait.. then 12 KB data.. It’s sending 2 separate files in this request, instead of maintaining connection and having 24 KB of file on web server.

    I am using httpclient for this and tried passing content-length as well. But doesn’t work.

    Please guide / help / support.

    Reply
    • Hi Prateek.
      Unfortunately, I’ve never tried what you’re describing. So I don’t know what might be wrong.
      Sorry that I can’t help.
      Regards,
      Sara 🙂

      Reply
  24. great tutorial. worked from scratch in less than 30mins for noob. thumbs up. i tried 8266 for several days and hazzled with missing characters in IDE and tutorials. BUT NOT here!

    Reply
  25. I couldnot get my ip from serial moniter .It keep on showing dots(……) and I used baudrate 115200.Will be gratefull for your reply

    Reply
    • Hi Ali.

      That usually happens when people forget to insert their network credentials or don’t insert the credentials properly.
      Please make sure that you’ve inserted your network credentials and double-check that they’re correct.
      Also, make sure that the ESP is relatively close to your router so that it is able to catch Wi-Fi signal.

      Regards,
      Sara

      Reply
  26. Sara
    thanks for sharing this nice project. I have few questions:
    1. There is a way to secure the access to the device with login?
    2. There is a way to access the device with URL rather than IP address?

    PS: I managed to modify the HTML code so it will be friendly and dynamically adjust the application size on the connected devices screen sizes, iPad, iPhone with different sizes. Also considering the phone rotation. If interested I can share the code (where should I place it?).

    David

    Reply
  27. Hai Rui
    In the sketch, I have added Serial.println(“”); but still there is garbage before it prints …. on the serial monitor. Can you tell the command?

    Reply
    • Hi.
      Getting some garbage at first, is normal with the ESP8266.
      After that initial garbage, it should print adequately to the serial montior.
      Also, make sure that you have the right baud rate selected.
      Regards,
      Sara

      Reply
      • Thank you Sara for your prompt reply.
        Of course! after the garbage useful data is coming on serial port.
        The garbage comes whenever the Reset button is pressed followed by useful data.
        I have set the correct baud rate and all….
        The garbage doesn’t appear after programming the IC through USB port in which it finally says
        hard reset using CTS. Please clarify
        Regards

        Reply

Leave a Reply to Geoff Cancel reply

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.