Build an ESP8266 Web Server – Code and Schematics (NodeMCU)

This tutorial is a step-by-step guide that shows how to build a standalone ESP8266 Web Server that controls two outputs (two LEDs). This ESP8266 NodeMCU Web Server is mobile responsive and it can be accessed with any device with a browser in your local network.

Build an ESP8266 Web Server - Code and Schematics (NodeMCU)

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

This tutorial covers two different methods to build the web server:

  • Part 1: Create a Web Server Using Arduino IDE
  • Part 2: Create a Web Server Using NodeMCU Firmware

PART 1: CREATE A WEB SERVER USING ARDUINO IDE

This part shows you how to create a web server to control two outputs using Arduino IDE. You can use this method to create a different web server to fulfill your needs.

This tutorial is available in video format (watch below) and in written format (continue reading this page).

Prepare the Arduino IDE

1. Download and install the Arduino IDE on your operating system (some older versions won’t work).

2. Then, you need to install the ESP8266 add-on for the Arduino IDE. For that, go to File > Preferences.

3. Enter http://arduino.esp8266.com/stable/package_esp8266com_index.json into the “Additional Board Manager URLs” field as shown in the figure below. Then, click the “OK” button.

Install ESP8266 Boards Arduino IDE Additional Boards Manager URLs

4. Go to Tools > Board > Boards Manager

Install ESP8266 Boards Arduino IDE Boards Manager

5. Scroll down, select the ESP8266 board menu and install “esp8266 by ESP8266 Community”, as shown in the figure below.

Install ESP8266 Boards Arduino IDE

6. Go to ToolsBoard and choose your ESP8266 board. Then, re-open your Arduino IDE.

Code

Copy the following code to your Arduino IDE, but don’t upload it yet. You need to make some changes to make it work for you.

