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.
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.
4. Go to Tools > Board > Boards Manager…
5. Scroll down, select the ESP8266 board menu and install “esp8266 by ESP8266 Community”, as shown in the figure below.
6. Go to Tools > Board 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("");
}
}
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.
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.
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.
ESP8266 | FTDI programmer |
RX | TX |
TX | RX |
CH_PD | 3.3V |
GPIO 0 | GND |
VCC | 3.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:
- ESP8266 12-E – read Best ESP8266 Wi-Fi Development Boards
- 2x LEDs
- 2x Resistors (220 or 330 ohms should work just fine)
- Breadboard
- Jumper wires
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).
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).
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
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.
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.
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.
The LED state is also updated on the web page.
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:
- ESP8266 DHT Temperature and Humidity Web Server (Arduino IDE)
- ESP8266 DS18B20 Temperature Web Server (Arduino IDE)
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.
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.
Open the flasher that you just downloaded and a window should appear (as shown in the following figure).
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:
- ESP8266 12-E – read Best ESP8266 Wi-Fi Development Boards
- 2x LEDs
- 2x Resistors (220 or 330 ohms should work just fine)
- Breadboard
- Jumper wires
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.
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:
- Click here to download ESPlorer
- Unzip that folder
- Go to the dist folder (here’s the path: ESPlorer-master\ESPlorer\dist)
- Run ESPlorer.jar. It’s a JAVA program, so you need JAVA installed on your computer.
- Open the ESPlorer
You should see a window similar to the preceding Figure, follow these instructions to upload a LUA file:
- Connect your FTDI programmer to your computer
- Select your FTDI programmer port
- Press Open/Close
- Select NodeMCU+MicroPtyhon tab
- Create a new file called init.lua
- Press Save to ESP
Everything that you need to worry about or change is highlighted in red box.
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> <a href=\"?pin=OFF1\"><button>OFF</button></a></p>";
buf = buf.."<p>GPIO2 <a href=\"?pin=ON2\"><button>ON</button></a> <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)
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.
Our Most Popular ESP8266 Projects
If you like the ESP8266, you may also like:
- Home Automation Using ESP8266
- ESP8266 Wi-Fi Button – DIY Amazon Dash Button Clone
- ESP8266 Daily Task – Publish Temperature Readings to ThingSpeak
- ESP8266 Weather Forecaster
- Nextion Display with ESP8266 – Touchscreen User Interface for Node-RED
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
This really great Rui!
So much fun with the ESP.
Thanks for sharing.
You’re welcome Jaap,
I agree this module is really fun to play with. (But It can also be quite frustrating sometimes :))
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.
Your connections are not stable -get a new breadboard and spray it with Inox first check soldered joints
Try diffrent USBports
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.
Hi Chris,
You can only connect GPIO 0 to GND if you are flashing firmware to your ESP.
In normal usage either have GPIO 0 disconnected or connected to VCC. Otherwise you can’t run scripts and you can’t upload code to your ESP.
The only one tcp server allowed error occurs if you upload multiple scripts to your ESP that require the esp to launch a web server. If you restart your ESP that error should go away.
Hi Santos,
It is great helpful to me, Thank you so much.
You’re welcome Chris!
I made the similar connections as shown in http://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2015/02/ESP-web-server_bb.png
still I am facing the problem of while saving it to ESP :“waiting answer from ESP – timeout reached,send abort.”
How to resolve it?
You have to do those exact connections.
Can you try to read this troubleshooting guide?
https://randomnerdtutorials.com/esp8266-troubleshooting-guide/
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
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/
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.
I try to encourage people to use pastebin or gist by github, but It depends if they actually use it…
Thanks for the suggestion Alexandre!
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.
Hi. Don.
Are you following this tutorial: https://randomnerdtutorials.com/esp8266-ds18b20-temperature-sensor-web-server-with-arduino-ide/?
Regards,
Sara
Thank you for getting back so quickly! I found the problem and the problem is my lack of knowledge. I didn’t know that GPIO4 is D2 pin and GPIO2 is D4 pin. I now have a printout of all the pin layouts. Thanks again, I will be buying you book!
Hi Don.
You can learn more about the ESP8266 pinout in this guide: https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/
Thanks for supporting our work.
regards,
Sara
i am getting garbage values for IP of esp like ⸮EO|v
MM⸮4B<l⸮4:h⸮R
⸮N please help!Hi.
Make sure you have the right baud rate selected in the Serial Monitor.
Regards,
Sara
I love you man.After 1 day searching on web,I get what exactly i wanted.
Awesome! I’m glad you found it useful.
Have a nice day,
-Rui
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
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
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
Very nice demo. For easy breadboarding with ESP-01, you can try this breadboard friendly adapter: tindie.com/products/rajbex/esp8266-breadboard-adapter/
Thank you for sharing, that’s a nice adapter, but you can easily make your own with a stripboard and a few headers.
Hi Rui,
Is there any other “esp8266” alike,
that suporta more gpio ?
Tanks &Keep up with the food work 😉 !
…” good work “…
( Mobile phone keyboard 😉 )
Thank you pdias!
Hi pdias,
Thanks! There a few other options in the market like the ESP8266 ESP-03
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 🙂
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
You by not have probably seen the 12 version. Lots of ports.
I have one on the way, to check out.
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.
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”)
i want to connect usb webcam to arduino uno…..how??????????????
i want to connect usb webcam to arduino uno…..how??????????????
Hi manish,
you can’t connect a webcam to an arduino. You might want to take a look into a Raspberry Pi instead.
https://randomnerdtutorials.com/rpi
Thanks for asking,
Rui
I am having problem finding the Dist folder in ESPlorer file please help me!
Heya,
Is there anyway to have both a web server, and a pure TCIP socket connection as well using NodeMCU?
Hi Ash,
Do you mean having the ESP8266 acting as a http client and server at the same time?
Heya,
No. I want a simple socket connection so that I can use Putty/write an android socket app for it.
And also combine it with a web interface kinda thing .
Also, is it possible to add a password to the server? I think it should be, but I can’t seem to find the method anywhere.
Hello Santos,
is it possible to use esp as a server and client simultaneously?
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
Thanks venkatakrishnan,
You can use this exact web server for home automation!
Hello, is there an example to refresh the page on client side on say a pin change event?
When the pin state changes, refresh the client browser?
Hi!
If You plan to use these esps for home automation read about MQTT.
NodeMCU support it out of the box.
Yes, I agree. That’s a great tip! Thank you for sharing
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?
Hi Ionut,
What do you mean? It’s not saving the init.lua file?
Which error is prompting?
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…
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()”)
Make sure your script is named init.lua. It happened to me too, because my script’s name was “my.lua”.
Hi Marius,
I say that information in my blog post and you can also download the file that is named as init.lua.
But thank you for bringing that up!
Rui
Are you ‘normalling’ GPIO-01 after programming the ESP8266? (I’ve forgotten to do this upon occasion, causing too much wasted time!)
hi, when I upload Init.lua, I have error “Waiting answer from ESP – Timeout Send aborted”
why ?
Hi yuwaldi.
Do you have any files already in your ESP8266?
That timeout happens when the ESP8266 is busy doing something else.
Try re-flashing the firmware again. Then Unplug your module.
Plug it again and try to upload the init.lua file.
Thanks for asking,
Rui
Hi Rui, I re-flashing no problem, when upload init.lua using esplorer , but still error, I use windows 7 (64), baud rate 9600, programming using FTDI, I hope your help, thanks
I hace the same time out problem.
how to solve it ?
I am not able to load the init.lua file because of this timeout problem.
Thanks
Ambro
Donwload firmware and flash program. Reflash. I had the same problem and solved with reflash the firmware update.
Hi there try connecting GPIO_0 to 3.3V instead of GND
Hi,
It you get message like “Waiting answer from ESP – Timeout Send aborted”…then make sure GPO 0 is connected to 3.3v not gnd…
Hope this helps…
I am not able to load init.lua file because of the time out proble.
My ESP responds well if AT comand is sent.
If I send AT+CIFSR I get two ip’s:
192.168.4.1
192.168.0.105 >> this is the good one !
How to solve the problem ?
thnks,
Ambro
It´s happening because you need to send nodemcu firmware to ESP module.
thanks!! thats work
You’re welcome Lalo!
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 )?
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″});
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 😉 )
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.
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…
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
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?
How did I do what? You can modify my code (the init.lua) file to center your text and buttons…
What you mean by connecting ESP-01s together?
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.
I had fixed the problem. It is really interesting. Thanks
Hi Stephen!
That’s awesome. I’m glad it worked out for you,
Rui
Wow… Great tutorial sir. Thanks a lot.
One question, does the esp module hang some times and needs resetting?
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
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?
I don’t know any resources on that subject… But you mean the web page buttons being momentary?
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.
I misread read your question, yes I meant the button on the web page act as momentary switches,
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
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
Nice job, I need ESP8266 based project for serial communication between arduino and wifi module.
What data you want to send to the ESP8266 via serial?
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.
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
Is it possible to use AvrStudio to code and compile a program for this module?
You can use the official SDK to compile your own firmware: github.com/esp8266/esp8266-wiki/wiki/Toolchain
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.
Hi Arno,
I’m sorry to hear that, I hope you get some modules soon!
Please let me know how this project works out for you,
Rui
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.
Content = “SSID: Password: “;
use this “content” to send to print as html form to take input as ssid and password…
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
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
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.”
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?
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.
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");
I did this but it is still not working, please help
Thanks
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 = “”,””
*%#”
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.
Hi
How can you make the font display bigger in the text line for use on a mobile browser?
Regards
Ian
Hi Ian,
You can easily replace in the “init.lua” file the html
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
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 🙂
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
Hi Karl,
I’m glad it worked.
Is your desktop computer connected to your router via Ethernet?
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?
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!
The embedded code should be made readable, as it is truncated by html 🙁
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
Yes,
That’s a good point! Thank you for sharing Helmut,
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.
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.
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.
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
Yes you can: https://randomnerdtutorials.com/esp8266
But keep in mind that the ESP8266 works at 3.3V. So be careful you might burn your ESP8266.
The best and most reliable way to program the ESP8266 is using an FTDI programmer.
I personally never had any problem using an Arduino, but it’s not the best approach.
Thank you for asking,
Rui
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:-).
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
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
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
That never happened to me viorel.
But you can see your web server in your web browser?
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.
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.
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.
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.
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.
Hi Kapil,
You can use timer delay, here’s how it works: github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en#tmrdelay
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
Hi Yann,
I don’t know of a good tutorial on how to use the ESP8266 as a restfull API in Lua.
But I’ve made a quick tutorial showing how you can do a GET request with this module
You can read it here: https://randomnerdtutorials.com/retrieving-bitcoin-price-using-esp8266-wifi-module/
Hello, Cannot get that project to work unfortunately despite the webserver project working very well.
Can you create a secure web server (https, instead of http) with the module? Thanks.
The ESP8266 doesn’t support https…
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
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
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.
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.
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!
You should download the version that I recommend in this blog post.
It’s the latest version of the NodeMCU firmware!
-Rui
Hi,
Can I talk directly to this module with my own android phone app without the use of an router like in ad-hoc mode?
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.
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.
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
Hey Reini,
Your words mean a lot to me. I’m really glad you enjoy my work! More projects coming soon with the ESP8266.
Thanks for reading,
-Rui
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
I wouldn’t any CSS to this project.
I works better if it’s as simple as possible.
-Rui
Oops sorry for typo! Should have said ” It works a treat for me”
Colin
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
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
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
Sorry for double post i did for correction.
No problem!
-Rui
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
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?
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.
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
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
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?
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
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
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
Hi Rui,
Thanks for the Webserver . Yet now i had found the best way to get nodemcu working on esp8266….
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
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.
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
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
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
how to change the port to 192.168.0.108:1090
ip suitable port router ??
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.
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?
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,
Figured out how to write my lua script to my 8266 non-volatile memory, thanks to (github.com/4refr0nt/luatool).
Hope this helps others also.
Thanks for all your help.
Thanks for the tip !
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.
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.
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!
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
Dear duncan,
watch this video at: youtube.com/watch?v=llzOz9RxbvE
If you need help, send e-mail.
yes ime verry stressed ive about pulled all my hair out its nearly had me in tears,any help be great,ime using esplorer
use this lhink to download ESPlorer:
codeload.github.com/4refr0nt/ESPlorer/zip/master
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.
Use this link to download: codeload.github.com/4refr0nt/ESPlorer/zip/master
Thanks, Ronaldo!
I must’ve had a bad download prior to your link.
ESPlorer now works like a champ on my Windows box.
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.
hi
is it possible to send data to serial port in dmx512 protocol . in this web site don . i dont understand . thank
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?
Dear gungsukma, use the esp8266-12 have 9 GPIOs and 1 ADC input.
To control some 220V devices with esp8266 you Can I use relay or Triac winth MOC306X.
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.
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).
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…
Simply pull up the port pins by 1K resistance.
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
Paulo
Thanks. I have since figured out that my first link to esplorer contained an incomplete download. Explorer is a great tool!
I’ve fixed the link in the meanwhile, Thanks James!
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)
hey i want to upload a file in client:send()
how it would be.
Use ESPlorer. Open the file you want to upload, and select Save to ESP. Then you can read it and send it with client:send. I guess you are asking this.
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!
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.
Can we connect it to proxy network?
can we connect it to proxy server.
Good day to all of you,
I am not able to fine the ESPlorer.jar file in the dist folder.
Any help ?
Thanks
iw2fvo
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
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?
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
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)
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?
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?
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.
Just found out, that if connected to an AP nearby (strong signal), the web page visible is on all browsers.
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..
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
Is there anybody, whose are still unable to upload the code on ESP module using ‘esplorer’????
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.
Can you try with different baud rates? 9600 or 115200?
Very simple. Remove the power to ESP8266 and ‘re connect. Then only open the flasher
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! 🙂
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
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.
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.
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.
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
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!
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…)
i fixed it
Hi Felix,
I’m glad you found a solution. Thanks for reading my blog!
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
Hi Carlos,
Are you using Safari?
Try to open this web server in Google Chrome.
My esp8266 responds “nil” instead of ip adress.
HELP, please!
and it also says “init.lua:8: only one tcp server allowed”
You can have two web servers running in your ESP at the same time.
You can send the command with the ESPlorer IDE to format all your files file.format() then restart your module with node.restart()
Finally upload your code again and you shouldn’t see that message again.
I hope this helps,
Rui
Send this command with the ESPlorer IDE print(wifi.sta.getip())
and it should print your IP address again.
Hi Rui,
Thanks for your enlightenment of esp8266 wifi module, actually i am interesting to explore this module furthermore.
Thanks,
Tony
Thank you for your words!
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
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
Does your book have the instruction set for the esp8266.
eg Conn:???“ ([A-Z]+) (.+) HTTP”); etc
Hi Franklin,
What do you mean?
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
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
Hi David,
Thank you for supporting my work!
I didn’t know that, it might help people with the same problem. Thank you for sharing.
Have a great weekend,
-Rui
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….
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.
Hi. I tried this trick but nothing. Still in busy mode. Can you help us? This project is very interesting…
Try to reset your board. And make sure you remove the GND from GPIO 0.
If your ESP is busy, it’s in flashing mode and it can’t upload new code…
Why this and this are different?
The first image is used to flash the ESP, that’s why it has GPIO 0 connected to GND. The other Figure is when you upload code to the ESP.
I hope this helps!
Yes, it helped. Thanks.
I’m glad to hear that! 🙂
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
You can send the command through ESPlorer IDE “file.format()” and then “node.restart()”.
This removes all the files stored in your ESP and restarts your module.
If you can’t do this for some reason, I recommend that you re-flash your ESP with NodeMCU firmware: https://randomnerdtutorials.com/flashing-nodemcu-firmware-on-the-esp8266-using-windows/
sir esp8266 connect to ESplorer for programming purpose that time GPIO 0 connect ground or not needed
No. The GPIO 0 is connected to GND only when you want to flash a new firmware.
When you want to upload Lua code you can’t have the GPIO 0 connected to GND.
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
Why can’t you use this project?
It uses the ESP8266 with NodeMCU as a standalone web server. You don’t need to use Arduino…
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.
What’s the power supply that you are using?
Does it supply enough current to your ESP?
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 ??
You can’t restart your ESP with GPIO 0 connected to GND. Otherwise your ESP goes into flash mode and it will not run any scripts
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?
I’ve just answered your question! Thanks!
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.
Hi John!
Which browser are you using? Don’t use Safari browser. All the other major browsers should work!
Hi there ,
After flashing the esp module and loading the lua file i can’t get the ip of the module.
Any suggestions??
Send this command to your ESP print(wifi.sta.getip())
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?
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.
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?
Hi John,
Thank you for your support! I really appreciate that! I apologize for the copy/past problem. I might need to migrate the code to another plugin, because it messes with “” and breaks the code.
Here’s how you would create a button 200px by 200px: https://randomnerdtutorials.com/wp-content/uploads/2015/10/button.png
I hope this answers your questions!
Rui
hi rui thanks for a great blog,can i run the esp on web from any where?
Hi Shoki,
Thank you for your feedback. Please read this blog post: https://randomnerdtutorials.com/how-to-control-your-esp8266-from-anywhere-in-the-world/
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!!!!!
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?
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…
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.
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?
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
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?
Hi John, try posting your code, I would be happy to help if I can, even though I’m also new to the ESP8266.
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.
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).
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.
well apparently I don’t know how to place the code in a reply cause it didn’t go…….any tips on how to do that?
Can you upload your code to pastebin.com and post a link here? Thank you John!
Oh, oops heres the link (blush) http://pastebin.com/pf4PpCAz
Hi John. Your code works fine on my ESP-01 with the following in the buffer:
http://pastebin.com/RXn8SEcn
“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.
Hi John. I tried ESPlorer 0.2.0-rc2 and I can reproduce the error now. I was using ESPlorer v0.1 build 206 and here I don’t encounter the error, maybe because there is no LUA interpreter in that version but I don’t know. I got the ESPlorer v0.1 from this download and run the .jar file from the “dist” folder:
https://codeload.github.com/4refr0nt/ESPlorer/zip/6987af991fe49df2c8f611588d3ea6d92260ee7e
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
Judging from all Rui is doing and all the emails he gets, I’m thinking he’s a very busy man LOL.
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.
for sure John, he has a lot going on.
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?
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.
No dice there either…
esp8266.com/viewtopic.php?f=6&t=1946
Ok, after making a simple card for my ESP8266 01, it works a lot more reliably compared to the breadboard version. I can quickly hit the buttons now. Unless I go real fast, it doesn’t hang. I also stopped using a switched 3.3V power supply, and used an LD33CV (Chinese LM1117) instead. I also think i t may have to do with WiFi signal strength.
hello Santos
An error is always occured :
nil
init.lua:10: only one tcp server allowed
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.
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,
Thank you for reading,
Rui
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.
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.
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
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?
in addition if I run this on my phones using the phone as a hot spot it will stay connected. It may be because the phone is sending stuff to the ESP to keep it alive?
Is you ESP receiving enough amperage?
It sounds like it is crashing, because it either ran out of memory or it is a power issue…
hello mr.Rui Santos
i can not flashing esp8266
What settings should I change in advanced tab?
hi
ican not flashing esp8266
How much flashing take time?
what change some of the settings on the Advanced tab?
With all the default settings you should be able to flash the ESP.
Do you have the GPIO 0 connected to GND when you first restart your ESP?
I first use of the esp8266 and the GPIO0 connected to gnd
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.
work great
after flash the esp8266 should GPIO 0 disconnect to gnd for program with esplorer?
SAFARI does show this cute web server correctly!
The answer was in Magnus’ post of 8th april, up there:
https://randomnerdtutorials.com/esp8266-web-server/#comment-251045
At least in my case, my init.lua just needed Magnus’ little header at the very beginning of the buf stream, plus some more detail before . This should work for you too:
…
end
end
buf = buf..’HTTP/1.1 200 OK\n\n’;
buf= buf..”,
buf = buf..”;
buf = buf..’…..
etc…
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…
Safari won’t work sometimes with this web server.
I recommend using Google Chrome! Thanks for asking,
Rui
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…
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!!
The ESP8266 can be a bit frustrating due to power issues mainly.
Here’s a guide that might help: https://randomnerdtutorials.com/esp8266-troubleshooting-guide/
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.
Please read this blog post: https://randomnerdtutorials.com/esp8266-troubleshooting-guide/
Your ESP is not going into upload mode…
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
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
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..”
“;
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
You are either setting or doing an api call that you can’t…
Double check your function calls…
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();
Do you have an external power supply to power your ESP8266?
It might be a current issue that causes your ESP8266 to crash…
I have more information about other problems here: https://randomnerdtutorials.com/esp8266-troubleshooting-guide/
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 ?
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
After rebooting, Wi fi router lost ESP connection. How to make auto connection to the network after it was disconnected ?
After rebooting your router or your ESP8266?
After rebooting router.
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
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 !
Hi Hugo,
I’ve never used that app before…
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.
Looks like I just needed a better resistor between the LED and GND. They are almost 15K each. Is this going to cause problems?
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
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!
https://randomnerdtutorials.com/esp8266-web-server
ftdi can only produce at 3v3 Out 50mA is not enough for esp8266!
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
”
SSID”);
PASS”);
IP address”);
Netmask”);
IP gateway”);
“);
“);
“);
“);
my mail is [email protected]
to show you better the problem
please help
hey can you help I tried to add something to your code but it is not working
Did you change the network details? SSID and password? Did you name your file init.lua?
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.
Please take a look at this page: https://randomnerdtutorials.com/esp8266-troubleshooting-guide/
Read “Finding the ESP8266 IP Address”
Sir, the Save to ESP in unclickable. What should I do?
Hi Laura, you have to establish a serial communication with your ESP first
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(“”);
}
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
thanks-bro.
thanks-bro
You’re welcome,
Rui
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.
Hi Rui, Great tutorial..
I have a doubt, which web server we are connecting (html page), is it there a webserver running in ESP8266?
Yes, the ESP is running the web server and stores the web page.
Thanks.
Rui
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)?
I don’t have any tutorials on that exact subject.
Thanks for asking.
Rui
how to do the same in linux Os..please do reply
You can run the ESPlorer IDE on Linux
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.
Would you prefer to use the Arduino IDE version of this tutorial: https://randomnerdtutorials.com/esp8266-web-server-with-arduino-ide/
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
It should work in all your browsers…
Does it on your Mac but with Google Chrome or Firefox?
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.
You’re welcome!
I’m glad you found it useful,
Rui
Maintainn the excellenbt work and generating the group!
Thanks!
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)
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
Thank you Bill! I’m glad I could help.
Regards,
Rui
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,
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
How to get status of specific GPIO to web server?
You can create a variable that stores the string “on” and “off”. That variable is printed in the HTML page when the gpio changes…
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 ?
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
You could use POST, but GET is easier to access the info and to explain to readers.
That’s a default request from the browser, you could load a favicon in your html page from another source
I wonder… Is your code is compliant with this “issue”?
https://github.com/nodemcu/nodemcu-firmware/issues/730
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.
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.
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 ?
You must be careful with the ” and use escape character and I show in my example…
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.
This link contains all the info about the NodeMCU firmware: nodemcu.readthedocs.io/en/master
How to get ip address of the my esp8266 module????
@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.
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
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
Uploaded to a Lysignal ESP8266-12E single relay board …. perfect ! GPIO 5 is the onboard LED and GPIO4 is the relay.
Thanks !
Hi. You’re welcome!
Thanks 🙂
Really GREAT — the exact info with the exact amount of explanatory detail.
Superb. Thank you so much for sharing !
Hi Paul.
Thank you for your support.
Regards,
Sara 🙂
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
Thanks Paulo. I’m glad you were able to use this example and apply it to your own project.
Regards,
Rui
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!
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 🙂
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?
Hi, unfortunately I don’t have any tutorial with that exact application…
Regards,
Rui
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.
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.
Nice tutorial! Is there a specific to be flashed on ESP8266 in order to work with Arduino IDE? Thanks.
Hi Fabio. What do you mean?
You just need to install the ESP8266 add-on in your Arduino IDE and then simply upload the code.
Here’s the tutorial to install the ESP8266 add-on:
– https://randomnerdtutorials.com/how-to-install-esp8266-board-arduino-ide/
Let me know if this answers to your question or if I misunderstood.
Thank you.
Regards,
Sara
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
Hi.
That’s true. We’ll be publishing a tutorial on how to fix the ESP32 IP address very soon.
Stay tuned.
Regards,
Sara 🙂
very helpful work, can u help me with making esp8266 as an access point and finally making a server which is on its sd card
Hi.
I don’t have any tutorial about that.
But we have a tutorial about access point with the ESP32:
https://randomnerdtutorials.com/esp32-access-point-ap-web-server/
Making an access point with the esp8266 is similar, but you have to make some changes.
I hope this helps.
Regards,
Sara 🙂
Hey there! I recently wrote a code but it’s not really working. Could you please check it out for me?
I posted the question here : https://stackoverflow.com/questions/53159923/location-tracker-using-nodemcu-and-gps-module-shows-only-time-and-date-and-also
Hi.
Have you tested our example codes in the GPS tutorial?
Are they working fine for you?
It may be something to do with the GPS readings.
https://randomnerdtutorials.com/guide-to-neo-6m-gps-module-with-arduino/
Regards,
Sara 🙂
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)” ;
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?
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 🙂
Is it true that only one web client (I have several PCs running windows) can be ‘attached’ to the server at a time?
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 🙂
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!
Hi Ursula.
Have you entered your network credentials and set the Serial Monitor right baud rate?
Are you getting any compilation error?
Regards,
Sara 🙂
Hello! No error when compile but for serial only point …………………………………………………..
Thanks !
Hi Nelu.
Did you update the code with your own network credentials?
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.
Hi.
What do you mean by “can’t see the esp network anymore”?
Regards,
Sara 🙂
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
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
Hi Leo.
What do you mean by “can communicate with the ESP8266 manually”?
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
Hi.
There was an error displaying the code in our website.
Please copy the code again, and everything should be working fine.
Regards,
Sara
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.
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?
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.
Have you checked the LED polarities?
I will check
please can I use the esp8266 wrom 32? to do this tutorial?
Hi.
this tutorial works with the ESP8266.
We have a similar tutorial for the ESP32: https://randomnerdtutorials.com/esp32-web-server-arduino-ide/
Regards,
Sara
I have this ESP8266. And donot have Arduino.
Please guide me what can i do with this alone?
I’m sorry, but I don’t understand your question.
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
Hi Esteve!
That’s great! Good luck with your projects 😀
You’re welcome.
Regards,
Sara
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
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
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.
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
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.
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
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
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
It´s working perfectly with Wemos D1 R2.
Muito obrigado !
Rui,
Thanks for yours tutorials, I like too much to watch you channel.
Ivan
From:Brasil
Thanks 😀
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
Hi Kyle.
I think one of the best ways is using MQTT.
See our tutorials about MQTT:
– https://randomnerdtutorials.com/what-is-mqtt-and-how-it-works/
– https://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/
– https://randomnerdtutorials.com/raspberry-pi-publishing-mqtt-messages-to-esp8266/
You can subscribe all ESP8266 to the same topic to execute the same code when they receive a certain message.
Regards,
Sara
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?
Hello, to convert a float/int to a string, just use it like this:
client.println(String(yourIntOrFloatValue));
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.
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
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.