/*********
  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

You need to modify the following two variables with your network credentials, so that your ESP8266 can establish a connection with your router.

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

Uploading the Sketch

Uploading the Sketch to the ESP-12E

If you’re using an ESP-12E NodeMCU Kit, uploading the sketch is very simple, since it has built-in programmer. Plug your board to your computer. Make sure you have the right board and COM port selected.

Then, click the Upload button in the Arduino IDE and wait a few seconds until you see the message “Done uploading.” in the bottom left corner.

Upload Web Server Code Sketch Arduino IDE ESP8266 NodeMCU

Uploading Sketch to the ESP-01

Uploading code to the ESP-01 requires establishing a serial communication between your ESP8266 and a FTDI Programmer as shown in the schematic diagram below.

ESP8266 ESP-01 FTDI Programmer Flashing Firmware Circuit

Note: alternatively, you can use a ESP8266-01 Serial Adapter, which is easier to use and less error-prone.

The following table shows the connections you need to make between the ESP8266 and the FTDI programmer.

ESP8266FTDI programmer
RXTX
TX RX
CH_PD3.3V
GPIO 0GND
VCC3.3V
GND GND

If you have a brand new FTDI Programmer, you’ll probably need to install the FTDI drivers on your Windows PC. Visit this website for the official drivers. (If the COM port is grayed out in your Arduino IDE, it is probably because you don’t have the drivers installed).

Then, you just need to connect the FTDI programmer to your computer, and upload the code to the ESP8266.

Schematics

To build the circuit for this tutorial you need the following parts:

Parts required:

If you’re using ESP-01, you also need an FTDI programmer or a Serial Adapter.

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!

Connect two LEDs to your ESP8266 as shown in the following schematic diagram – with one LED connected to GPIO 4 (D2), and another to GPIO 5 (D1).

ESP8266 NodeMCU Schematic Control LEDs Web Server

If you are using ESP-01…

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-01 Schematic Control LEDs Web Server

Testing the Web Server

Now, you can upload the code, and it will work straight away. Don’t forget to check if you have the right board and COM port selected, otherwise you’ll get an error when trying to upload. Open the Serial Monitor at a baud rate of 115200.

Finding the ESP IP Address

Press the ESP8266 RESET button, and it will output the ESP IP address on the Serial Monitor

ESP8266 NodeMCU Web Server LED Control GPIOs Arduino IDE IP Address Serial Monitor

Copy that IP address, because you need it to access the web server.

Accessing the Web Server

Open your browser, type the ESP IP address, and you’ll see the following page. This page is sent by the ESP8266 when you make a request on the ESP IP address.

ESP8266 NodeMCU Web Server LED Control GPIOs Arduino IDE

If take a look at the serial monitor, you can see what’s going on on the background. The ESP receives an HTTP request from a new client – in this case, your browser.

You can also see other information about the HTTP request – these fields are called HTTP header fields, and they define the operating parameters of an HTTP transaction.

ESP8266 NodeMCU Web Server LED Control GPIOs Serial Monitor Arduino IDE IP Address

Testing the Web Server

Let’s test the web server. Click the button to turn GPIO 5 ON. The ESP receives a request on the /5/on URL, and turns LED 5 ON.

ESP8266 NodeMCU Web Server LED Control GPIOs Serial Monitor Arduino IDE

The LED state is also updated on the web page.

ESP8266 NodeMCU Web Server LED Control GPIOs

Test GPIO 4 button and check that it works in a similar way.

How the Code Works

Now, let’s take a closer look at the code to see how it works, so that you are able to modify it to fulfill your needs.

The first thing you need to do is to include the ESP8266WiFi library.

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

As mentioned previously, you need to insert your ssid and password in the following lines inside the double quotes.

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

Then, you set your web server to port 80.

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

The following line creates a variable to store the header of the HTTP request:

String header;

Next, you create auxiliar variables to store the current state of your outputs. If you want to add more outputs and save its state, you need to create more variables.

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

You also need to assign a GPIO to each of your outputs. Here we are using GPIO 4 and GPIO 5. You can use any other suitable GPIOs.

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

setup()

Now, let’s go into the setup(). The setup() function only runs once when your ESP first boots. First, we start a serial communication at a baud rate of 115200 for debugging purposes.

Serial.begin(115200);

You also define your GPIOs as OUTPUTs and set them to LOW.

// Initialize the output variables as outputs
pinMode(output5, OUTPUT);
pinMode(output4, OUTPUT);
// Set outputs to LOW
digitalWrite(output5, LOW);
digitalWrite(output4, LOW);

The following lines begin the Wi-Fi connection with WiFi.begin(ssid, password), wait for a successful connection and prints the ESP IP address in the Serial Monitor.

// 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();

loop()

In the loop() we program what happens when a new client establishes a connection with the web server.

The ESP is always listening for incoming clients with this line:

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

When a request is received from a client, we’ll save the incoming data. The while loop that follows will be running as long as the client stays connected. We don’t recommend changing the following part of the code unless you know exactly what you are doing.

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();

The next section of if and else statements checks which button was pressed in your web page, and controls the outputs accordingly. As we’ve seen previously, we make a request on different URLs depending on the button we press.

// 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);
}

For example, if you’ve pressed the GPIO 5 ON button, the URL changes to the ESP IP address followed by /5/ON, and we receive that information on the HTTP header. So, we can check if the header contains the expression GET /5/on.

If it contains, the code prints a message on the serial monitor, changes the output5State variable to on, and turns the LED on.

This works similarly for the other buttons. So, if you want to add more outputs, you should modify this part of the code to include them.

Displaying the HTML Web Page

The next thing you need to do, is generate the web page. The ESP8266 will be sending a response to your browser with some HTML text to display the web page.

The web page is sent to the client using the client.println() function. You should enter what you want to send to the client as an argument.

The first text you should always send is the following line, that indicates that we’re sending HTML.

<!DOCTYPE html><html>

Then, the following line makes the web page responsive in any web browser.

client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");

The next one is used to prevent requests related to the favicon – You don’t need to worry about this line.

client.println("<link rel=\"icon\" href=\"data:,\">");

Styling the Web Page

Next, we have some CSS to style the buttons and the web page appearance. We choose the Helvetica font, define the content to be displayed as a block and aligned at the center.

client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");

We style our buttons with the some properties to define color, size, border, etc…

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;}");

Then, we define the style for a second button, with all the properties of the button we’ve defined earlier, but with a different color. This will be the style for the off button.

client.println(".button2 {background-color: #77878A;}</style></head>");

Setting the Web Page First Heading

In the next line you set the first heading of your web page, you can change this text to whatever you like.

// Web Page Title
client.println("<h1>ESP8266 Web Server</h1>");

Displaying the Buttons and Corresponding State

Then, you write a paragraph to display the GPIO 5 current state. As you can see we use the output5State variable, so that the state updates instantly when this variable changes.

client.println("<p>GPIO 5 - State " + output5State + "</p>");

Then, we display the on or the off button, depending on the current state of the GPIO.

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>");
}

We use the same procedure for GPIO 4.

Closing the Connection

Finally, when the response ends, we clear the header variable, and stop the connection with the client with client.stop().

// Clear the header variable
header = "";
// Close the connection
client.stop();

Taking it Further

Now that you know how the code works, you can modify the code to add more outputs, or modify your web page. To modify your web page you may need to know some HTML and CSS.

Instead of controlling two LEDs, you can control a relay to control practically any electronics appliances.

To build a web server to display sensor readings, you can read the following tutorials:

Alternatively, if you want to program your ESP8266 using MicroPython, you can read this tutorial: ESP32/ESP8266 MicroPython Web Server – Control Outputs

If you like ESP8266 make sure you take a look at our course about Home Automation with the ESP8266.

PART 2: CREATE A WEB SERVER USING NODEMCU FIRMWARE

This part shows you how to create a web server to control two outputs using NodeMCU firmware and LUA programming language. You can use this method to create a different web server to fulfill your needs.

ESP8266 Create a Web Server Using NodeMCU Firmware

First, watch the video demonstration below

Why flashing your ESP8266 module with NodeMCU?

NodeMCU is a firmware that allows you to program the ESP8266 modules with LUA script. Programming the ESP8266 with LUA using the NodeMCU firmware is very similar to the way you program your Arduino. With just a few lines of code you can establish a WiFi connection, control the ESP8266 GPIOs, turning your ESP8266 into a web server and a lot more.

Downloading NodeMCU Flasher for Windows

After wiring your circuit, you have to download the NodeMCU flasher. It’s a .exe file that you can download using one of the following links:

You can click here to find all the information about NodeMCU flasher.

Flashing your ESP8266

If you’re using an ESP8266-12 you just need to plug the ESP into your computer. If you’re using an ESP-01, you need an FTDI programmer to connect it to your computer. To establish a serial communication between your ESP8266 and a FTDI Programmer as shown in the schematic diagram below.

ESP8266 ESP-01 FTDI Programmer Flashing Firmware Circuit

Open the flasher that you just downloaded and a window should appear (as shown in the following figure).

ESP8266 NodeMCU Flasher Software

Press the button “Flash” and it should start the flashing process immediately (You might have to change some of the settings on the Advanced tab). After finishing this process, it should appear a green circle with a check icon.

Schematics

To build the circuit you need the following parts:

Parts required:

If you’re using ESP-01, you also need an FTDI programmer.

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!

If your using ESP-01…

If you’re using the ESP8266-01, use the following schematic diagram as a reference.

ESP-01 Schematic Control LEDs Web Server

Uploading the Code

I recommend using the ESPlorer program created by 4refr0nt to create and save LUA files into your ESP8266. Follow these instructions to download and install ESPlorer:

  1. Click here to download ESPlorer
  2. Unzip that folder
  3. Go to the dist folder (here’s the path: ESPlorer-master\ESPlorer\dist)
  4. Run ESPlorer.jar. It’s a JAVA program, so you need JAVA installed on your computer.
  5. Open the ESPlorer
ESPlorer ESP8266 NodeMCU Getting Started

You should see a window similar to the preceding Figure, follow these instructions to upload a LUA file:

  1. Connect your FTDI programmer to your computer
  2. Select your FTDI programmer port
  3. Press Open/Close
  4. Select NodeMCU+MicroPtyhon tab
  5. Create a new file called init.lua
  6. Press Save to ESP

Everything that you need to worry about or change is highlighted in red box.

ESPlorer Upload code to ESP8266 NodeMCU Board

Code

Upload the following code into your ESP8266 using the preceding software. Your file should be named “init.lua“. You can click here to download the file.

wifi.setmode(wifi.STATION)
wifi.sta.config("YOUR_NETWORK_NAME","YOUR_NETWORK_PASSWORD")
print(wifi.sta.getip())
led1 = 3
led2 = 4
gpio.mode(led1, gpio.OUTPUT)
gpio.mode(led2, gpio.OUTPUT)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive", function(client,request)
        local buf = "";
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
        if(method == nil)then
            _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
        end
        local _GET = {}
        if (vars ~= nil)then
            for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
                _GET[k] = v
            end
        end
        buf = buf.."<h1> ESP8266 Web Server</h1>";
        buf = buf.."<p>GPIO0 <a href=\"?pin=ON1\"><button>ON</button></a>&nbsp;<a href=\"?pin=OFF1\"><button>OFF</button></a></p>";
        buf = buf.."<p>GPIO2 <a href=\"?pin=ON2\"><button>ON</button></a>&nbsp;<a href=\"?pin=OFF2\"><button>OFF</button></a></p>";
        local _on,_off = "",""
        if(_GET.pin == "ON1")then
              gpio.write(led1, gpio.HIGH);
        elseif(_GET.pin == "OFF1")then
              gpio.write(led1, gpio.LOW);
        elseif(_GET.pin == "ON2")then
              gpio.write(led2, gpio.HIGH);
        elseif(_GET.pin == "OFF2")then
              gpio.write(led2, gpio.LOW);
        end
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)

View raw code

Don’t forget to replace your WiFi Station details in that code above (Network Name and Password).

Accessing your web server

When your ESP8266 restarts it prints in your serial monitor the IP address of your ESP8266. If you type your ESP8266 IP address in your web browser, you can access your web server.

ESP8266 NodeMCU Web Server Control Outputs LEDs

Our Most Popular ESP8266 Projects

If you like the ESP8266, you may also like:

Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.

Updated August 6, 2019



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 »

Enjoyed this project? Stay updated by subscribing our newsletter!

561 thoughts on “Build an ESP8266 Web Server – Code and Schematics (NodeMCU)”

      • Holy moly… So everything is hooked up to the FTDI properly, then I plug the usb into computer and click flash….. nothing. Unplug USB, plug in again and try again… nothing.. I repeat this 5 times and on the 5th time it programs! Either these things suck or my FTDI is crap lol.

        Reply
      • Hi,Mr.Ru santos,

        I followed your webpage (https://randomnerdtutorials.com/esp8266-web-server/) instructions to flash esp8266 01 module successfully,when I opened downloaded init.lua file with ESPlorer and change to ssid and password of my router,set up 9600 bautrate, then I clicked “save to ESP” button,wait for a while,I got that message “waiting answer from ESP – timeout reached,send abort.” by the way, I connected esp8266
        to ch340 usb – ttl converter as your picture above.

        after that,I do a test. I removed the wire connected GPIO 0 to GND,
        and clicked “save to ESP” again, I got this message as following,
        PORT OPEN 9600
        FILE=”init.lua” file.remove(FILE) file.open(FILE,”w+”) uart.setup(0,9600,8,0,1,0)
        > >> > > > > > > >
        –Done–
        >
        >
        > dofile(“init.lua”)
        nil
        init.lua:8: only one tcp server allowed
        >
        please tell me
        1. can I removed the wire connected GPIO 0 TO GND?
        2. if I can’t remove the wire connected GPIO 0 TO GND,
        why can’t I save it to ESP successfully?
        If you could tell me,I will be appreciated.
        Thank you.

        Reply
      • iam sorry bt i want ask if i use the arduino uno with esp8266 what is the type of the firmware that i have to upload to the nodemcu flasher , iknow that when i use the arduino i have to type some ATcommand in the serial page to get the ip my question now when i get the ip by this way and type it in the html location this webpage will apear or not

        Reply
        • Hi,
          If you want to use the Arduino IDE to program your ESP, you don’t need to flash your ESP with NodeMCU.
          Here’s how to use the ESP with Arduino IDE: https://randomnerdtutorials.com/how-to-install-esp8266-board-arduino-ide/
          Here’s how to flash the ESP with its default AT firmware: https://randomnerdtutorials.com/esp8266
          How to flash the ESP with NodeMCU firmware: https://randomnerdtutorials.com/flashing-nodemcu-firmware-on-the-esp8266-using-windows/

          Reply
          • thank you RUI very much for reply to my message ,but iam not use the ftdi iam using the arduino uno with its arduino ide 1.6.7
            and iam already uploaded that code to the arduino
            #include

            #define DEBUG true

            SoftwareSerial esp8266(10,11); // make RX Arduino line is pin 10, make TX Arduino line is pin 11.
            // This means that you need to connect the TX line from the esp to the Arduino’s pin 10
            // and the RX line from the esp to the Arduino’s pin 11
            void setup()
            {
            Serial.begin(115200);
            esp8266.begin(115200); // your esp’s baud rate might be different

            pinMode(2,OUTPUT);
            digitalWrite(2,LOW);

            pinMode(3,OUTPUT);
            digitalWrite(3,LOW);

            pinMode(4,OUTPUT);
            digitalWrite(4,LOW);

            sendData(“AT+RST\r\n”,2000,DEBUG); // reset module
            sendData(“AT+CWMODE=2\r\n”,1000,DEBUG); // configure as access point

            delay(10000);
            sendData(“AT+CIFSR\r\n”,1000,DEBUG); // get ip address
            sendData(“AT+CIPMUX=1\r\n”,1000,DEBUG); // configure for multiple connections
            sendData(“AT+CIPSERVER=1,80\r\n”,1000,DEBUG); // turn on server on port 80
            }

            void loop()
            {
            if(esp8266.available()) // check if the esp is sending a message
            {

            if(esp8266.find(“+IPD,”))
            {
            Serial.println(“listening”);
            delay(1000); // wait for the serial buffer to fill up (read all the serial data)
            // get the connection id so that we can then disconnect
            int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
            // the ASCII decimal value and 0 (the first decimal number) starts at 48

            esp8266.find(“pin=”); // advance cursor to “pin=”

            int pinNumber = (esp8266.read()-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
            pinNumber += (esp8266.read()-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

            digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

            // make close command
            String closeCommand = “AT+CIPCLOSE=”;
            closeCommand+=connectionId; // append connection id
            closeCommand+=”\r\n”;

            sendData(closeCommand,1000,DEBUG); // close connection
            }
            }
            }

            /*
            * Name: sendData
            * Description: Function used to send data to ESP8266.
            * Params: command – the data/command to send; timeout – the time to wait for a response; debug – print to Serial window?(true = yes, false = no)
            * Returns: The response from the esp8266 (if there is a reponse)
            */
            String sendData(String command, const int timeout, boolean debug)
            {
            String response = “”;

            esp8266.print(command); // send the read character to the esp8266

            long int time = millis();

            while( (time+timeout) > millis())
            {
            while(esp8266.available())
            {

            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            response+=c;
            }
            }

            if(debug)
            {
            Serial.print(response);
            }

            return response;
            }

            after that, this is my connection

            tx of the module to pin10
            rx of the module to pin11
            ground to ground
            vcc and ch-pd to 3.3v from the arduino
            when i open the serialpage and open baudrate to 115200 and nl&cr
            its return the ip
            when i connect my pc to the esp network and open the browser and type my ip its return not page found

            what i can do please i need that help because iam student and in final year and i want to do this project

            iam sorry fo asking you many question but you are good man and iam really need help to do that

          • I want suggest to commenters that are posting long codes for they using snippets services such as gist or pastebin.

            Rui, this could be a guideline for the website.

          • Hellow,Rui Santos:

            I’m a new coder, and I can’t realize comment below:

            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:

            commet write two newline characters in a row stands up end of the client HTTP,but your if-loop only one newline character.

      • Hi Rui,
        Nice tutorial but I have tried to get a DS18b20 to work but with your setup I get “-127.00 *C”. I have replaced parts and still get the same results, as you said “quite frustrating”
        Any ideas.

        Reply
        • hi Rui
          iam using the arduino with my esp8266 and iam already connect my esp8266 to my arduino to get toggle pins from the webserver to the arduino , i connected the 3.3 voltage from my arduino
          after i uploaded the code to the arduino and connected VCC and GH-PD to 3.3 voltage from my arduino
          and open the serial page at 115200 baud rate its return the ip adress like that 194.164.4 but if i connect to the esp network and open the ip in the html location its type not page found
          what ican do ?
          have i to connect the VCC to the source out the arduino ?
          i neeeeeeeeeed your help
          regards

          Reply
    • Rui,
      I very much enjoyed the oldd PORTWINE, when I was in Villa Gaia.
      My problem ist that in ESPlorer the “Save to ESP” does not work. error……….
      Your help is highly apreciated,
      regards
      Gerry

      Reply
      • Hi Gerry,
        Thank you for your comment! I live very close to “Vila Nova de Gaia”. 🙂
        That error occurs when your ESP is busy doing something else.
        Have you managed to flash your ESP properly? (have you seen the green arrow in the NodeMCU flasher?)
        After flashing the ESP did you remove GPIO 0 from GND and connected to VCC?
        Then restart your ESP and try to save the script to your ESP.
        I hope this helps!
        Rui

        Reply
  1. Very nice demo. For easy breadboarding with ESP-01, you can try this breadboard friendly adapter: tindie.com/products/rajbex/esp8266-breadboard-adapter/

    Reply
      • Hi Rui
        Very good tutorial, good work, keep it up, I know it wouldn’t be as simple to bring up this practical tutorial . I got couple of questions
        1. The above given steps are compatible with esp03?
        2. What are the frustrations you had with esp8266, for me first 3 esp didn’t worked consistently, later the 4th one works fine still not consistent. The major frustration I had is because of improper power supply (esp is hungry for power), other frustration is loop when you boot(data led blinks) with random value sent at serial port And unable to flash…for me the overall experience is quite frustrating. …I have kept all my 7 esp away from my hand in order not to waste time 🙂

        Reply
        • Hi Nazir,
          Thanks for your feedback!
          1 – I haven’t tested this project with the esp03, but it should work just fine… The GPIOs that you need to define in the LUA code are a bit different tough. Here’s the GPIOs assignment:

          IO index ESP8266 pin
          0 [*] GPIO16
          1 GPIO5
          2 GPIO4
          3 GPIO0
          4 GPIO2
          5 GPIO14
          6 GPIO12
          7 GPIO13
          8 GPIO15
          9 GPIO3
          10 GPIO1
          11 GPIO9
          12 GPIO10

          In my web server I have used “GPIO0” which I defined as “led1 = 3” and “GPIO2” as “led2 = 4”

          2 – I’ve never used the ESP8266 esp3. Yes this module can be quite frustrating and most of my frustrations come from using the AT firmware… Which often gives me the error: “busy s..”. I haven’t had any power issues and most of the time I had my module plugged to my laptop. I would encourage you to experiment with the NodeMCU firmware, personally I’ve found it more stable.
          If you need anything else feel free to ask!
          I hope this helps,
          Rui

          Reply
  2. Can this same unit control a relay and take an analog reading and push it back up to another web server?

    Doing a garden watering system that has a web server for data collection on godaddy. Want to query moisture level from this device which send the data back to the godaddy server and then godaddy web server checks logic, if logic is right send another command down to turn a relay on to open a water valve.

    Reply
    • Hi Steve,
      Yes this module can control a 3.3V relay.
      To read an analog reading you might want to grab that data with an Arduino then send that data via serial to your ESP8266 that does a POST/GET http request to your web server to plot the data.

      Here’s a GET http request example:
      conn=net.createConnection(net.TCP, false)
      conn:on(“receive”, function(conn, pl) print(pl) end)
      conn:connect(80,”www.google.com”)
      conn:send(“GET / HTTP/1.1\r\nHost: http://www.google.com\r\n”
      ..”Connection: keep-alive\r\nAccept: */*\r\n\r\n”)

      Reply
  3. Hi RUI
    the web server thing is awesome

    im planning to use these ESP8266 for home automation

    how can i use them for home automation

    Reply
  4. Hi, it seems that data is lost when I unplug and reconnect the power supply and need to reprogram the module. Why is happening and how to save data into the ESP forever?

    Reply
      • The file is uploading, the module is working but after I disconnect and reconnect the power supply it doesn’t work anymore and I must reupload the file. It seems like it’s resetting after power disconnection…

        Reply
        • After saving init.lua file unplug your module.
          Then power your module again and send this line to your ESP8266:

          file.list()

          It should list your init.lua file, If your file was saved properly.
          (Tip open a new file in ESPlorer and click the button on the ESPlorer that says, send current line and only send “file.list()”)

          Reply
    • Are you ‘normalling’ GPIO-01 after programming the ESP8266? (I’ve forgotten to do this upon occasion, causing too much wasted time!)

      Reply
  5. Thanks Rui for this information 🙂
    Have you try the esp8266 on httpd mode (it´s a python web server and you can enter de ssid and password of your wifi )?

    Reply
    • Hi Chris, You’re welcome!
      No, I haven’t… Can you send me a link with information regarding that python web server?
      You can use the ESP8266 as its own standalone web server and make it act as an Access Point if you replace my initial code

      wifi.setmode(wifi.STATION)
      wifi.sta.config(“YOUR_NETWORK_NAME”,”YOUR_NETWORK_PASSWORD”)

      with this:

      wifi.setmode(wifi.SOFTAP);
      wifi.ap.config({ssid=”test”,pwd=”12345678″});

      Reply
      • Hi,
        I Will give you the URL tomorow (i haven ´t my computer), but what i mean, with httpd you can turn your esp on a acces point, directly connecting your computer on esp, the websever Check all wifi conection and you select the right ssid wifi and enter your password in live. After your esp is connecting to your wifi box! (Sorry for my english 😉 )

        Reply
        • Hi again,

          This url spoke about httpd:

          esp8266.com/viewtopic.php?f=6&t=376

          and this one:

          harizanov.com/2014/11/esp8266-powered-web-server-led-control-dht22-temperaturehumidity-sensor-reading/

          I have try it, the web sever fonctionly proprely and you can scan the ssid but when i save the password the esp reboot… may be the power is not enough…i will try with a other esp.

          Reply
          • Hi again, Thank for sharing those resources.
            That seems really odd, it never happened to me, so I’m not sure what’s causing that problem.
            You might want to report that problem or ask on the esp8266 forum…

  6. I tried to add some background color and changed font size to a bit bigger. I am using Lua Uploader to upload to ESP8266. It works OK with background color and font size but didn’t work after saved to the ESP8266. Do you have any ideal? Thanks

    Reply
    • How did you do this ? I’m am also trying to center all text and buttons. How can I use one server and have many esp-01s connected together?

      Reply
    • I know this is an old thread, but i felt a comment was in order incase others have this type of issue. I too had problems working HTML into the string sent out from the 8266. What I seemed to find in the end is that when using the ESPlorer IDE, I get errors when too many HTML attributes are placed in the code. (Almost as if there were a buffer overrun or something. (just speculating)) But! When uploading the code via Arduino IDE (with necessary adjustments to the code to satisfy the Arduino IDE) , it WORKS! I believe therefore there is a bug in the way the string is built, or a limit to it’s length in ESPlorer. I haven’t however used the Lua Uploader.

      Reply
    • Hi Tesla,
      I had this module running for three full days without any problem.
      But some firmwares versions come with bugs that make the web server very unstable… With this particular firmware version I didn’t have any problem yet.
      Thanks for asking,
      Rui

      Reply
  7. Great stuff, thanks for sharing!
    I’d like to do something very similar but a little bit more complicated, I want to the LED’s switches to be momentary on/off rather than toggle on/off. I’m a complete novice at Lua and programming for the web, can you suggest any resources that might help get me pointed in the right direction?

    Reply
      • That would be great but I was thinking a little more generally, I have a little programming experience but have never programmed in Lua or done anything which uses internet or network communications.

        Reply
    • Hi

      Here’s my solution:

      if(_GET.pin == “ON1”)then
      gpio.write(led1, gpio.HIGH);
      print(“Open Door 1”)
      tmr.alarm(1,500, 0, function() print(“Close Door 1”) end) — one shot delay

      Reply
      • Hello, this is what i need vor my Grage door 🙂 can you Tell me where you drop this in the Skript? Or can you send me the Code? Thanks
        Axel

        Reply
  8. Rui, thanks for taking the time to not only present this design but to answer all the questions! May I ask: You are relying on dhcp of the router to assign an IP to this device correct ? Is it possible to assign the module a fixed IP that way the router could route traffic to it easier.

    Reply
    • Hi,
      If you want to assign the module a fixed ip. so it’s easier to do some port forwarding you can set the ESP8266 as an Access Point.
      You can set an ip with this command: wifi.ap.setip()
      Here’s the wiki page on that subject: github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en#wifistasetip

      Reply
  9. Hey Rui,

    Looks good what you published.
    I can’t try it becouse my ESP has gone in smoke and my suplier is out of stock.
    But is looks good and i’m going to try it when i got a new ESP.

    Thanks for helping me out.

    Reply
  10. Hi Rui,

    Thanks for this awesome tutorial.

    I am able to flash the firmware & script its working fine.
    I did some modification in your code and able to use Both Station & AP mode at the same time.

    Now i don’t want to hard code the SSID & PWD for Station mode in code and want to provide a flexibility to set it from the webpage how to modify the html part of the code so that i can pass SSID & PWD from web and then depending upon the data i will call wifi.sta.config() function to connect to my router ???????????

    For configure the Station mode SSID & PWD i will use AP mode, where forAP mode i will hard code the SSID & PWD.

    Reply
  11. Hello Rui, thanks very much for introducing the esp8266 to us. This is a great project, and very enjoyable to use. I was wondering if there is a way to get the html to display on apple devices. I can see it on my desktop computer using google chrome and also on my kindle but it will not load on the apple iphone browser. Any ideas? or maybe i am expecting too much from the code on the esp8266 project? Thanks for your efforts and for your patience in answering all the questions. Mark Z Lowell, Indiana

    Reply
    • It should work just fine Mark.
      Can you test on google Chrome? (instead of Safari)
      I’ve used my iPad to test this project and it works just fine.

      Thanks for trying my project,
      Rui

      Reply
      • Rui,
        Thanks for posting this example. I built this (both AP and STATION modes) and it works great on my desktop browsers, but I also have trouble on an iPhone (both Chrome and Safari), but different results on each browser, as follows:
        Chrome: connects to the AP, but displays raw HTML (not rendering correctly). I’m OK using Chrome only, but is the browser expecting more HTML (e.g., head/body tags, etc.)?
        Safari: does not connect: “Safari cannot open the page because the network connection was lost.”

        Reply
      • I can’t get it to work on my iPhone either. It tells me “Safari cannot open the page because the network connection was lost”. Tried on iPhone 4s, 5s and 6 Plus but no dice.

        However, if I go straight for the URL with the request set, as 192.168.0.1/?pin=ON1 it works, as in the led lights up. Still no page showing up.

        It would be nice to be able to see the actual page though. :O/

        Any ideas?

        Reply
        • I downloaded and installed Chrome on the 4s, and it worked. Seems there is something off with Safari on iPhones then. It would be nice to have a workaround for Safari at least.

          Reply
          • Eh, ok. Things got very weird in Chrome now. All of a sudden it showed me the HTML code instead of the rendered page. I even re-flashed my chip, uploaded my init.lua, uninstalled and reinstalled Chrome (on iPhone), just to be 100 % sure it would be restored to the previous working site, but… still showing code. It still looked the same in “normal” browsers of course.

            I figured that it could have been an issue with Google’s caching of stuff. I added proper doctype, head, title and body tags and closing them as well. Then it worked in Chrome again.

            I tried commenting out the doctype, head, title and body tags again, just for… fun(?). Then it stopped working again. I can’t really draw any conclusions from this. Proper HTML tags and it will show up in Chrome on iPhone, but still no idea on how to make it work on iPhone Safari. *confuzzled*

    • The iPhone wants to receive a http header. Before the line

      client:send(buf);

      you could just add

      client:send("HTTP/1.1 200 OK\r\n");
      client:send("Content-type: text/html\r\n");
      client:send("Connection: close\r\n\r\n");

      Reply
    • It seems to me that some required html tags are missing. Adding them worked for me

      Title of the document

      The content of the document……

      And in the script:
      local buf = “”;
      buf = buf..”HTTP/1.1 200 OK\n\n”
      buf = buf..””
      buf = buf..””
      buf = buf..”Title”
      buf = buf..””
      buf = buf..””
      …..
      buf = buf..”GPIO2 ON OFF“;
      buf = buf..””
      buf = buf..””

      local _on,_off = “”,””

      Reply
      • *%#”
        impossible to paste code in the comment window.
        Read w3schools.com/tags/tag_body.asp
        add tags to the buf in the beginning (after the http/1.1..tag?) and add the required closing tags as the last tags, just before the if,thenif.. in the end.

        Reply
      • Thanks

        I am using the header 1 tag. I wanted to make header 1 bigger. Can I alter the style sheet in lua? Also I would like to make the buttons and the button text about 3 times bigger. My HTML knowledge is very basic but I am learning!

        Regards

        Ian

        Reply
  12. Hi Rui,
    Great work
    I am planning to use arduino with ethernet module for home automation. I want to control this automation with my android phone via internet. As far as I understand, I need a web server in my computer for this. Can you explain how to create my server ?
    Thanks 🙂

    Reply
  13. Hello Rui,

    Got this project up and running without too much trouble. However, I can only access the ESP’s IP address via a wired browser (e.g. desktop computer), but not in mobile devices on the same network (iphone/ipad). Ideas?

    Karl

    Reply
      • Yes, I have two desktops, one in my “lab” in the basement, one upstairs in my office. Both are hard wired to the router via cat 5 cable. Both will load the ESP8266’s page no problem (using 192.168.1.24 in my case).

        However, when I try using either my iPhone or iPad with the same address, it doesn’t play. (Safari cannot open the page because the network connection was lost) I’ve tried a couple other iOS browsers besides Safari and get the same result. Maybe something to do with port settings on my router?

        Reply
        • It seems the generated html is a bit too ‘minimalistc’. Depending on the browser. By adding some statements like this:
          ——————————————-
          buf = buf..”HTTP/1.1 200 OK\n\n”;
          buf = buf..”\n”;
          buf = buf..”ESP8266″;
          buf = buf..””;
          buf = buf..” ESP8266 Web Server”;
          buf = buf..”GPIO0 ON OFF“;
          buf = buf..”GPIO2 ON OFF“;
          buf = buf..””;
          —————————
          the website is displayed by Safari (IOS) and chrome (android).
          DOCTYPE HTML, and statements are quite essential; the takes care of the smaller smartphone-displays and improves readability.

          Nice work!

          Reply
          • Hi Helmut,
            You can scroll it.
            At the bottom of the embedded code there’s a scroll bar. If you don’t want to copy and past you can download my Lua Script code.
            I hope this helps,
            Rui

          • Helmutt /Rui
            where do these statements need to be in the code ?
            I’m having the same trouble with safari on ios

          • Helmut,
            I, too, am having a rendering problem on iPhone (IOS) and Chrome browser.
            I’ve modified Rui’s AP example code so that your statements are inserted just before and after Rui’s “buf” statements. I am a noob with lua, but had no difference in my IOS/Chrome (on iPhone 6) rendering – still shows as raw HTML. You mention DOCTYPE statements, but your example has none…can you please elaborate?
            Thanks!

          • Helmut,
            After experimenting a bit more with additional HTML tags, my iPhone now displays the 8266 server page correctly.
            I modified the code to:
            buf = buf..”\n”;
            buf = buf..”\n”;
            buf = buf..”\n”;
            buf = buf..”ESP8266″;
            buf = buf..””;
            buf = buf..” ESP8266 Web Server”;
            buf = buf..”LED ON OFF“;
            buf = buf..”GPIO2 ON OFF“;
            buf = buf..”\n”;
            buf = buf..””;

            Perhaps the DOCTYPE and tags made the difference? Now the page renders in iPhone/Chrome & Safari, but (get this) my desktop browsers don’t even connect to the server on my 8266!
            I learned that the AP mode doesn’t work unless I connect to the router first? (in my terminal window, I get an echo of ‘nil’ IP address after the getip() statement, if I send the AP-based code (as a text file) from my terminal after a power cycle. (I’m not currently using ESPlorer, cuz I cannot get it to run on Windows).
            To fix this, I have to run the router-based code, then I manually enter the AP statements in my terminal program, and I get a valid IP address and everyone’s happy (iPhone and desktop browsers connect, render and run properly).

          • Sorry, my code snippit didn’t come across correctly in my last post. Here is my modified lua code:

            buf = buf..”\n”;
            buf = buf..”\n”;
            buf = buf..”\n”;
            buf = buf..””;
            buf = buf..”\n”;
            buf = buf..” ESP8266 Web Server”;
            buf = buf..”LED ON OFF“;
            buf = buf..”GPIO2 ON OFF“;
            buf = buf..”\n”;
            buf = buf..”\n”;
            buf = buf..””;

          • crap! my code still didn’t paste correctly…I think the blog software is trying to interpret my code.
            Anyway, I added lines to the buffer for , , , , and , and that seems to have fixe my rendering problem on iPhone/Chrome.

  14. Hi Rui,

    Thanks for this awesome tutorial.

    I am able to flash the firmware & script its working fine.
    I did some modification in your code and able to use Both Station & AP mode at the same time.

    Now i don’t want to hard code the SSID & PWD for Station mode in code and want to provide a flexibility to set it from the webpage how to modify the html part of the code so that i can pass SSID & PWD from web and then depending upon the data i will call wifi.sta.config() function to connect to my router ???????????

    For configure the Station mode SSID & PWD i will use AP mode, where forAP mode i will hard code the SSID & PWD.

    Reply
  15. I recently made Lua based temp sensor. Few points to keep in my mind based on my experience.
    1. always supply extra power to esp8266 when uploading Lua file. during flashing the nodemcu firmware you can supply from ftdi. after that, disconnect the vcc from ftdi to esp8266 and supply another 3.3 volt to esp8266. keep ground of ftdi connected.
    2. never ever write the loop code in init.lua. you will end up reflashing. instead write a basic wi-fi connection code in init.lua and call another lua file from init.lua.

    Here are home automation ideas.
    1. LPG Gas.smoke.CO gas sensor using MQ-2 sensor. since esp-01 does not have analog input, I built the sensor using arduino nano, esp8266 and MQ-2 sensor. thi sesp8266 at AT firmware. I am waiting for ESP-12 which has analog input also. then I may not need arduino. It uploads the data to thingspeak. There i setup the alert which will send me text message if gas sensor value reach a certain value.
    2. make temp sensor to monitor your furnace or ac usage of hvac. I build using esp8266 and ds18b20 temp sensor with lua firmware. It uploads the data to thingspeak.com.
    3. Next project I have yet to build..
    — Main door locked/unlocked monitor, garage door monitor, basement sump pit water level monitor. I will monitor the garage door and if garage door is found open and I am away, i shall be able to close by sending the command to esp8266 using talkback from thingspeak. i am already using talkback command for my mq-2 sensor project where I can set the buzzer limit.

    Reply
  16. Hi Rui, your blogs is so nice and well explained. Just have a question in my mind,
    is it possible to program the ESP8266 module with arduino uno? i mean as a replacement of ftdi programmer.if yes, could you gave me link related to this? thanks

    Reply
      • Hi Rui, thanks for your quick response and advice:-), highly appreciated. I’ll going to try this once my order arrived.can’t wait to start:-).

        Reply
  17. hey rui,
    i am new to esp8266 , i am facing a major problem that when i connect esp8266 to my atmega328 ,my rx and tx are blinking continously and usb port is disabled automatically whtz the problem with connect
    .. just connected as per your tutorial

    Reply
  18. First very nice project. I think will be good to control some devices on my house. I already replicate your project but no success so far. There are two things that I want you to clarified me. You mentioned ” You might have to change some of the settings on the Advanced tab” Please what must be change and why. Secondly change you network name and password.
    I have a computer connected wireless to my router and my wifi con is DavId and password.
    This is what it should be put on lua files. Sorry I am a beginner I just start to learn about AP MAC STA MAC etc. Please help to make this working
    Kind regards

    Reply
  19. Hi.
    I’ve tried your code and the board hangs constantly when I try to switch on or off the leds.
    Did you uncounted the same behavior?

    Regards

    Reply
  20. Hi,
    Fastinating read. Unfortunately I’m also experiencing problems with getting the init.lua flashed onto an ESP8266. A message either say’s ‘waiting for answer from ESP – Timeout reached. Send aborted’ failing that the device status shows as ‘busy’ (and gets stuck in this state).

    Flashed my ESP8266 twice now via ESP8266Flasher and the device seems to flash okay. Any idea’s where I’m going wrong please?

    Hooked up via an FTDI programmer exactly as you’ve illustrated (at a guess should this be incorrect the ESP8266 would not flash its firmware successfully using ESP8266Flasher) without avail.

    Anyone’s help on getting up and running so to speak would be appreciated.

    Thank you.

    Reply
  21. Hi, Great tutorial. Tried and failed to get beyond flashing the newer version of firmware onto some of these devices. The file with modified wifi settings comes up with a timeout error again and again. Occasionally upon flashing the firmware the Com Port disappears altogether (immediately after flashing). Any ideas what can be the cause of this please?. Wanted to add have tried an FTDI and a Prolific USB programmer with the same results (they are USB to TTL adapters that provide a ‘virtual’ Com Port aren’t they? Failing that am not using the correct adapter). Can you confirm what pinout diagram should be used before and after flashing the firmware please? Confused as come across other pinout configurations too. Thank you.

    Reply
  22. Hi Rui, thanks for your great tutorials 🙂

    Just a quick question, you mention you could use this to control a relay.

    Would I just connect the gpio pin to the control pin of the relay or would it need a pull down resistor in there somewhere, I say pull down as if gpio0 is pulled high during boot it enters flashing mode (I think? I’m an electronics n00b ATM but learning….slowly)

    Thanks again.

    Reply
    • Hi, In answer to your question regarding hooking up an ESP8266 to a relay i’ve managed to get a 5v single relay module to work with the GPIO connected directly to the input of the latter but notice that whilst GPIO is switched off (logic 0) the relay is switched on and vice versa. At a guess there should be additional components used to switch on/off a relay. Perhaps someone on here can comment? The 5v single relay module is being powered via the same 3.3v positive rail as the ESP8266 itself just to confirm.

      Reply
  23. Beautiful tutorial, very much glad to have come across this one. Wondering if it is possible to toggle the switch for say.. 2 or 3 seconds and then turn off, rather than having on and off options. I am a newbie, please forgive if this is a daft question.
    I know in arduino there is a delay (1000) function, which will delay further execution by 1 second. Anything similar in Lua ?
    Thanks and advance.
    cheers.

    Reply
  24. Hello Riu,
    Thanks a lot for this great tutorial.
    Do you have some hint to implement a restfull API in LUA ?
    I want to send some data to a Microsoft Azure service whith the POST, GET, UPDATE Restful command.
    Thanks for your help.
    Yann

    Reply
  25. Hi Rui,
    thank you very much for your tutorial.

    I tried some bigger webserver demos with no success.
    Your demo worked like a charm instantly.
    I have experience in progamming Delphi and a bit assembler.

    Can you recommend a bloody beginners tutorial about html-coding?

    Is there somewhere a userforum that focuses on small embedded webservers
    discussing how to create buttons, status-LEDs small textboxes for statusmessages?

    My first idea is to modify your demo to a single button with integrated light.
    Click once button lights up – click again button-light is switched off.
    Maybe visualised just by different button-colors?

    I guess the lua-script needs some bigger changes for this. There must be a variable
    for the current switch-status, html-code for button-color must be added etc.

    best regards

    Stefan

    Reply
  26. Hello Rui, great job

    I have follow the steps of your post and it seems all is OK, but, I send the code to the ESP8266, and all seems to be OK, but when I restart the module it appears the following message:

    “NodeMCU 0.9.5 build 20150126 powered by Lua 5.1.4
    lua: cannot open init.lua”

    So I cannot get the IP address of the module. It seems the code is not running on my ESP8266. What could be wrong?

    Regards
    David

    Reply
    • David,
      I believe your problem is that you need to permanently write the lua code in Rui’s example to the 8266 module. Rui’s tutorial simply writes init.lua to the 8266 temporarily.
      I have used LuaLoader to write lau files to the 8266 permanently in the past, but this did not work for me with an FTDI interface – it only worked for me when I substituted an Arduino Uno for the FTDI.
      Good luck.

      Reply
      • David,
        Hope you got your init.lua working. If not, try ESPlorer as your interface. I now have a working ESPlorer on windows after discovering a bad download, and this program seems to work well as a general purpose ESP IDE. Use the ESPlorer’s “Save to ESP” button to write your init.lua code permanently to the 8266.
        I have a slightly modified version of Rui’s example (using AP mode instead of STATION, and adding DOCTYPE and html and body tags to the HTML section) and it works perfectly from my iPhone – even after a power cycle. Just be sure to connect to your new AP or STATION with your browser when testing.

        Reply
  27. Hello congratulations on your work! I am in doubt which firmware version should I use this example! What firmware version should I write to the ESP8266?
    Thank U! Congratulations for your work!

    Reply
    • Hello, Yes you can talk directly to an ESP8266 instead of using your router. This is called AP mode from what’s been gathered (apologies should the latter be incorrect).
      The ESP8266 dynamically asigns your Andriod device with an IP address in this case as opposed to your router.
      The ESP8266 doesn’t seem to like IOS though.

      Reply
      • Gadge Guru,
        I have successfully used my iPhone to talk to the 8266 (mine’s an -01 version) in AP mode. I used Rui’s example, but had to add DOCTYPE, html and body tags to the HTML page section (see lines starting with “buf = buf..” in order for my Safari browser to render the HTML code correctly. Also, don’t forget to connect the iPhone to the AP server signal first, or the IP address of the 8266 won’t connect.

        Reply
  28. Very good description Sir. You are a very friendly person and all your projects you share are very good and very helpful for a beginner. I had no problems with the project, everything goes as you described it. Many thanks to you, you can always see everything for sharing with the world. I’m a real fan of your projects and hope there come many do so.

    Best regards from Germany

    Reply
  29. Hi,
    Like your program! I works a treat for me.
    Is it possible to change the colours of the buttons or is this ouside the scope of Nodemcu?
    cheers
    Colin

    Reply
  30. Hi,Rui,its my first post on this thread and also first try a LUA project developed by you.So
    i ought to say THANKS as i am verry satisfied although i dont know anything about this lang.(LUA).Your project works on my first try and works good!,but i notice: 1) when powered off needs to reupload the lua script file as although were saved on esp as you suggested.
    2)The ESPlorer changed to 02 betta version but there is no problem to understand.
    Can you please give an answer on 1)? and where this comming?

    EDIT:As i also use this module (ESP8266-01) with Arduino i have problem when ip changed during rooter powered off and repowered.IMHO this is not happen on this project,am i wrong? as i am going to use for home automation.

    Thanking in advance congr. because i think you are young man and sorry for any typos as i am Greek

    Greetings
    Reply

    Reply
    • Hi Christos,
      You English is fine! Don’t worry. Awesome I’m glad it worked out for you.

      1) That shouldn’t happen. Are you sure you’re saving the code to your ESP8266? Or you are simply Sending the lines to the ESP8266?

      2) I haven’t tested the new ESPlorer version I’ll give it a try very soon and update this blog post…

      3) You can try to set your ESP8266 as an Access Point so it doesn’t change the IP address.

      Have a nice day,
      Rui

      Reply
      • Hi,Rui
        Thanks for your quick responce, the code saved on esp as you suggested not simply the lines.The problem remain as tested more than 3 times.

        Greetings

        Reply
      • Hi,Rui and everyone

        WORKAROUND TO SOLVE THE PROBLEM when module disconnected after powered off(although code saved on ESP and not lines only):put a switch on GPIO0 and GPIO2 in off state(this mean there is no load on these pins),then power the module on and put the switch in on state(the two leds must be off now, if yes you are ok)

        NOTE:there is no problem even internet ip changed as the module ip remains same

        Have a nice day

        Christos

        Reply
        • Yes, worked fine for me. But how to manually disconnect everytime when newly powered on. Anything to change in coding to avoid this or anything can be added in the circuit?

          Reply
  31. Thanks for this Rui. It’s a good leg-up for the project I have in mind; I’m completely new to Lua so it’s helpful having a well-structured, fully functioned example to work with.

    Reply
  32. hi,
    I thought we can’t use gpio0 as output, when I use gpio0 as output this pin sens it as low, and it make the module put into flash mode, maybe that’s why the module cant restart with gpio0 pin loaded, or maybe we can use a bigger resistor to the gate of transistor?

    Best regards from Indonesia,
    Dani

    Reply
  33. Hi Rui,

    Can I have the same code for esp-03 so i can control more gpio’s

    You have been so polite adn swift in making your replies

    Great Job.
    Good Luck

    -Kumaran

    Reply
  34. Can the network name and password be eliminated by giving the user to feed the above parameters ie YOUR_NETWORK_NAME , YOUR_NETWORK_PASSWORD on a html page rather than permanently writing the same in the lua code?

    Reply
  35. Hello Rui
    would you like to suggest, or would have the please of you that you have your webserver, for example, which is really good, will broaden the MCP23008. I think that would be good, because then you have so several GPIOs, especially for the esp8266-01 that would be good. AllAboutEE this has already written a library for Lua, I think it will be relatively easy for you to realize that. I’m sorry there is too much beginner to bring this together.

    Would be nice if you could do that.

    Best Regard
    reini

    Reply
  36. Hi Rui
    thanks for your good example…
    unfortunatly my ESP doesn’t works, I explain.
    Using AT command with original firmware it works good.
    After NodeMCU upgrade it seams to works but just after I load your example the ESP go in connect/disconnect loop to the serial and I cannot connect it but I have to reload original firmware.
    Do you have any Ideas
    Thanks in advance

    Reply
  37. Hi Rui,

    Thank you for this tutorial, its interesting weekend project.
    I tried to flash with success, but i cannot upload the init.lua using latest version of esprorer.
    Can i have the older ESprorer ? Mine is ESprorer v0.2.0-RC1

    Best Regards,

    John

    Reply
  38. Hello Rui! Nice project! I will like to ask you some things:
    – Please give me a link to a recommended usb to serial adaptor
    – If i connect a 10k resistor to VCC and CH_PD is that ok ?
    – What kind of led have you used? (Example: Red Led with 20mA and 1.7 volts )

    Would be nice if you could answer me those questions .

    Best Regard
    adih2001

    Reply
  39. Large number of Lua programs for standalone ESP8266 are appearing these days but for all of them the SSID and password are firmware coded.Therefore while one moves away from the tested network it does not work. I have seen only one ,very lengthy that provides the entry of SSID & password to be written in a webpage first while ESP is in own access mode and thereafter it goes to wifi mode so that one can use it any network.A simple Lua program with above features to switch on and off GPIO0 is required.

    Reply
  40. hey, I have completed most steps in this tutorial. I only have a problem with obtaining the IP address of the module.
    I get “init.lua:8: only one tcp server allowed” I do not quiet understand where my flop are.
    please help

    Reply
  41. Rui, very nice example. But how can i see the status of the leds when i enter the page for a second time? Can you please make an example?

    Wim

    Reply
  42. Rui, I asked before but I still don’t see my reply in this list.
    Anyway, I asked if it’s possible to see the status of the LED’s when you enter the page.

    Maybe by coloring the buttons red and green by the actual state.

    Can you please make an example?

    Regards, Wim

    Reply
  43. Rui,
    Thanks for all your support on this topic. It’s obviously a hot topic for us 8266-ers.
    My goal is to create a 8266-server based website that would prompt for a wireless router’s SSID/Passcode, then connect to that router. I want my 8266 to be usable anywhere by anyone with a wifi signal (i.e., I don’t know in advance how to connect to their wifi signal). It seems as if the AP mode you discuss here “should” work, but I’m stuck due to my observation that I have to first run the lua code (STATION mode) which connects to a known wifi router, *then* set the mode to SOFTAP. Do you know of a way that I can skip the STATION mode steps altogether?
    I haven’t yet flashed your lua code into my 8266, so I simply send the text file to the 8266 every time I change something or power cycle. I’ll try this next to see if things work any better.

    Reply
    • Rui,
      I think I found part of my problem – it’s pretty obvious when I think about it.
      When I setup an AP (your sample credentials are test/12345678), I then need to connect directly to the AP (not my wifi router). I guess nobody else mentioned this little detail yet, but it’s critical to AP-mode operation.
      I still have the problem where in order to get into AP mode, I first have to setup a STATION mode to a wifi router. Any way I can avoid this?

      Reply
      • I think I know why AP mode wasn’t getting applied in my earlier attempts (except after a STATION mode setting)…I had lua script command errors.
        Now, I can power on the 8266 (with NodeMCU lua interpreter v0.9.5 previously flashed) and send the lua script above using CoolTerm with the first 2 lines replaced with the following 5:
        wifi.setmode(wifi.SOFTAP)
        cfg={}
        cfg.ssid=”test”
        cfg.pwd=”12345678″
        wifi.ap.config(cfg)

        I can then join this new wifi “test” AP with my iPhone and then navigate with either Chrome or Safari browser to IP address 192.168.4.1 and see the LED control web page. I can also control the LED remotely from the web page.

        Oh, and I also had to add a few lines to the html code at ~ line 26 to include a “DOCTYPE html” tag (prior to any other html), and I also added and tags for good measure. These changes allowed the page to render properly in my iPhone browsers.

        My next step is determine how to write my lua code into non-volatile memory on the 8266. I know about the “init.lua” reserved filename for auto-start scripts – I just have to figure out how to write my working code to that file on the 8266. My AP setting survives a power cycle, but the functionality in the lua script does not. Unfortunately, I’m using a Windows 7 machine, and these instructions for ESPlorer installation seem to be for a Linux environment…I haven’t yet been able to install on Windows.
        Has anyone else loaded lua script such as this example to an 8266 from a Windows machine? If so, please share which loader you used, and other details (e.g., FTDI USB adapter or Arduino,

        Reply
    • After further research, it appears that the AP mode generates a different IP address than the STATION mode does. In my case, the statement “print(wifi.ap.getip())” produces a response of 192.168.4.1, whereas the equivalent station mode gives 192.168.106.125.
      In any case, it looks like my AP wifi signal does survive a “node.restart()”, but the IP address does not (I have to send the init.lua file again to restore it). I am able to connect to “test” with my iPhone, but when I go a browser, neither IP address renders the server page.

      Reply
  44. Rui,
    Parabéns pelo seu trabalho.
    Eu baixei o mas não achei o caminho:
    Go to the dist folder (here’s the path: ESPlorer-master\ESPlorer\dist)
    e também não achei o arquivo ESPlorer.jar.
    Tem outro lkocal onde possa baixar? Outra pergunta, é necessário esta no computado os arquivos de: https://github.com/nodemcu/nodemcu-firmware.
    Grato.

    Reply
  45. Hi!

    Thank you for sharing this easy tutorial!

    I got problems when I try to connect to it on a webbrowser, seems like port 80 is not open at all. I just copied and pasted your code.

    Thanks!

    Reply
  46. Hi,please can some one tell me how to upload a lua code to the esp8266,i just dont understand it,there not one simple tutorial any where,there so many firmwares too,and they are put in different places some have 5 bins and node mcu has one ime so confused,ive had the thing for two week now and still not got a clue,ive two of them so they musnt be faulty,ive the node mcu dev kit the yellow board v0.9 please help me.i want to use my oled ssd1306 as a user interface on it,i read node mcu firmware does it auto but i cant get it working,i think i2c is pin 5 and 6,cheers folks

    Reply
  47. Duncan
    Are you using ESPlorer on windows? If so would you share where the installation instructions are? I am unable to install or launch ESPlorer on my windows 7 PC but would like to try it.

    Reply
  48. hello,
    I have send my data to thingspeak. can i go for sending data from one esp8266 to another one.?
    If yes then how it would be??
    Please leave reply.

    Reply
  49. Hi, I’m newbie and your tutorial is great.

    So esp8266 only has two GPIOs. If I want to control more LEDs, should I use more esp8266, or can I just use multiplexing? If later, do you have any tutorial about multiplexing?

    I want also to control some 220V devices with esp8266. Can I use relay?

    Reply
    • gungsukma,
      If you wish to control 220V devices, you will need a relay with a 3.3VDC compatible input. I recently purchased such a relay (FOTEK SSR-40 DA) on AliExpress for less than $4 (http://www.aliexpress.com/item/2014-New-High-Quality-40A-250V-SSR-White-Solid-State-Relay-Controller-3-32V-DC/32226842249.html). This SSR is for controlling AC devices up to 380 volts and 40 amps. I plan to drive this SSR directly from my 8266 (or Arduino). However, I haven’t yet tried this, so I may need higher current than 8266 can supply, so I may need to add a transistor to drive the SSR.
      That said, a Triac should also work, but you may need some external circuitry to condition your control signal.
      Let us know what you do and how it works for you.

      Reply
      • gungsukma,
        Just tried to drive my SSR (see posting above) directly with my 8266-01 (GPIO2 pin) and it works! (at least the LED on the SSR lights up when I click the GPIO2 “On” button on the web page).

        Reply
        • Just noticed something else. When GPIO2 is connected to my load (the base of an NPN transistor or my SSR input), and I power cycle my 8266 (with the remainder of the circuit), I get a solid blue LED on the 8266 (and no AP gets configured). Also my LED on the GPIO0 pin is on. I assume the 8266 is going into flash mode, as someone else observed on this discussion). Perhaps my circuit is too much of a load for the 8266 (and it sees this as a ground)? Doesn’t make sense, since this is GPIO2, but that’s what is happening to me…

          Reply
  50. Hey Rui, thanks for this amazing simple tutorial.

    I need to do the same but also pick data from I2C from a PIC (do you know how to do it?)

    and also, how can i upload a different html page to there.. (custom).

    Thanks again,

    Regards

    Paulo Cardoso

    Reply
  51. Hi,
    here I put a minimum modification, to read config for wifi connection at the beginning and one ON/OFF button has been added.

    — Read Configuration
    file.open(“config”, “r”)
    ssid = string.gsub(file.readline(),”\n”, “”);
    passwd = string.gsub(file.readline(), “\n”, “”);
    file.close()

    wifi.setmode(wifi.STATION)
    wifi.sta.config(ssid, passwd)

    print(ssid)
    print(passwd)
    print(wifi.sta.getip())

    led1 = 3
    led2 = 4
    gpio.mode(led1, gpio.OUTPUT)
    gpio.mode(led2, gpio.OUTPUT)

    srv=net.createServer(net.TCP)
    srv:listen(80,function(conn)
    conn:on(“receive”, function(client,request)
    local buf = “”;
    local _, _, method, path, vars = string.find(request, “([A-Z]+) (.+)?(.+) HTTP”);
    if(path == nil) then
    path=””
    end

    print(“Path: “..path)
    if(method == nil)then
    _, _, method, path = string.find(request, “([A-Z]+) (.+) HTTP”);
    end
    local _GET = {}
    if (vars ~= nil)then
    for k, v in string.gmatch(vars, “(%w+)=(%w+)&*”) do
    _GET[k] = v
    end
    end
    buf = buf..” ESP8266 Web Server v2″;

    local _on,_off = “”,””
    if(_GET.pin == “ON1”)then
    gpio.write(led1, gpio.HIGH);
    elseif(_GET.pin == “OFF1”)then
    gpio.write(led1, gpio.LOW);
    elseif(_GET.pin == “ON2”)then
    gpio.write(led2, gpio.HIGH);
    elseif(_GET.pin == “OFF2”)then
    gpio.write(led2, gpio.LOW);
    end

    if(gpio.read(led1)==0) then
    buf = buf..”GPIO0 ON“;
    else
    buf = buf..”GPIO0 OFF“;
    end

    if(gpio.read(led2)==0) then
    buf = buf..”GPIO1 ON“;
    else
    buf = buf..”GPIO1 OFF“;
    end

    client:send(buf);
    client:close();
    collectgarbage();
    end)
    end)

    Reply
  52. Hi,
    I’m having some problems here…
    First, when flashing, I don’t always get the green circle at the end, but I can save to ESP every time I flash my ESP8266.
    Second, everytime I unplug it, or do a reset I can’t upload my code again, it jus says “the request timed out” and in order to upload my code again I have to flash my ESP8266 again, and this just takes a lot of time.
    Third, after all the above are “ok” I can’t get the ip adress, insted I get the line “print(wifi.sta.getip())” on the serial monitor, this should change to the ip address.

    If you could try and help me I would appreciate a lot!

    Reply
    • Lino,
      If you don’t get the green icon on the ESP Flasher utility, your flash did not complete. You need to fix this first. I had this problem forever, then replaced my ESP module and all is well again…I can flash in one click, just like the flasher promises.

      Reply
  53. I am very new to esp8266.
    I have flashed it and I have done the wifi connection to my router. I had two IP’s : just the second is ok. ( 192.168.4.1 and 192.168.0.105 ) >>> is this OK ?
    When I try to save to esp the init.lua file , I have the time out message.
    Com port is connected succesfully.
    Any pin to be grounded / +3.3v connected to load the init. lua ?
    Thanks for helping ,
    regards,
    Ambro

    Reply
  54. Are you familiar with how to make this accessible to public networks (control anywhere over internet)? I’ve set up local network control but work like to be able to control anywhere in the world. Can you help?

    Reply
  55. Hi,
    Is it possible to send command from internet via esp8266 to arduino uno ?
    My project is controlling temperature in room( using lm355 sensor). Idea was to set temperetare which we want in room via internet to arduino.

    Regards,
    Matea

    Reply
  56. Hello..

    I have done nice testings with ESP with 2 TCP servers on ESP. Then we can assign 2 IPs and use in different sub nets.
    One IP is acting as AP and other is connected with router.

    ESPlorer is warning ” it cant run 2 TCP Servers” but it is working.
    Please let me know my faults or wrong of thinking.

    wifi.setmode(wifi.STATIONAP);
    wifi.ap.config({ssid=”test”,pwd=”12345678″});

    led1 = 3
    led2 = 4
    gpio.mode(led1, gpio.OUTPUT)
    gpio.mode(led2, gpio.OUTPUT)

    srv=net.createServer(net.TCP) — 1st TCP Server Works as AP with SSID = test and Pass = 12345678
    srv:listen(80,function(conn)
    conn:on(“receive”, function(client,request)
    local buf = “”;
    local _, _, method, path, vars = string.find(request, “([A-Z]+) (.+)?(.+) HTTP”);
    if(method == nil)then
    _, _, method, path = string.find(request, “([A-Z]+) (.+) HTTP”);
    end
    local _GET = {}
    if (vars ~= nil)then
    for k, v in string.gmatch(vars, “(%w+)=(%w+)&*”) do
    _GET[k] = v
    end
    end

    buf = buf..” ESP8266 Web Server”;
    buf = buf..”GPIO0 ON OFF“;
    buf = buf..”GPIO2 ON OFF“;
    local _on,_off = “”,””
    if(_GET.pin == “ON1”)then
    gpio.write(led1, gpio.HIGH);
    elseif(_GET.pin == “OFF1”)then
    gpio.write(led1, gpio.LOW);
    elseif(_GET.pin == “ON2”)then
    gpio.write(led2, gpio.HIGH);
    elseif(_GET.pin == “OFF2”)then
    gpio.write(led2, gpio.LOW);
    end
    — print(tmr.now())

    client:send(buf);
    client:close();

    collectgarbage();
    end)

    end)

    wifi.sta.config(“Your_SSID”,”PASSWORD”) — 2nd TCP Server connceted with your Router
    wifi.sta.connect()
    gpio.mode(led1, gpio.OUTPUT)
    gpio.mode(led2, gpio.OUTPUT)
    srv=net.createServer(net.TCP)
    srv:listen(80,function(conn)
    conn:on(“receive”, function(client,request)
    local buf = “”;
    local _, _, method, path, vars = string.find(request, “([A-Z]+) (.+)?(.+) HTTP”);
    if(method == nil)then
    _, _, method, path = string.find(request, “([A-Z]+) (.+) HTTP”);
    end
    local _GET = {}
    if (vars ~= nil)then
    for k, v in string.gmatch(vars, “(%w+)=(%w+)&*”) do
    _GET[k] = v
    end
    end
    buf = buf..” ESP8266 Web Server”;
    buf = buf..”GPIO0 ON OFF“;
    buf = buf..”GPIO2 ON OFF“;
    local _on,_off = “”,””
    if(_GET.pin == “ON1”)then
    gpio.write(led1, gpio.HIGH);
    elseif(_GET.pin == “OFF1”)then
    gpio.write(led1, gpio.LOW);
    elseif(_GET.pin == “ON2”)then
    gpio.write(led2, gpio.HIGH);
    elseif(_GET.pin == “OFF2”)then
    gpio.write(led2, gpio.LOW);
    end
    client:send(buf);
    client:close();
    collectgarbage();
    end)
    end)

    Reply
  57. Only the Android browser on my phone is working with this web server, similar as the video demo of this tutor.
    I tried many other browsers on Windows XP and W7, such as Opera, IE, Thunderbird and Chrome, all claiming the webpage not existing.
    Does any of you have experience with other browsers?

    Reply
    • I’ve built this and it works on my iphone6 with safari and chrome. I assume you are setting your phone’s wifi connection to the 8266 SSID?

      Reply
      • The same with me, it works fine on browsers on my Android phone, but not on browsers on any of my windows PC’s. I did not check Linux.

        Reply
  58. hi,
    Thank u mr. Rui for sharing such a effective project.
    but i’m facing some kind of weird problem:
    The wiring i did as u mentioned.
    The ESP module is flashing with Nodemcu without any problem.

    but, when i m trying to upload INIT.lua with Esplorer , it shows ‘waiting for answer from ESP – Timeout reached. Send aborted’.as u told “the module is busy with some other program”,so,i tried it on a other PC but same problem.
    since 15 days i’v been trying to solve this.today i decide to consult with u for an exact navigation.
    thanks..

    Reply
  59. I am afraid but it is not like to have assistance from this site.
    No replies, or no useful reply …
    Does it worth to buy a book ?
    Let me know please .
    Thanks
    iw2fvo

    Reply
  60. Hi,
    I have downloaded the nodemcu software but i am facing a problem when i press flash.It is not getting downloaded.It is showing “no wifi” and “no gpio”, even though i have connected gpio0 to ground.Could you help me with this.
    Thanks.

    Reply
  61. Hi,

    hope someone can help me out? i have done all of the steps and the module is working fine on my pc an android phone but not on my ios devices (iPhone. iPad) maybe it is something simple, can someone help?

    thank you! 🙂

    Reply
    • I think with the new Safari update it doesn’t have the necessary headings in the html page to be compatible with Safari… you might need to add to the head tag of the HTML web page additional information

      Reply
  62. Hi,

    Got an ESP-01 yesterday, seems to work ok with (updated) factory firmware with the AT commands.
    When I flashed it with the Nodemcu firmware it is ok to work with ESPlorer as far as the creation and storing of Lua scripts is concerned.
    However the execution of Lua scripts fails. Also, and this is probably the cause, the ESP-01 does not react correctly to the AT commands anymore. Every AT command is now responded by : ” stdin:2: ‘=’ expected near ‘+’ ” or something similar.

    Any suggestions ? Thanks on beforehand.

    Reply
    • Hi Jean,
      I recommend you send this command to your ESP8266 with the ESPlorer IDE file.format(). And try to upload the new lua files to see if everything works. On the other hand if you no longer want the NodeMCU firmware you need to reflash your ESP with the AT command firmware.

      Reply
      • Hi Rui,

        Many thanks for your reply, it works now, I had a few issues myself and not knowing what to expect (my first time with the ESP8266) it took me some time to cope with them: My set up was battery fed (4 Alcaline cells) through a 3.3VLDO regulator. What I didn’t realise at first is that my cells were almost empty. This explains the sometimes erratic behaviour of the device. Also I had a typo in the password, supid of course, and that also took some time…
        Also, sending commands to the ESP from the ESPlorer IDE works ok from the tap “scripts” (for the few set up commands that are available). From the tap “AT command” I however still get the “stdin:2: ‘=’ expected near ‘+’” error message for all possible commands. It does not matter too much since I intend to use the device with a Lua scipt anyway.
        I realise now that once the Nodemcu firmware is flashed the serial port is connected to the Lua engine rather to the orginal AT command interpreter of the factory flash. So actually the AT command set becomes more or less useless. Is this a correct interpretation ? Not having realised this at first was of course adding to my confusion.
        Yes, of course, if I want to use the ESP in its initial way I need to reflash it with the factory firmware.
        Anyway, also thanks for this nice tutorial, it is a great place to start. A question though: is there some place where I could find the list/libray of embedded functions (such as “createServer(…)”) for the ESP with Lua ?

        Thanks again and all the best,
        Jean.

        Reply
  63. Hi Rui ,
    I have been working on ESP8266 for some time .its really damn cool wifi module at affordable price .
    i am facing a problem that ESP8266 is losing the TCP server every now and then and i have to reset it again and again ,My project is also based on home automation

    can you please help me to solve this problem .
    I am using ESP8266 -01 with AL-thinker firmware 0.9.5

    Reply
    • Hi Sunil,
      It seems that you’re not supplying your ESP with enough amperage and when your web server requires more power it reboots your ESP.
      Make sure you use a power supply that supplies 3.3V and 300mA.
      I hope this helps!

      Reply
  64. Hey! i have done this about 1/2 a year ago, and i want to do it again, so i needed a web server… What do i do when i have an unsecured access point?(i live on a farm with no neighbours, and don’t need password on our wifi…)

    Reply
  65. Hi Rui,

    Congrats for the projects!

    I could open the web server on my laptop / desktop, but I couldn’t open it from my iPhone. Do you now how to fix this issue?

    Regrads,

    Carlos Sales Junior

    Reply
  66. Hi Rui,
    Thanks for your enlightenment of esp8266 wifi module, actually i am interesting to explore this module furthermore.
    Thanks,
    Tony

    Reply
  67. Dear Rui:

    wonderful tutorial, thanks very much,
    how we can fix the ip address for ESP8266 from the beginning?
    i have problem also in connecting to it not always replay and to much delay in response

    thanks

    Reply
    • Hi Khalil,
      Thank you for your feedback!
      Fix the IP? You can see the IP in your serial monitor? You can send this command to print in the output window of the ESPlorer your current IP address: print(wifi.sta.getip())

      Are you supplying enough current to have your module stable?
      Thanks for reading,
      Rui

      Reply
      • Hi Rui,
        I admire your patience in answering the many questions. Thank you.
        In the programs you wrote we see code eg ….Conn: “ ([A-Z]+) (.+) HTTP”); etc. I was trying to find the instruction set for the esp language, so I was asking if in your book you had more information about the instructions and their use. I searched but did not find anything on the internet. I found the API but did not see eg Conn:
        Regards
        Franklin

        Reply
  68. Awesome tutorial, just bought your book too.
    One thing: on my Adafruit Hazzah, the led HIGH/LOW are reversed.
    i.e: Low = On,
    and High = Off

    Dave

    Reply
  69. Hello Rui,

    I have a problem when I try to upload code init.lua, the status is BUSY, even though I’ve Flash my ESP twice and still didn’t work….
    Could you help me to fix it…
    Thanks before….

    Reply
    • Hi Vincent,
      Try to do this trick. Having your ESP connected to your FTDI. Open the ESPlorer and open the serial communication.
      Then connect a jumper wire from the ESP8266 RESET pin to GND, pull that cable and connect it to 3.3V. This should reset your ESP and allow you to upload code.

      Reply
  70. Thank you Rui,
    I’m a Newbie. Just got my self a ESP12 with the dev board on eBay.
    After uploading the Lua.init webserver, how to stop and update the lua again.
    It seems while the webserver is running, i cant reprogram this ESP.
    Thank you.
    Sam

    Reply
  71. hi everybody
    I need some help…!
    please help me to solve this problem.
    I have 2 esp modules esp01 and esp07 most of the think that i do are with the ep07. I use nodemcu firmware and the version is “v0.9.2.2 AT Firmware” and it works pretty well but now I want use the esp stand alone for controlling relay but icant use arduino ide and also this instructure and I can’t access to my esp.
    how can I fix this problem….??
    thanks for all

    Reply
  72. I’m having issues with this webserver running in NodeMCU Devkit 1.0 ( ESP-12)
    My webserver works fine if got continuous interaction. However if no activity for 1minute, it stops responding when reload browser.
    Need to restart NodeMCU to get it running again.
    How can I fix this ? I have reflashed the firmware.

    Reply
  73. after restarting esp and gpio0 pin still connected to the + of the led web server doesn’t work but when i leave the gpio0 floating with no connection it starts normally ??

    Reply
  74. Hi Mr.Rui Santos

    Thanks for your tutorials. I posted my question here a couple of day ago, now I can’t find it. I don’t what is happened?

    Reply
  75. HI Rui, Thanks for the great work and sharing you do! I have learned much since following your tutorials. I can communicate with the 8266, and have been able to control gpio pins. but am having problems with the wifie aspects and many of the different ways to access the 8266 out on the web seem to confuse the issue. I have tried many different projects with little luck. I think because there are so many terminals out there and syntax seems to change (in nodemcu)since the writing of the articles I reference to. So in an effort to get something going I came back to this project. I am using an ESP-7 and communicating with ESPlorer 2.0-rc2. The code uploaded fine (I think) but when I restart the 8266 I don’t get an IP address back it simply says (nil). If i query the module manually using “print(wifi.sta.getip()) ” I get an answer of “192.168.0.109255.255.255.0192.168.0.1” Next I go to my browser and type in 192.168.0.109. and get “webpage not available”. I know I must be doing something incorrectly but I’m not sure what. Can you help? Thanks again for such wonderful tutorials.

    Reply
  76. Still working with this project, I did get the basic functionality of it working. I think that in an effort to copy/paste, some formatting got in there to mess it up. Bought you a coffee 😉 (and got your book ) Now in an effort to understand the communication to the browser. I
    I started doing tutoring on HTML. Basically I wanted to start with making the ON/OFF buttons bigger so that on a mobile device they would be easier to deal with. From the tutorial I tried to inject into the buf = buf statement — ON — this worked in theory on a straight html page accessed via the chrome browser, but if I try to incorporate it into the code for the 8266 I get an lua:23: error saying “malformed number near 200px” . Have I not coded properly? or does lua not like trying to deal with that statement?

    Reply
    • The statement as written won’t come through (sigh) basically stating pixel size incorporated into the button using style equal height:200px;width….”and so on. Incomplete because I don’t want to chance it not coming through again.

      Reply
  77. For some reason the last post didn’t go through in it’s entirety So I’m trying again…

    Still working with this project, I did get the basic functionality of it working. I think that in an effort to copy/paste, some formatting got in there to mess it up. Bought you a coffee 😉 (and got your book ) Now in an effort to understand the communication to the browser. I
    I started doing tutoring on HTML. Basically I wanted to start with making the ON/OFF buttons bigger so that on a mobile device they would be easier to deal with. From the tutorial I tried to inject into the buf = buf statement — ON — this worked in theory on a straight html page accessed via the chrome browser, but if I try to incorporate it into the code for the 8266 I get an lua:23: error saying “malformed number near 200px” . Have I not coded properly? or does lua not like trying to deal with that statement?

    Reply
  78. Hi Rui,
    You’ve done a really great job (as always I should say). It worked just fine, thanks to your explanations. Now, I want to use ESP8266 to send data from some sensor (LDR or Flex sensor), to control a servo. I will appreciate your help very much. Thanks a lot!!!!!

    Reply
  79. Hi Rui,
    I am using your tutorial. I can access my my server page on my laptop to control the 2 leds.
    However, i cannot access my my server page on my iphone using safari. how can i fix this?
    By the way, i can upload the init.lua from esplorer into the esp without connecting gpio0 to gnd. Do you have ideas about this?

    Reply
    • The safari browser doesn’t recognize the ESP… Can you use chrome instead?
      You can’t have GPIO 0 connected to GND when you power your ESP. Otherwise your ESP goes into flash mode and you can’t upload your scripts…

      Reply
  80. Mr. Santos,
    Your demos have really helped me to understand the way the ESP8266 works.
    I have a problem though,
    each time I click “save to esp”, it waits a while , then i get “waiting answer from esp-timeout reached,send aborted”
    what do i do?
    the GP10-0 pin is left open.

    Reply
    • Hi Darius,
      Did the flash process worked? Did you see the green arrow in the NodeMCU flasher?
      Sounds like your ESP is still in flash mode or busy doing something else.
      Can you restart your ESP with GPIO 0 disconnected or connected to VCC?

      Reply
  81. I’ll try again, I’ve been using this script on one of your general purpose wifi board 4x.
    I edited the script to use 4 relays. Currently I’m using tmr.delay as a timer between on and off. Here’s a sample of the script: local _on,_off = “”,””
    if(_GET.pin == “ON1”)then time=900000000;
    gpio.write(led1, gpio.HIGH);
    tmr.delay(time)
    –elseif(_GET.pin == “OFF1”)then
    gpio.write(led1, gpio.LOW);
    –elseif(_GET.pin == “ON2”)then
    gpio.write(led2, gpio.HIGH);
    tmr.delay(time)…………..

    It’s not ideal, because I’d like to put a interupt in a loop.
    Ive tried “i=0
    while i<= 900000000 do
    i=i+1
    end "
    but this doesn't seem to work, I'm hoping you can help.

    Bill

    Reply
  82. Hey Rui, I’ve been working on expanding on your project, that will control gpio pins via wifi. The program you supplied works fine but I wanted to experiment and maybe expand it.. My first issue was that I couldn’t see the small buttons well on my cell phone. So to start I studied up a bit on HTML and CSS, and added a CSS style of size(width and height), and font size within the HTML button element. Those worked (yay). So then I thought “hey how about colored buttons”, green for on, and red for off. When I added that, the ESPlorer compiler error-ed with “unexpected symbol” (with no real indication of where except “near” the line I was in (duh)). I’ve been stuck on this for a while. I’ve tried escaping special characters all different ways without any luck. I have found if I remove one of the attributes in the style (either width and height, or font size), and replace it with background-color, it works, but I can’t get all attributes to go.
    When I add “background-color:green” to the css style It won’t compile. However if I replace one of the other attributes with it, it will compile. I might also mention that the same code written in an HTML editor (without the escaped characters) works fine when viewed in a browser. Since I’ve done most of my programing in assembly language, I am like a fish out of water when it comes to the various scripting languages prevalent today. I’m sure I’m missing something in my quest to understand all the different syntax/coding involved. Sadly I find most of the lua tutorials a bit hard to follow. Can you tell me where I am going wrong?

    Reply
    • The buf uses ” as in “html stuff” so you cannot use ” in your html code change ” in html to use ‘ instead. Eg buf “html stuff ‘my function’ ” I used onmousedown function I also had same error , I am trying to make button momentary to activate led only when pressed.

      Reply
      • Hi Firepower, I’d think a momentary output could be acomplished in the sketch in the 8266. I’ve done this with a bluetooth/arduino setup to control my garage door and lights, quite successfully using MIT’s App inventor to create the app for the android phone. In as far as the HTML code goes, I understand what you say; the code is simply building a string to be sent to the calling browser. The double quotes should be escaped out using the “\” to do so. I have no issues with ” size width:150px;height150px; or adding to that” font-size:100″ The trouble comes when adding “background-color:(and color here)”. As stated if I REPLACE one of the attributes with the background color attribute it loads and works; but I can’t put all 3 in (ie size, font size and color).

        Reply
      • My sketch is exactly like Rui’s with the exception of the building of the HTML string in the buffer. I expanded Rui’s original lines as such:

        buf = buf..”Switch 1 On Off“;
        buf = buf..”Switch 2 On Off“;

        This works. But when I add another css style element, such as “background-color:green; It won’t compile. If I replace one of the attributes with it, it compiles.

        Reply
          • “Futterama says
            November 3, 2015 at 5:41 pm Hi John. Your code works fine on my ESP-01 with the following in the buffer:
            http://pastebin.com/RXn8SEcn
            Hi Futterama, and thanks for the response. That is really odd because that’s exactly how I did it, and it didn’t work. It brings a couple questions to mind. You didn’t say; are you uploading with ESPlorer using the “save to ESP” button. If so what version? I’m using V0.2.0-rc2 on wndows7 on a Lenovo laptop. I’m thinking of loading ESPlorer on my desktop using windows 10 and duplicating the effort to see what happens. perhaps I have a bad load of ESPlorer. I must admit also that I got this Lenovo 2nd hand and it does do some quirky things even though it’s been wiped and restored. I’m just wondering if the character set is exactly the same?? IDK just grasping at straws at this point. Last night I also tried increasing the size of the font describing the buttons like’ <p style= \"font-size:90px\"………' and that blew up too; I could have sworn in my aging mind that I had that working in a previous write. As a good friend of mine once said "I'm as confused as a newborn baby in a topless bar"…….cheers

          • “Futterama says
            November 3, 2015 at 5:41 pm Hi John. Your code works fine on my ESP-01 with the following in the buffer:
            http://pastebin.com/RXn8SEcn
            Hi Futterama, and all viewing. Ok I’ve taken your rendition that worked on your machine; pasted it in replacement of the lines in question in mine. Still no go so I must take from that it’s not a typo, something very weird going on. But oddly the error changed (although the code looks the same to the human eye). The error this time was stdin:1: function arguments expected near ‘;’w(…….I think my next step will be to put it all over on the desktop and see what happens under Win10 environment and or fresh load of ESPlorer. Stay tuned.

          • Futterama and all, I’ve tried again this time on the desktop with a fresh load of ESPlorer on Windows10. Just to make sure I wasn’t doing any “subliminal” typos, I copied and pasted your code in place of the buffer building code that was there. It still failed! If you’d like to see the feedback from the upload it’s here:

            http://pastebin.com/7kneMbCE If you see something in there that I don’t I’d appreciate feedback, especially if it’s something stupid I’m doing/not doing: for now I’m stumped.

          • Very interesting, it would appear that there is a bug in the later ESPlorer version I’m using. I’m not sure how to get this information back to the ESPlorer developement team, perhaps Rui can assist with that.

          • Hi John. Usually you would go to the github page to find a way there to report a bug so I took a look. I found this reported issue:
            https://github.com/4refr0nt/ESPlorer/issues/11
            The solution given here, also works for your code, at least for me.
            In ESPlorer 0.2.0-rc2, go to the “Settings” tab, and check “Turbo Mode” under “Send”.
            Make sure you use the “Save to ESP” button and not “Send to ESP”.
            Apparently, the ESPlorer v0.1 I used, will also fail if I use “Send to ESP” and it has “Turbo Mode” enabled by default.

          • Thanks for that Futterama, I’ll try your suggestion next opportunity. I will be the first to admit that I’m somewhat fuzzy as to how the parts go together. Is each sketch (arduino term) (program, to my old training lol) compiled as it’s being uploaded? Or at all for that matter. As I understand from reading up on lua, it can operate in a command line mode as well as compiled code(?) There are different upload buttons in ESPlorer, I’ve not seen a good explaination of them, and only seen enough information to get started with it. Do you know of a good tutorial for it; and nodemcu for that matter? If I understand correctly nodemcu is residing on the 8266 as an OS, I assume to process all the nodemcu statements, does it have anything to do with the compilation? I don’t think the report on block comments applies here because this issue is not with a commenting function. Here, as I see it, we are building a string to be passed to the browser, not commenting. In the compiling something is getting misinterpreted within the string as a control or special character. I do realize there are double brackets in the feedback, but these are applied by the process, not the author which adds to my confusion, is this an echo of what was sent to the 8266/nodemcu, or a response from it? I hope we get some improved documentation on all this, I thought using nodemcu would be a better way to go than the Arduino IDE, now I’m not so sure.

          • …..and after all that being said Futterama, I tried your workaround and indeed it worked! and a big thanks and click of the glass for that one! So apparently the issue is at least related to the report you sited to be sure. You’ve been a great help, thanks for the “steering” 🙂 Hopefully this will get some “air time” and help others, I’d love to see some more in depth training on ESPlorer and nodemcu.

    • John,
      Can you send me an example of your sketch? I’m working on that too.
      Maybe between te two of us we can figure it out. I know with esplorer I get errors where with lualoader I don’t. I have queried Rui a couple of time on loops but haven’t seen any responses, maybe he’s on vacation.

      Bill

      Reply
  83. Ok I “think” I’ve posted the code on Pastebin.com.( never used that before) Named it “Rui’s code modified by John” I did it before creating an account, so not sure if it went. I’d appreciate feed back if it can be seen or not. Thanks all.

    Reply
  84. Futterama just as an update I did find that even though the buttons displayed as hoped for I did find that the program occasionally hangs, if you try to change states too fast. For example tap on and off close together and it locks up and needs to be reset. If I wait about 2 seconds between sends, it seems to keep going. If this were to be used in a true remote situation the 8266 could lock up and have to have a local reset to work again. Kinda defeats the purpose eh?

    Reply
    • John, I have the same problem. I thought it was because of the weak power supplied by the FTDI, but even with an external supply of 3.3V, the program hangs and gets disconnected when I try to push the buttons consecutively. The firmware is still running good, but the network connections drops. I’m no LUA or HTML expert (good with C and Python), so I can’t really tell if it’s the code. I think I’ll give a try to what Rajesh says on March 5, 2015 at 3:45 am.

      Reply
    • Send the commands:
      file.format()
      node.restart()

      Try to re-upload the script and you should be fine.
      That error happens when you try to upload the same script multiple times.

      Reply
  85. Dear Rui and fellow Coders,
    Many thanks for a wonderful knowledge base on ESP8266.
    All above steps worked fine.
    I will come back to bother you again when Mr. Murphy steps in.

    Regards,

    Reply
  86. Hi Rui , I’m using esp8266 , I’v already flash it by using node mcu flash master . Now I want to make a TCP server to store some data or string and that can be acceseble by an android aps. Now please help me by giving the require code to make this server by lua script. . I’m very new in network communication as well as in coding. So please help me.

    Reply
  87. I have tried by coding the following in esplorer

    print(“ESP8266 Server”)
    wifi.setmode(wifi.STATIONAP);
    wifi.ap.config({ssid=”test”,pwd=”12345678″});
    print(“Server IP Address:”,wifi.ap.getip())
    sv=net.createServer(net.TCP, 60)
    sv:listen(8080,function(c)
    c:on(“receive”, function(c, pl) print(pl) end)
    c:send(“hellow world”)
    end)
    but it does not work . So please help me by giving the require code.

    Reply
    • If you delete these two lines of code from my example:
      wifi.setmode(wifi.STATION)
      wifi.sta.config(“YOUR_NETWORK_NAME”,”YOUR_NETWORK_PASSWORD”)

      And instead you use these two lines of code:
      wifi.setmode(wifi.SOFTAP);
      wifi.ap.config({ssid=”test”,pwd=”12345678″});

      you should be able to use the esp as an AP.
      I hope this helps,
      Rui

      Reply
  88. Works great but seem to disconnect after a min or two and I have to reset to reconnect. If I send pings it doesnt disconnect. I see other people have had a similar issue. Any idea what the problem is?

    Reply
  89. thanks rui, let me know if the following code I run in ESPLORER , then the server data can be read by an android aps or not?? actually it is a group project so I want to confirm that whether my program is correct or not? And please give a guide if I follow this procedure where is my mistake.

    print(“ESP8266 Server”)
    wifi.setmode(wifi.SOFTAP);
    wifi.ap.config({ssid=”test”,pwd=”12345678″});
    print(“Server IP Address:”,wifi.ap.getip())
    sv=net.createServer(net.TCP, 60)
    sv:listen(8080,function(c)
    c:on(“receive”, function(c, pl) print(pl) end)
    c:send(“hello world”)
    end)
    after successfully run of this code, is “hello world” term is readable by an android aps? If i connect in this procedure ..in android phone 1st connect the AP “test” and by putting the IP and Port 8080 in android aps? Please help me..please.

    Reply
    • Oh, man!
      I forgot to eliminate the ”
      The blog chopped most of the code because of them….

      Another try. I’ve replaced all the double ”
      and put single ‘
      instead. I hope you’ll understand anyway.
      Good luck:


      end
      end
      buf = buf..’HTTP/1.1 200 OK\n\n’;
      buf= buf..”,
      buf = buf..”;
      buf = buf..’…..
      etc…

      Reply
  90. Third try out!
    Now I’ve replaced all the double ”
    and all single ‘
    by #
    Reverse these changes before compiling.


    end
    end
    buf = buf..#HTTP/1.1 200 OK\n\n#;
    buf= buf..##;
    buf = buf..##;
    buf = buf..#…..
    etc…

    Reply
  91. Puaj!
    Ha ha ha!
    I don’t know what else should I try…
    Perhaps it’s time to move this blog to another site
    Any way, thanks Rui for your excellent work!!

    Reply
  92. I have my first NodeMCU 0.9.5 build 20150318 powered by Lua 5.1.4 running fine a webserver for months.
    One day I hade some time to play with it. I ended up with his.

    —from,ESPlorer v0.2.0-rc2 by 4refr0nt—
    NodeMCU 0.9.5 build 20150318 powered by Lua 5.1.4
    set up wifi mode
    Waiting answer from ESP – Timeout reached. Command aborted.Waiting answer from ESP – Timeout reached. Command aborted.
    —-from my log—
    We save known file init.lua
    Try to saving file init.lua …
    Save file init.lua: Success.
    FileSaveESP: Try to save file to ESP…
    DataSender: start “Smart Mode”
    FileSaveESP: Starting…
    sending:file.remove(“init.lua”);
    Operation done. Duration = 3077 ms
    Waiting answer from ESP – Timeout reached. Command aborted.

    I have tried many things to breath life into my little MCU.
    I hope some one understand my English and have an idea to concur this error. It seems to me that the file-system is broken.

    Reply
  93. Hi Rui,

    A project that I’m doing uses an ESP8266 ESP-05 module , and I have attached a commercial WiFi 3dB gain antenna to it. I am using basic AT commands via a USB to serial converter to assign functions to it such as renaming the “SSID” WiFi broadcast name.
    Intend to run it as a standalone webserver running just off a rechargable 3.7V 5600mAH lithium battery via a 3.3V regulator chip as the power supply.
    To save the battery, is it possible to program it via an Arduino , or via GIO hardware lets say to run only 8 hours a day during business hours instead of 24/7?
    If a user of a smartphone saw the renamed SSID as “free-WiFi-access”, can it then automatically open the web-browser ESP8266 homepage when he or she clicks on it, or do you have to manually type in the internal IP 192.168…..address on the browser’s search tool bar to accomplish this?
    Cheers then
    Paul

    Reply
  94. Hi Rui,

    Thank you so much for the great tutorials and websites. I am trying to establish a telnet server on my ESP and then connect to it through a telnet client on another device (ideally my computer). I wanted to know if there was a way to verify that I have established a telnet server on the ESP and verify that I have connected the client to the server. So far, I have used LuaLoader to upload the following code:
    _____________________________________________________________________________________
    — Simple demonstration how to use telnet server
    s=net.createServer(net.TCP,180)
    s:listen(2323,function(c)
    function s_output(str)
    if(c~=nil)
    then c:send(str)
    end
    end
    node.output(s_output, 0)
    — re-direct output to function s_ouput.
    c:on(“receive”,function(c,l)
    node.input(l)
    –like pcall(loadstring(l)), will support multiple separate lines
    end)
    c:on(“disconnection”,function(c)
    node.output(nil)
    –unregistered redirect the output function, the output will goes to the serial communication
    end)
    print(“Hello world”)
    end)
    _________________________________________________________________________________________
    After deleting the other scripts I had saved on the ESP, I was able to get rid of the “only one tcp server allowed” error. Now, I think the server is established, but I’m not sure what steps to take to a) verify the server exists and b) connect to the server with a telnet client from my computer.

    Could you share some of your wisdom with me? (I am very new to this)

    Thank you so much for the help,
    Ben

    Reply
  95. Hi i try ti make a web server with this code

    buf = buf..””;
    buf = buf..””;
    buf = buf..” MODULO WIFI “;
    buf = buf..”Analogo ON/OFF ON OFF“;
    buf = buf..”Digital ON/OFF ON OFF“;
    buf = buf..”Respuesta del Bombillo”;
    buf = buf..””;
    buf = buf..”function ON() {document.getElementById(“BOM”).innerHTML = “ON”;}”;
    buf = buf..”function OFF() {document.getElementById(“BOM”).innerHTML = “OFF”;}”;
    buf = buf..”

    Todos los derechos reservados ® 2016. Diseñado Carlos Roldan

    “;
    buf = buf..””;
    buf = buf..””;

    but the tool show me a error

    > PANIC: unprotected error in call to Lua API (init.lua:39: attempt to call global ‘BOM’ (a nil value))

    please help me

    Reply
  96. Hi Rui,
    Thank you for this tutorial ! very interesting !
    I followed your webpage instructions to flash esp8266: no problem for that, it works well with the green tick at the end of the procedure. But when I try to download the init.lua file with ESPlorer after change the ssid and password of my router,set up 9600 bautrate, then I clicked “save to ESP” button,wait for a while,I got that message “waiting answer from ESP – timeout reached,send abort.” For information, I am using a “FT232RL FTDI Serials Adapter Module Mini Port f. Arduino USB to TTL 3.3V 5.5V GM”. I connected esp8266 to converter exactely as in your picture above.

    How can I do to solve this problem ?

    Below are what I see in the serial monitor:
    Logging enable
    Load saved settings…
    Set new color theme: Success.
    Load saved settings: DONE.
    Snippets (LUA): loading…
    Snippets (LUA) load: Success.
    Scan system…
    Could not find any serial port. Please, connect device and ReScan
    Scan done.
    Try to open file init.lua
    File name: C:\Echange Ordi salon\02 WIFI ESP8266 Web Server\init.lua
    Try to load file init.lua
    Loading init.lua: Success.
    Open “init.lua”: Success.
    Scan system…
    found last saved serial port COM5
    Scan done.
    Serial port COM5 save as default.
    Baud rate 9600 save as default.
    Try to open port COM5, baud 9600, 8N1
    Open port COM5 – Success.
    We save known file init.lua
    Try to saving file init.lua …
    Save file init.lua: Success.
    FileSaveESP: Try to save file to ESP…
    FileSaveESP-Turbo: Try to save file to ESP in Turbo Mode…
    DataTurboSender: start “Smart Mode”
    FileSaveESP-Turbo: Starting…
    send:FILE=”init.lua” file.remove(FILE) file.open(FILE,”w+”) uart.setup(0,9600,8,0,1,0)
    DataSender: Done. Duration = 3157 ms
    SendToESP: Waiting answer from ESP – Timeout reached. Send aborted.
    ESP SAFE: try to close file anyway for ESP filesystem good health
    send:file.close();

    Reply
      • Hi Rui,
        Thank you for your message. I have, last week end, solved this issue….By using an external power supply!!! It works perfectly !
        Thank you for this tutorial. The next step will be to replace led by relays and to trigger them from my home automation software (with HTTP command)!
        I have a question: do you know if it is possible to set up a static IP by modification of the init.lua file? I have found that :
        SSID = “YOUR SSID”
        PW = “YOUR SSID PASSWORD”
        IPADR = “192.168.0.126” //Requested static IP address for the ESP
        IPROUTER = “192.168.0.1” // IP address for the Wifi router
        wifi.setmode(wifi.STATION)
        wifi.sta.setip({ip=IPADR,netmask=”255.255.255.0″,gateway=IPROUTER})
        wifi.sta.config(SSID,PW)

        Could I just remove this (in your init file):
        wifi.setmode(wifi.STATION)
        wifi.sta.config(“YOUR_NETWORK_NAME”,”YOUR_NETWORK_PASSWORD”)
        print(wifi.sta.getip())

        And add what I have found in the init.lua file ?

        Could it work ?

        Reply
        • Hi Rui!
          Hope you are doing well. I have just realized that you have not make a comment on my request. Could you havea look to my question?
          Thank you for your help!
          Philippe

          Reply
    • You can do a if statement in your ESP8266 code that checks if your ESP still has an IP address.
      If it returns true it continues connected, if it returns false you try to reconnect your ESP to your router again

      Reply
  97. Thank you for this tutorial it works for me 🙂
    But I have a question, I wish to control it with my android phone. I downloaded the “arduino wifi control” app on playstore which normally allow to control LEDs like in the tutorial.
    But I have a “connection error” message, does it work for you ??

    Thanks for your help !

    Reply
  98. I am using your code, your schematic, I’ve checked it over for two days.
    Whe I plug in the FTDIit streams garbage. If I remove the wiring for the LED’s, particularly to GPIO’s and reboot the module, it will work. It connects to the network and I get a webpage in my browser. I then connect the wiring for the LED’s again, without removing power, and it works! But if I reboot the module again (unplug the FTDI) then plug it back in again, the 8622 will stream garbage again. Changing the Baud rate doesn’t make a difference.

    Reply
  99. First off GREAT article and for once it worked first time 🙂

    That said I was wondering if you could help me understand one thing

    led1 = 3
    led2 = 4
    led3 = 5
    led4 = 6
    led5 = 7

    What is 3 and what is 4? Pins up from Gnd?
    If I want to map to GPIO12, GPIO13, and GPIO14 what # would I use 8, 9, and 10 or 31, 21, and 41 or what?

    TIA

    Reply
    • Just wanted to chime in and say I was able to just use 5, 6, and 7 and it auto mapped to GPIO12, 13, and 14 and worked perfectly. I have a try colored LED and just by expanding your HTML code I can turn on and off all 5 LED/Colors [the initial 3/4 Red/Blue, and my 3 color RGB LED] I am a happy camper! Thank you!

      Reply
  100. Hello
    I have a problem
    I am configuring the IP as web server, but I have the following configuration
    conn:send(“”);
    conn:send(“”);
    conn:send(“SSID”);
    conn:send(“PASS”);
    conn:send(“IP address”);
    conn:send(“Netmask”);
    conn:send(“IP gateway”);
    conn:send(“”);
    conn:send(“”);
    conn:send(“”);
    conn:send(“”);
    when I give you to connect
    the sends the following parameters
    /?ssid=1&pass=2&add=3&mask=4&gate=5
    as I receive these parameters and store them in variables
    thank you very much

    Reply
  101. hi. ihave save the code to the esp, but unfortunately i cant see the ip adress, how did u restart the esp? and which serial monitor to watch? sorry im new to ESPlorer.

    Reply
  102. Hi guys, I modified the code to control 4 outputs in standby mode without using an external wifi. i used arduino IDE for esp8266.
    To control lamps, connected in wifi “luminaria” use the password “1234567890” and then 192.168.4.1.

    #include
    #include
    #include

    const char *ssid = “luminaria”;
    const char *password = “1234567890”;

    ; //
    WiFiServer server(80);

    void setup() {
    Serial.begin(115200);
    delay(10);
    pinMode(5, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(0, OUTPUT);
    pinMode(14, OUTPUT);
    digitalWrite(5, LOW);
    digitalWrite(4, LOW);
    digitalWrite(0, LOW);
    digitalWrite(14, LOW);

    // Connect to WiFi network
    Serial.println();
    Serial.print(“Configuring access point…”);
    /* You can remove the password parameter if you want the AP to be open. */
    WiFi.softAP(ssid, password);

    IPAddress myIP = WiFi.softAPIP();
    Serial.print(“AP IP address: “);
    Serial.println(myIP);
    Serial.println(“HTTP server started”);
    server.begin();

    // Start the server

    }

    void loop() {
    // Check if a client has connected
    WiFiClient client = server.available();
    if (!client) {
    return;
    }

    // Wait until the client sends some data
    Serial.println(“new client”);
    while(!client.available()){
    delay(1);
    }

    // Read the first line of the request
    String request = client.readStringUntil(‘\r’);
    Serial.println(request);
    client.flush();

    // Match the request

    if (request.indexOf(“/light1on”) > 0) {
    digitalWrite(5, HIGH);

    }
    if (request.indexOf(“/light1off”) >0) {
    digitalWrite(5, LOW);

    }

    if (request.indexOf(“/light2on”) > 0) {
    digitalWrite(4, HIGH);

    }
    if (request.indexOf(“/light2off”) >0) {
    digitalWrite(4, LOW);

    }
    if (request.indexOf(“/light3on”) >0) {
    digitalWrite(0, HIGH);

    }
    if (request.indexOf(“/light3off”) > 0) {
    digitalWrite(0, LOW);

    }
    if (request.indexOf(“/light4on”) > 0) {
    digitalWrite(14, HIGH);

    }
    if (request.indexOf(“/light4off”) > 0) {
    digitalWrite(14, LOW);

    }
    // Set ledPin according to the request
    //digitalWrite(ledPin, value);

    // Return the response
    client.println(“HTTP/1.1 200 OK”);
    client.println(“Content-Type: text/html”);
    client.println(“”); // do not forget this one
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(” CONTROLE DE LAMPARA REMOTO WIFI “);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“LAMPADA1”);
    client.println(“ LIGA “);
    client.println(“ DESLIGA “);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“LAMPADA2”);
    client.println(“ LIGA “);
    client.println(“ DESLIGA “);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“LAMPADA3”);
    client.println(“ LIGA “);
    client.println(“ DESLIGA “);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“LAMAPDA4”);
    client.println(“ LIGA “);
    client.println(“ DESLIGA “);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    client.println(“”);
    if (digitalRead(5))
    {
    client.print(“LAMPADA 1 ON”);

    }
    else
    {
    client.print(“LAMPADA 1 OFF “);

    }

    client.println(“”);

    if (digitalRead(4))
    {
    client.print(“LAMPADA 2 ON”);

    }
    else
    {

    client.print(“LAMPADA 2 OFF”);

    }
    client.println(“”);

    client.println(“”);

    if (digitalRead(0))

    {
    client.print(“LAMPADA 3 ON”);

    }

    else

    {
    client.print(“LAMPADA 3 OFF”);
    }

    if (digitalRead(14))

    {

    client.print(“LAMPADA 4 ON”);

    }

    else

    {

    client.print(“LAMPADA 4 OFF”);

    }

    client.println(“”);

    client.println(“”);

    client.println(“”);
    client.println(“”);
    delay(1);
    Serial.println(“Client disonnected”);
    Serial.println(“”);

    }

    Reply
  103. Hello really good post with the right information on, I have been following all the steeps one by one and when I check all the devices connected through my router, expecting find my ESP, it is not there.. on ESplorer I got this after OPEN THE PORT
    Communication with MCU…
    ((((Got answer! AutoDetect firmware…
    Communication with MCU established.
    Can’t autodetect firmware, because proper answer not received (may be unknown firmware).
    Please, reset module or continue.))))

    I think that I am missing one steep or doing something wrong!!
    I would appreciate any answer
    thanks

    Reply
  104. Hi Rui, I just got my ESp8266 modules they have 4megabit ram. which firmware should should I update to. I want make a garage door opener and use my cell phone to open the door.

    Reply
  105. I really like this idea. I am building a home automation system with arduino and esp8266. How can I relay the data from the web server to my arduino so I can control my relays (5V)?

    Reply
  106. I’m facing the problem of reliability, the Nodemc fails to give response for “http Get” requests after some time and works fine if we reset it.

    Reply
  107. Hi
    Nice Turtorial
    I have a problem:
    every time when i wanna try to connect my smartphone to the ESP wit the Direct IP.
    say my smartphone to me Safari cant open the network adress cause networkeconnection interrunpted.
    I hope you Can help me 🙂
    PS: My Computer us same WIFI as ESP and mobilephone and my computer can open the IP with Firefox and show me the webpage.

    Sorry for bad English 🙂

    THX Bösi

    Reply
  108. Thanks for posting this. I used your code as a framework for a device that I built to power cycle my connection to electric utility Smart Meter. I have a Raspberry Pi that monitors all of my lights, as well as my power consumption. If the Raspberry Pi does not get a reading from the Smart Meter, it sends a message to the ESP8266 to power cycle the connection to the Smart Meter. The ESP8266 turns off the power, waits 12 seconds and turns it back on. It works great – Thanks.

    Reply
  109. How to make same web server using AT commands for ESP-01 module. What other binaries will be required. And how can I make my module to do same work again everytime I power on module (just like init.lua for NodeMCU)

    Reply
  110. Newbie to 8266 stuff, I’m an old guy, retired from an IT career. But servers and networking hardware and OS stuff was my forte. Did a little programming, but mostly systems stuff. So your book was a good read. I’m in the process of learning to use the NodeMCU 8266 and you have been a big help to me in getting going! Thx.
    Bill

    Reply
  111. Hi, I have bought your book and am using it with a lot of fun. Now I want to make my ESP an Access Point with a web-server written in LUA. Do you have any code examples ? When i define ESP as SOFTAP and define a web server I can see requests comming in but I do not get any response on the screen of the sending device.

    Looking forward to a response.

    Br,

    Reply
    • Hi Arno,
      Thanks for your support. Please replace the do the following:
      wifi.setmode(wifi.STATION)
      wifi.sta.config(“YOUR_NETWORK NAME”,”YOUR_NETWORK_PASSWORD”)

      With this to add a AP in Lua:
      wifi.setmode(wifi.SOFTAP)
      wifi.ap.config({ssid=”test”,pwd=”12345678″})

      I hope this helps,
      Rui

      Reply
  112. Which development board shall i use for this web server ?
    WeMos D1 mini or ESP8266 NodeMcu by Lolin ?

    Rui, is there any difference in Lua script if we use ESP8266-12 except for that GPIO pin configuration ?

    Reply
  113. Hello! Nice work!

    Two questions….

    1) why you use GET instead of POST?

    2) how you deal with GET favicon.ico? In sample it is not a huge problem but you interact twice with bowser in one so called “session”…

    Best regards
    MvincM

    Reply
  114. Hi Rui,

    Very nice tutorials with excellent stuff , Can you please tell how shall i do following add-on features:
    1. Security : Add more security feature in this web server so that no other person can use the same IP address and have control over my devices. Can you please add the lua code for prompting username and pwd everytime anyone opens the IP address and the page opens only if it matches.

    2. Lua code for controlling LDR and humidity sensor through ADC pins of ESP-12.

    Reply
  115. I tried above and it works perfectly ok.
    I just had one problem i can access that IP over my WiFi or local network only not over internet from anywhere (mobile data etc.).
    How can i do that , Please help.

    Reply
  116. I modified the buttons a bit on the website, changed the HTML code
    does anyone know upload it in my Node MCU
    a lot of HTML syntaxes give errors in a Arduino IDE if I port by writing client.print(“Html code line by line”)
    Can someone help me out ?

    Reply
  117. Rui, this is an excellent project! Everything worked perfectly for me. As I read through the comments, everyone seems to be asking for simple modifications to your basic example. I have found simple introductory projects like this all over the cloud, but nothing substantial. I believe everyone is missing the obvious question: “How do I learn to do this myself?” In other words, where can I find documentation that describes the networking functions in LUA for NODEMCU? Thank you for your support.

    Reply
    • @manikandan you can send the command print(wifi.sta.getip()) to your ESP, it should return the IP address. Other ways, you could query your router for connections. Or at your pc you could download and use a program I’ve come to love called “whosonmywifi” which when running monitors and updates all connections to your wifi router. Hope that helps.

      Reply
  118. Hi Rui,

    I tried the webserver-Demo with a nodeMCU-Firmware created by
    https://nodemcu-build.com. I included all modules for WiFi and HTTP that are nescessary

    The board connects to my router and gets an IP-adress but the browser reports an error.

    If I use the script under an older firmware NodeMCU 0.9.5 build 20150318 powered by Lua 5.1.4
    the script works and I can control the GPIOs through the website

    So something must have changed in how webservers are porgrammed with the newer firmware.
    Do oyu have time to update the demo-code?
    Or do you happen to know a link with a webserver-demo that works with the new firmwares?

    best regards

    Stefan

    This uses the SDK V2.0.0

    With this nodeMCU-Firmware

    Reply
  119. Hi Rui,

    How can we send the GPIO status to some site (Let’s say IFTTT) and simultaneously get my youtube channel subcribers and print it ?

    Thanks

    Reply
  120. Uploaded to a Lysignal ESP8266-12E single relay board …. perfect ! GPIO 5 is the onboard LED and GPIO4 is the relay.
    Thanks !

    Reply
  121. Really GREAT — the exact info with the exact amount of explanatory detail.
    Superb. Thank you so much for sharing !

    Reply
  122. Very good!
    I will start doing something similiar. The only difference is that the ESP8266 will be configured as an access point. In this way I will not need a external Wifi connection. The cell phone will be a ESPClient. Would you, please, tell what are the benefits of the Arduino IDE and the NodeMCU approaches.
    Keep up the good work.
    Cheers
    Paulo Dias

    Reply
  123. hello Rui,
    truly amazing tutorial website you got. thank you for sharing your knowledge.

    if I may ask, do you have tutorial on making multiple webpages for your esp8266 webserver ?
    it’s like putting the I/O buttons on one page and temperature reading on another page.

    appreciate your reply.

    thank you!

    Reply
    • Hi Richard.
      Thank you for suggestion.
      Unfortunately, at the moment, we don’t have any project related with that subject.
      We’ll add that to our future projects’ list.
      Regards,
      Sara 🙂

      Reply
  124. Hello Sir,
    Thank you for your great post. I wonder that can we add select option as on and off state time as minutes or seconds for make bilinking LEDs?

    Reply
  125. How to fix IP address in esp8266 web server code. I face load shedding problem every time power down and restore after 2 hour esp-01 rest and my ip address changes and very difficult to find again so plz solve my problem I am very thankfu to you.

    Reply
    • Hello Naeem!
      The most reliable way of assigning a fixed IP address to your ESP is using your router configurations.

      Are you familiar with MAC Addresses? Basically a MAC address is a unique identifier assigned to your ESP (or any network device). You can use a function to retrieve your ESP MAC address while using a WiFi

      Then, you login into your router dashboard (the router ip and login/pass are usually printed in the router label). You can assign a fixed IP address to your ESP MAC address, so it always has the same IP address.
      The steps to assign a fixed IP to a MAC address is very similar to all the routers.

      I don’t have any tutorials on that exact subject, but I hope that points you in the right direction.

      Reply
  126. Very nice article. If you make the ip address fixed, there will not be any need to check serial output for ip address and it can be used as a standalone esp

    Reply
    • Hi.
      That’s true. We’ll be publishing a tutorial on how to fix the ESP32 IP address very soon.
      Stay tuned.
      Regards,
      Sara 🙂

      Reply
  127. Hi. I love the weberver example !
    On my ESP6288 ESP-12E Board I had to do a modification in the code to make it work.
    (modify the GPI-O definition)
    I replaced “pinMode(output4, OUTPUT)” by “pinMode(D4, OUTPUT)” ;

    Reply
  128. I did everything like you detail here. Only my LED goes off when the web says on and on when off. I checked the NodeMCU pins with a scope and the pins voltage is 180 out with the display. What gives?

    Reply
    • Hi Phil.
      I noticed that in some ESP8266, GPIO 2 works the other way around. This means when you send a HIGH signal it turns off, and when you send a LOW signal it turns on.
      So, you can either change that in the code, or use any other GPIO.
      Regards,
      Sara 🙂

      Reply
    • Hi again.
      You can have several browsers displaying the web server at the same time.
      When a client makes a request, the ESP8266 sends the response and then closes the connection. As soon as the connection is close, it can receive a new request from other client.
      Regards,
      Sara 🙂

      Reply
  129. Hey 🙂 I did everything you said in the tutorial, but i get no response of the serial monitor. Do you have any recommendations, what error I could have made.
    Thanks!

    Reply
    • Hi Ursula.
      Have you entered your network credentials and set the Serial Monitor right baud rate?
      Are you getting any compilation error?
      Regards,
      Sara 🙂

      Reply
  130. I uploaded the code with an FTDI programmer on ESP8266-01, and after that I made the connections with the leds, but I can’t see the esp network anymore.

    Reply
  131. Rui I cannot connect to the ESP8266 my computer recognizes it but won’t let me in. All it says is No Internet, secured. It’s frustrating!!! Can you help me? Thanks Leo

    Reply
  132. I didn’t give you near enough information on the first comment I sent so here’s the rest. I’m running Widows 10 Pro Ver 1803. I can communicate with the ESP8266 manually but when I try to go WiFi it recognizes the ESP8266 but won’t let me connect to it. The message I get is No Internet, secured. If you can help me I would be grateful. Thanks, Leo

    Reply
  133. some error are ther when run the ip address of over nodeMCU
    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;}”);

    this line print in webpage

    Reply
    • Hi.
      There was an error displaying the code in our website.
      Please copy the code again, and everything should be working fine.
      Regards,
      Sara

      Reply
  134. I followed the Tutorial on building LEDs controlled from web server with Esp8266. I can communicate wirelessly with my ESP but, no led lights up when I click on a button of the web page.

    Reply
    • What do you mean by you “can communicate with the ESP” ?
      Do you receive the request information in the serial monitor.
      Are you getting any errors?

      Reply
      • Hi Sara. I mean I can access to the web page remotely (hosted in my ESP8266) through any device (smartphone or PC) via WiFi. I receive all information about the device who accessed to the web server in the serial monitor. I do not get any error.
        But when I click on any button to switch on my LED, no LED lights up. I think it could be due to the circuit mounted in my breadboard. How can you help me as I aslo want to know if circuit is well built as per the tutorial in order to see the any lights up.

        Reply
  135. Thank’s a lot for Yout help. After a lot of fustrating try’s with Your help I have made it, and now I will play whit a relay and will see what happens.
    Another time thank you

    Reply
  136. Hello Friends
    i need help
    am bigner
    i dont know code about Esp8266 wifi
    when i upload program then on serial monitor only dots will shows

    Reply
    • Hi.
      that error usually means that:
      – you’ve forgotten to enter your network credentials
      – you’ve entered the networks credentials incorrectly
      – you don’t have wi-fi connection; the ESP8266 can’t get wi-fi signal

      Please make sure that you’ve entered your network credentials correctly and that your ESP8266 board is relatively close to your router.
      Regards,
      Sara

      Reply
  137. Hello Sara Santos
    Create a web server using NodeMCU, I have the code in the NodeMCU compiled it well, but when uploading the error occurs
    serial.serialutil.SerialException: could not open port ‘COM7’: FileNotFoundError(2, ‘The system can not find the specified file.’, None, 2).

    Would you like help to solve it, please.

    Reply
    • Hi Ricardo.
      That error usually means that you haven’t selected the COM port before uploading the code.
      Select the COM port and try to upload the code again.
      Also, your ESP8266 may not be properly connected to your computer USB port.
      Regards,
      Sara

      Reply
  138. Hello;
    I have the module NodeMCU ESP8266ESPMOD FROM AI-THINKER, I have tried the code described above, I see many ………., when it says to press the RESTORE ESP8266 button, and the IP address of ESP will be displayed in The Monitor Series, where I find is a button, on the board?, I need a little help please.

    Reply
    • Hi again.
      When we say to press the ESP8266 RST button it is to restart the program that we we can see the IP address.
      With your board, the best way to restart is probably remove the 3.3V power supply and power up again while the Serial Monitor is opened.

      If you see many dots that usually happens when the ESP is not able to connect to the network. Please double-check that you’ve inserted your network credentials right and that the ESP8266 is relatively close to your router.
      Regards,
      Sara

      Reply
  139. Dear Sara, Rui,
    Thanks for this again wonderful tutorial.
    I used your code a base to set up a webserver using an ESP8266 to control how many times a day an irrigation shall starts. Works like a charm.
    I also added eeprom usage for storing the number – no frequent changes. Just in case of a power failure.
    However, how could I run the webserver and simultaneously set a GPIO at the correct time to start irrigation let’s say three times a day => every 8 hours. Can you help?
    Thx

    Reply
  140. Hi Sara and Rui,
    Just an hour ago I started with your tutorial and loaded in to a LoLin ESP.
    It was running the fist time, no problem what so ever.
    So thank you a lot for this great tutorial.
    Cheers,
    Gerard

    Reply
  141. Hi Rui, Hi Sara,
    This is Kyle from Texas and I am a novice at electronics. I have just started using arduino ide with a nodemcu 12-E and was getting frustrated until i found your site about the web server program and your instructions are the best I’ve found after digging through the web. I am trying out the different projects to help guide me to my goal. I would like to have a master 12-E run two slave 12-Es wirelessly. Could you make suggestions on how to send data from the master to the slaves to execute the same command simultaneously?
    Thank you,
    Kyle

    Reply
  142. It works nicely.
    Thank your for your efforts.

    I got some problems for expand this example to my work.
    I want to display float type data temperature value.

    looks like this method in your code :
    —– client.println(“GPIO 5 – State ” + output5State + “”)

    The temperature value must be changed to string type, but it is not so easy.
    Do you have any suggestion?

    Reply
  143. Hello! At the end of programming the ESP01 in the arduino IDE, the console hangs on ‘Performing a hard rest via RTS’. What can I do?
    Thanks.

    Reply
    • Hi.
      After that message, your code should be running normally.
      Disconnect GPIO0 from GND and see if you get something on the serial monitor.
      If you don’t, connect the CH_PD pin to GND and then to 3.3V again.
      I hope this helps.
      REgards,
      Sara

      Reply
  144. Hello Sara! Disconecting GPIO0 makes dots appearing in the serial monitor. When I connect CH_PD to GND and back to VCC the ESP01 logs in to my network and then I can see the webpage but, when I connect the leds it doesn’t log into the network.

    Reply
  145. I really liked this very much and suggest other to see this before they proceed to any project which includes esp8266 .
    Regarding this fun project can you tell me that if i can adjust this code to count the number of touches to the ON/OFF buttons there in web and pass that number to LCD display .

    Reply
  146. Code Confirmed to be working with Wemos D1 with no modifications other than SSID and Pass. (didn’t test with LEDs because i dont care too.)
    Best part is no FTDI flashing. although i do have a programmer.

    Thanks for the example code!

    Reply
  147. Hello
    Is it possible to change one of this button to push mode? (no switch mode).please send the code. I appreciate to answering. Best regards.

    Reply
    • Hi.
      Basically, you need to create a button with onmousedown event. Learn more here: https://www.w3schools.com/jsref/event_onmousedown.asp

      When you press the button, it should call a javascript function that makes a request on a certain URL.
      https://pastebin.com/KJJiubp1

      Then, the ESP32 should handle what happens when you receive a request on the /action?go=on and /action?go=off URLs

      I recommend following this tutorial instead:
      https://randomnerdtutorials.com/esp8266-web-server-spiffs-nodemcu/

      I hope this helps.
      Regards,
      Sara

      Reply
      • Hi SARA
        Thank you for your good nswer. But i apologize for my poor English and second one for my knowledge of code writing. I don’t have any knowledge about code writing but i was able to add several buttons to your project just by using (copy and paste) and it work fine.
        Now i need a code to change one of this buttons work like a push button. My mean is when I push that button the button goes on and when i abandon button it turn off immediately.
        Thank you again for your help and support. I appreciate to you. Best regards.

        Reply
  148. Wow! You guys are doing an amazing job. I started with Arduino a few months ago and I learned so much following your tutorials. I think I’m gonna read them all !!

    Reply
      • Actually, I had a small question about the code. Could you please develop a little the part you said “don’t change unless you know what you’re doing”. Could you tell me what the variables “header” and “c” doing exactly?

        char c = client.read(); // read a byte, then
        Serial.write(c); // print it out the serial monitor
        header += c;
        if (c == ‘\n’)…

        Thank you!

        Reply
  149. Hi,

    Thanks for the GREAT WORK that you do !

    I have an issue with an HTML synthax

    client.println(”

    text

    “);

    It gives me an error.

    Tried it with w3schools is does work !

    text

    Regards,
    Mario

    Reply
  150. Hi Sara,

    I see that my HTML line disapeared in my previous post ??? Here the line in [] marks.

    [ client.println(”

    text

    “); ]

    WaterPumpSense:188:50: error: expected ‘)’ before ‘color’

    Regards,
    Mario

    Reply
    • Hi.
      That error means that you’re missing a ‘)’ somewhere in the code or that you have any syntax error before the variable “color”.
      Regards,
      Sara

      Reply
      • Can anyone help me with that synthax ? or point me to a place where I could find that infos.

        Thanks in advance.

        MArio

        Reply
  151. Will this webserver run from an ESP in access point mode? Any tips on doing that?

    And can the ESP return the MAC address, or any other identifier of the devices that are connected to it?

    Reply
  152. Wouldn’t it be better to put the web page on as a separate file rather than holding it within the code?
    Though of course “Better” has a number of parameters, and I can see that it may be easier to do it this way: I can’t see how to get the code to change what the page displays if it is on its own file.

    Reply
  153. Web server project works great ! Thanks !
    I need more range; is there a way to connect multiple ESPs to relay control over longer distances ?

    Reply
  154. Rui

    In 2015 you said “The ESP8266 doesn’t support https…”

    I’d like my login and password change pages for my app to be encrypted. Has anything changed in the last 3 years?

    Reply
  155. First, bravo and thank you for this very clear tuto.
    I made it with an ES01-S.
    That works very well when the ESP01 is plug to my PC: I connect to the web server with sucessfull.
    But when I connect the ESP01 on a bread board with 2 led on GPIO0 and GPIO2, I can’t connect to the web server.
    Do you know why ?
    Thank you for your help

    Reply
      • Hi,
        When the ESP is supply by an adaptor (3.3V), when I write the ESP IP address in the browser on my smartphone, I have the message “Site inaccessible”.
        When the ESP is plug directly on my computer, all is good: I access to the web server directly from my smart phone
        Thank you for your help

        Reply
        • It may be a power issue.
          Upload a blinking LED sketch and see if you get it working with the external power supply. If not, it means somethings wrong with power.
          Regards,
          Sara

          Reply
          • I have check and no problem with the power. But I think have found the root cause: If the Led on the GPIO2 is plug on GND, the ESP01 can’t boot.
            I have reversed the led (- on GPIO, + on resistor->VCC) and that works.
            Of course you must adapt the code and send an OFF order for shine the led.
            Perhaps my experience will can help other members.
            Thank you for your support

  156. sir .. after uploading the code its not showing ip address on serial monitor its showing that connecting to ssid ..please fix my problem.. thank u …

    Reply
    • Hi Make sure that you’ve inserted the right ssid an password on the code, so that the ESP8266 can connect to your local network.
      Regards,
      Sara

      Reply
  157. Dear Sir,

    We open the web browser of local IP of ESP we see all stuff having buttons, but after clicking the Button adds in the url and goes to say “ESPlocalIP/5/on” so how could we see the same html page having buttons?

    Reply
  158. Hello

    I am using an ESP12-E (DOITING) and when trying to use this program through Arduini IDE, I am getting the message : LEAVING, HARD RESETTING via RTS Pin . So it does not work.

    I have followed exactly your procedure. The installed version of esp8266 by esp8266 community is: 2.7.4.

    Please help.

    Reply
    • Hi.
      That’s a normal message after uploading the code.
      Just press the on-board RST button, and it should start running the code.
      Regards,
      Sara

      Reply
  159. Hello, I have programmed the esp8266 with a tutorial to turn on the led and everything is fine
    but I would like if an esp8266 scheme + relay + 220v bulb is possible if possible I claim scheme because I am a newbie and I don’t want to burn something at home
    Thank you

    Reply
  160. Hi, everything works, thank you!

    My next step is trying to let a servo rotate when a file has been uploaded by a submit button. What would I have to change for this? I’m still quite new to this..

    Reply
  161. Hello, this is what i need for my Grage door 🙂 can you Tell me where you drop this in the Skript? Or can you send me the Code? Thanks
    Axel

    Reply
  162. Hello Sara !
    client.println(”

    string

    “);

    What could be the problem ? The IDE, gives this bug.

    error: unable to find string literal operator ‘operator””http’ with ‘const char [12]’, ‘unsigned int’ arguments

    Reply
  163. client.println(” <p <a h ref= “http:/ /192.168.0.122/” String </a </p “);

    I want to use a clickable link.

    I have distorted the original, I hope you’ve passed to …

    Reply
  164. Hi,Santos:

    I’m a new coder, and I can’t realize comment below:

    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:

    commet write two newline characters in a row stands up end of the client HTTP,
    but your code if-loop only one newline character, is your or me fault?

    Reply
  165. hello Rui,
    i added another LED to the connections and i’ve changed the code but the third LED is always on irrespective of switching the buttons. Please help me out

    Reply
  166. Hi everybody,

    I use a esp8266 to send data to a Fibaro HC2:

    #include <ESP8266WiFi.h>

    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) …

    WiFiClient client;
    if (client.connect(host, port))

    if (client.connected())
    { client.print(“POST /api/scenes/”+…

    It is running well.

    Now I want to send data to the device. (HC2 can send GET requests.)
    Can I start a webserver simultaneously ?
    perhaps only by adding

    WiFiServer server(80);

    WiFiClient clientX = server.available();
    if (clientX) { …

    if (header.indexOf(“GET …

    Thanks in advance!
    muc

    Reply
  167. I did everything as instructed and it worked perfectly. I used the phone and tried it on the computer for control.
    Why does the whole thing stop working a few days later? No code or circuit coneections were changed? The page says network change detected and page does not load, might this be a router setting issue or is the code designed that way? Thanks

    Reply
  168. Hi guys

    Ive created this sketch on the JAYCAR XC4411 Uno + ESP8266 Wifi.
    It compiles and uploads ok, and the webpage on the created server looks fine.
    I can send the photo of the board if required.
    For the life of me I cannot get any response on the leds on any Digital Pins on the board.
    I did get the onboard led to respond when I used GPIO 14 in the code, however.
    Have you any idea how to find the GPIO mapping to thw=e actual pins on the board..??

    Thank you so much for these projects. I have made a good many and they work well.

    Kind Regards
    Mel

    Reply
  169. Having fun with the esp8266 simple webserver turning on and off LED…. Nice!

    I was wondering…. is there a way to send and receive integer data from the D1mini using the client.println command? or does client.println only support sending “text” and send/receive binary data from the browser client?

    also – is there a way to connect to the esp8266 server from my iphone on the local network? I can access with PC browser…. ie. 192.168.1.230 but no luck with iphone…?

    thanks
    Scott

    Reply
  170. Hello,
    I cannot find the library “esp8266 by ESP8266 Community”.
    I did add the board manager URL “http://arduino.esp8266.com/stable/package_esp8266com_index.json” but I cannot find the mentioned library for the “ESP8266WiFi.h”

    Is the name changed or can I download it somewhere else?

    Reply
  171. hi, im trying to implement a better solution for the example program: blink, where i have a switch/button on the webserver and with body for temperature and humidity showing values from a dht11. how can i implement the button? can´t figure out this
    HTML part… pls help me 🙁

    Reply
  172. Hi! mr. Rui Santos, this tutorial really helpful, but how i can load my HTML file instead of writing alot of client.println
    Thanks.

    Reply
  173. Hi guys
    I´ve tried to compile the code and I get thefollowing error
    Traceback (most recent call last):
    File “C:\Users\jcase\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2/tools/elf2bin.py”, line 211, in
    sys.exit(main())
    File “C:\Users\jcase\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2/tools/elf2bin.py”, line 183, in main
    out=args.out, eboot=args.eboot, app=args.app))
    File “D:\obj\Windows-Release\37win32_Release\msi_python\zip_win32\cp850.py”, line 19, in encode
    UnicodeEncodeError: ‘charmap’ codec can’t encode character ‘\u2013’ in position 129: character maps to

    exit status 1

    Compilation error: exit status 1
    I did not find any hint where the problem may lay.Has anyone a suggestion?.
    I copied the posted code twice
    My board is ESP8266 -12e
    Thanks in advance

    Reply
      • Thank you very much for your prompter answer.I have repeated the procedure and takes this time the code not from the web page, but from the link you gave me. To no avail. I get the same error in the same positions. Other examples work perfectly

        Reply
        • Hi.
          I’m not sure what might be wrong.
          I’ve just compiled the code and it works just fine.
          Try downgrading your ESP8266 boards to version 3.0.1 (Tools > Board > Boards Manager and search for ESP8266).
          Regards,
          Sara

          Reply
          • I got the web server with two LEDS going using arduino ide a few month ago. I now get a python error attributable i think to <ESP8266WiFi.h>. I have looked on line an tried zeroing out preferences.txt but that didn’t solve. you walked me through a different problem last time (it turns out that the SSID has to be all lower case for some reason – thx). If you can suggest a fix i would be obliged.

            Compiling core…
            /Users/dclark/Library/Arduino15/packages/esp8266/tools/python/3.7.2-post1/python /Users/dclark/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/signing.py –mode header –publickey /private/var/folders/r1/t35d92d57tl4h_wqh4y1xj_5078cnn/T/.arduinoIDE-unsaved2022728-72403-743txu.sa4rg/sketch_aug28a/public.key –out /private/var/folders/r1/t35d92d57tl4h_wqh4y1xj_5078cnn/T/arduino-sketch-8236C593FC8AB2E14A5E82218B6DE0C9/core/Updater_Signing.h
            Using library ESP8266WiFi at version 1.0 in folder: /Users/myself/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi
            Compilation error: Error: 13 INTERNAL: fork/exec /Users/dclark/Library/Arduino15/packages/esp8266/tools/python/3.7.2-post1/python: no such file or directory

            you guys are great. i got the same error on a windows and a mac machine. when i removed libraries and re-installed 3.0.2 it compiles:
            https://forum.arduino.cc/t/arduino-2-0-rc-3-nodemcu-compile-cant-find-python3/946670/4

            there is so much more going on nowadays, libraries etc.

            please send link to donate button.

  174. I got the web server with two LEDS going using arduino ide a few month ago. I now get a python error attributable i think to <ESP8266WiFi.h>. I have looked on line an tried zeroing out preferences.txt but that didn’t solve. you walked me through a different problem last time (it turns out that the SSID has to be all lower case for some reason – thx). If you can suggest a fix i would be obliged.

    Compiling core…
    /Users/dclark/Library/Arduino15/packages/esp8266/tools/python/3.7.2-post1/python /Users/dclark/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/signing.py –mode header –publickey /private/var/folders/r1/t35d92d57tl4h_wqh4y1xj_5078cnn/T/.arduinoIDE-unsaved2022728-72403-743txu.sa4rg/sketch_aug28a/public.key –out /private/var/folders/r1/t35d92d57tl4h_wqh4y1xj_5078cnn/T/arduino-sketch-8236C593FC8AB2E14A5E82218B6DE0C9/core/Updater_Signing.h
    Using library ESP8266WiFi at version 1.0 in folder: /Users/dclark/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/libraries/ESP8266WiFi
    Compilation error: Error: 13 INTERNAL: fork/exec /Users/dclark/Library/Arduino15/packages/esp8266/tools/python/3.7.2-post1/python: no such file or directory

    Reply
      • I know! but it wouldn’t work unless I folded the SSID to all lower. It must be my EERO LAN management system.

        Yeah, I deleted the library, reloaded version 3 something and everything worked fine. I tried to post the link on Arduino.cc that had the fix. Maybe it didn’t show up.

        thanks much!

        Reply
  175. Hi Lara, tried to finalize th projact but it was failed.
    Upload was OK, but the end suprizing:

    ….Writing at 0x00030000… (100 %)
    Wrote 283152 bytes (207081 compressed) at 0x00000000 in 18.4 seconds (effective 122.8 kbit/s)…
    Hash of data verified.

    Leaving…
    Hard resetting via RTS pin…”
    Here it stacks the login to network doenst start as wrote in this project.
    My board is ESP12E (1.0)

    Reply
  176. Hello – Can anyone help with the more relays lets say 4 and if you only wanted one on at a time . if you selected another button one of 2 things should happen a lock out or a shut off of all so only 1 button is allowed to be on at any given time. How would you write this part of the code. i am a newbie to programing.
    Thanks ….kmc

    Reply
  177. Hello, I have several web servers based on this tutorial. I am trying to add input fields, and radio buttons. can you please show me an example? Thanks, your site here has helped me so much over the last few years.

    Reply
  178. Rui and Sara:

    Very nice, useful work.
    Thank you so much.

    Question:
    In the Lua script – what is the purpose of _on and _off ?
    They are declared but never used.

    I’m guessing they are left over from the development process.

    Thanks again !

    Reply
  179. Hallo I have done the example
    “Build an ESP8266 Web Server – Code and Schematics (NodeMCU)”
    It works fine and a have learned a lot of things.
    But one point I do not understand.

    // Connect to Wi-Fi network with SSID and password
    Serial.print(“Connecting to “); –> this and the next line is not printed??????
    Serial.println(ssid); –> not printed
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    //Serial.print(“Connecting to “); –> I have tested at this line –> the print was ok.
    //Serial.print(ssid);
    }

    Reply
    • Hi.
      After uploading the code to the board, open the Serial monitor. Then, reset the board by pressing the RST button so that it starts running the code from the start.
      When you open the Serial monitor, the board is probably already running the code, so you can’t see the first print statements.
      Regards,
      Sara

      Reply
      • Hallo Sara
        I have done it time bevor and onesmore now. –> Same result.
        For test I have reduced the Baudrate to 9600 Baud –> then the printout is ok.

        Is it a driver or a USB problem?

        best regards from Austria
        Roman Nachbauer

        Reply

Leave a Reply to Rui Santos 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.