In many applications, ESP8266 WiFi modules can replace Arduino by adding Wi-Fi connectivity at a lower cost. At the launch of ESP8266 (in 2014), the preferred programming language was Lua (we can always program in this language!).
Quickly, the vast majority of Arduino libraries have been adapted to run on the ESP8266. Today it is as easy to program an ESP8266 module as an Arduino in C++. We will discover in this tutorial how to install the necessary libraries on the Arduino IDE, and discover through simple examples the basics of the programming of the ESP8266.
Install boards and libraries for ESP8266 modules on the Arduino IDE
Launch the Arduino IDE and open the preferences from the File menu. On macOS, go to the Arduino menu then Preferences … Click on the icon indicated by the red arrow on the photo below.
In the input field, paste the following internet address and validate
http://arduino.esp8266.com/staging/package_esp8266com_index.json
This will indicate to the Arduino IDE that it must go to the arduino.esp8266.com site in order to recover other compatible development boards. Now go to the Tools menu and then boards Type and finally board Manager
In the search field, type esp8266 to find the new board to install. If the board do not appear, check in the preferences that the URL is correct. also check the internet connection. Click on Install.
The installation lasts only a few minutes. When the installation is complete, close the board manager and open the Tools menu again. In the board Type submenu, you now have a new section called ESP8266 Modules.
The main manufacturers who contribute the most to the community (Adafruit, ESPresso, Olimex, Sparkfun, WeMos …) are on the menu. For other modules, simply choose Generic ESP8266 Module.
To display the examples installed with ESP826 development board, if you just have to choose from the list then go to the File -> Examples.
Before going further, note on the ESP-01
The ESP-01 is a more limited version of the ESP8266. It only has 2 GPIOs. The module has a smaller flash memory (512KB to 1MB). The programming is identical but “more painful” because it is necessary to put the module in a particular mode before being able to upload the program (Bootload mode). This is not a suitable module for learning and starting with the ESP8266. If however you need information, you will find several tutorials on the blog by doing a search with the keyword ESP-01 in the search field located in the upper right corner of the page.
Differences between Arduino and ESP8266 pin tracking
The ESP8266 has 9 digital I / Os instead of 14 for the Arduino Uno. While on the Arduino Uno there are only 6 outputs that support PWM mode (3, 5, 6, 9, 10 and 11), all outputs of the ESP8266 can generate a PWM signal.
In summary
Arduino / Genuino 101 | ESP8266 (ESP-12x) | |
Microcontroller | Arduio Uno and most compatible boards : ATmel ATmega328p
New Genuino 101 : Intel Curie |
Tensilica Xtensa LX106 |
WiFi | – | |
Bluetooth | LE | – |
Adressing | 8…32bits | 32bits |
Frequency | 16 MHz | 80 MHz |
Flash memory | 32ko | 512…4Mo (1) |
I/O | x14 | x11 (D0…D8 + RX/TX) |
PWM output | Arduino Uno and compatible : x6 (3, 5, 6, 9, 10, 11)
Arduino 101 : x4 |
All outputs are PWM |
Analog output | x6 (A0..A5), 10bits, 5V max. | x1 (A0), 10 bits, 1V max. (2) |
UART (port série) | x1 | x1 (3) |
I2C | x1 | x1 |
SPI | x1 | x1 |
Technical documentation | Arduino Uno R3 | version 5.4 |
(1) Connected to the GND pin at power up to put the ESP into bootload mode. This mode allows you to re-install the original firmware or load an Arduino program. On some board, WeMos d1 mini for example, this operation is supported by the board manager. This operation is therefore useless, the upload is transparent.
Typically, manufacturers publish a pinout that indicates the equivalent pin on an Arduino Uno. Here, for example, the pins of a WeMos d1 mini. This connection diagram is valid for all ESP-12x-based boards.
Attention to the GPIO which works at a voltage of 3.3V
Special feature of the ESP8266 compared to the Arduino Uno (this is no longer the case for the Genuino 101 and new Intel Curie-based boards), the GPIO operates at a voltage of 3.3V. It will therefore in some cases adapt your editing. For this, there are voltage dividers (5V to 3.3V) or vice versa (3.3V to 5V).
How to program the ESP8266 with the Arduino IDE?
Hardware and test circuit
Here is a small editing to make with an ESP8266 (here a WeMos d1 mini) and an LED that will allow you to test the various codes proposed in this tutorial.
For the record, here is a table summarizing the typical supply voltage according to the color and the diameter of the LED.
Color | Longueur d’onde (nm) | Tension (V) for a 3mm LED diameter | Tension(V) for a 5mm LED diameter |
Red | 625-630 | 1,9-2,1 | 2,1-2,2 |
Blue | 460-470 | 3,0-3,2 | 3,2-3,4 |
Green | 520-525 | 2,0-2,2 | 2,0-2,2 |
Yellow | 585-595 | 2,0-2,2 | 3,0-3,2 |
White | 460-470 | 3,0-3,2 | 1,9-2,1 |
Classic programming
The first thing to know when starting with an ESP8266 module is that it can be programmed exactly like an Arduino. Unlike the less powerful ATTiny microcontrollers, the SoC of the ESP8266 is able to execute all C ++ commands of the Arduino code. The only condition to respect is to use the library adapted for this last one as soon as one wants to use the WiFi (following paragraph).
Open the Arduino IDE and paste this code into a new project before uploading it.
What does this program do?
- An integer variable (int) indicates which output the LED is connected to
- In the setup() loop, we indicate that the pin (here 16) is an output (OUTPUT)
- The loop() loop runs to infinity. At each passage
- We put the output (16) at the low level (LOW), that is to say that the output voltage is zero (no current)
- We wait 1 second. The delay is indicated in milliseconds (1000ms = 1s)
- The output (16) is set high (HIGH), that is, the output voltage is 5V (the current flows)
- We wait 2 seconds
- And so on
int led = 16; void setup() { pinMode(led, OUTPUT); // Initialise la broche "led" comme une sortie - Initialize the "LED" pin as an output } // Cette boucle s'exécute à l'infini // the loop function runs over and over again forever void loop() { digitalWrite(led, LOW); // Eteint la Led - Turn the LED OFF delay(1000); // Attendre 1 seconde - Wait for a second digitalWrite(led, HIGH); // Allume la Led - Turn the LED off by making the voltage HIGH delay(2000); // Pause de 2 secondes - Wait 2 secondes }
Now, replace in output 16 by the equivalent identification of ESP8266, namely D0, which gives int led = D0;
As you can see, the program works identically.
Web Server Programming: connect the ESP8266 to the WiFi network
Web Server programming allows you to add a Web interface (written in HTML and javascript) to an ESP8266 project. It is also possible with an Arduino but it makes sense with an ESP8266 which natively has a WiFi connection.
Let’s go back to the previous code and add the two necessary libraries
#include <ESP8266WiFi.h> #include <ESP8266WebServer.h>
We will create two variables to define the SSID (identifier of the WiFi network) and the password before creating an object that will contain the Web server (C ++ object)
const char* ssid = "xxxx"; // WiFi ssd const char* password = "xxxxxxxxx"; // WiFi password ESP8266WebServer server(80); // create a web server. listing standard http 80 port
The code of the setup function does the following
- Serial.begin(115200) opens the serial port at 115200 baud
- WiFi.begin(ssid, password) the ESP8266 connects to the WiFi network
The while loop writes a dot on the serial port every 500ms until the ESP8266 is connected to the WiFi WiFi.status() != WL_CONNECTED (very bad idea when running on battery elsewhere, but that is just to understand the operation) - Serial.println (WiFi.localIP()) writes on the serial port the IP address assigned by the internet box or the router to the ESP8266
-
server.on ("/", [] () { server.send (200, "text / plain", "Home"); // Add an entry point, a web page });
We add an entry point, ie an internet address (URL) on which we will display for the moment a simple text
-
server.on ("/ parametres", [] () { server.send (200, "text / plain", "A page of parameters"); });
A second page that could be a parameter page
- server.begin() finally, we start the web server
All that remains is to ask the ESP8266 to listen to the requests and to display the corresponding pages. For that we add the server.handleClient() command in the loop () function.
Past the complete code into a new project and upload it to the WeMos.
#include <ESP8266WiFi.h> #include <ESP8266WebServer.h> const char* ssid = "xxxx"; // WiFi ssd const char* password = "xxxxxxxxx"; // WiFi password ESP8266WebServer server(80); // create a web server. listing standard http 80 port int led = D0; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); Serial.println(""); // on attend d'etre connecte au WiFi avant de continuer while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // on affiche l'adresse IP attribuee pour le serveur DSN Serial.println(""); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // on definit les points d'entree (les URL a saisir dans le navigateur web) et on affiche un simple texte server.on("/", [](){ server.send(200, "text/plain", "Page d'accueil"); }); server.on("/parametres", [](){ server.send(200, "text/plain", "A parameter page"); }); // on demarre le serveur web server.begin(); pinMode(led, OUTPUT); // Initialise la broche "led" comme une sortie - Initialize the "LED" pin as an output } // Cette boucle s'exécute à l'infini - the loop function runs over and over again forever void loop() { // a chaque iteration, la fonction handleClient traite les requetes server.handleClient(); digitalWrite(led, LOW); // Eteint la Led - Turn the LED OFF delay(1000); // Attendre 1 seconde - Wait for a second digitalWrite(led, HIGH); // Allume la Led - Turn the LED off by making the voltage HIGH delay(1000); // Pause de 2 secondes - Wait 2 secondes }
Open the serial monitor to retrieve the IP address of the ESP8266 on the local network.
Now open a web browser and enter the IP address or IP_ESP8266/parametres.
And now, in a few lines of code, you just connect the ESP8266 to the local network (and internet at the same time). You can access a web interface from any computer or smartphone. By doing a port forwarding on your internet box or router, you can even access the interface outside of your home with a 3G / 4G connection.
Web Server Programming: drive the GPIO from the internet!
We will now see how to add commands to drive the GPIO from an interface. There are several methods to generate the HTML code of the interface that will be sent to the web browser. Here, we will simply create a string that will contain the HTML code. Everything is explained in detail in this tutorial. Each line is explained in the code. What you must remember :
- HTML code is built by assembling strings
- It is possible to integrate the variable content. Here the state of the output D0contained in the chain etatD0.
- Each state change is sent to the web server running on the ESP8266 using a form in the form of an HTTP POST request.
- Here, the update is triggered manually by pressing a button (submit)
String getPage(){ String page = "<html lang=fr-FR><head><meta http-equiv='refresh' content='10'/>"; page += "<title>ESP8266 Web Server Demo - www.projetsdiy.fr</title>"; page += "<style> body { background-color: #fffff; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }</style>"; page += "</head><body><h1>ESP8266 Web Server Demo</h1>"; page += "<h3>GPIO</h3>"; page += "<form action='/' method='POST'>"; page += "<ul><li>D0 (etat: "; page += etatD0; page += ") "; page += "<INPUT type='radio' name='D0' value='1'>ON"; page += "<INPUT type='radio' name='D0' value='0'>OFF</li></ul>"; page += "<INPUT type='submit' value='Actualiser'>"; page += "<br><br><p><a hrf='http://www.projetsdiy.fr'>www.projetsdiy.fr</p>"; page += "</body></html>"; return page; }
Now, we change in the setup the entry point to the home page. We connect the entry point “/” to the handleRoot function.
server.on ( "/", handleRoot );
When the main page (“/”) is displayed or the web server receives a POST request (GPIO refresh), the handleRoot function is called. The server.hasArg function allows you to connect actions. Here, if the query contains the argument (hasArg), then we must change the state of the GPIO. We execute the handleSubmit function, otherwise we refresh the page.
void handleRoot(){ if ( server.hasArg("D0") ) { handleSubmit(); } else { server.send ( 200, "text/html", getPage() ); } }
The handleSubmit function retrieves the value of the “D0” argument with the server.arg function and then it is enough to test the value of this one to realize the good treatment. Be careful, it’s a string of characters. We must test like this == “1” and not == 1. We take this opportunity to store the state of the output in the variable etatD0.
void handleSubmit() { // Actualise le GPIO / Update GPIO String LEDValue; LEDValue = server.arg("D0"); Serial.print("Set GPIO to "); Serial.println(LEDValue); if ( LEDValue == "1" ) { digitalWrite(D0, 1); etatD0 = "On"; server.send ( 200, "text/html", getPage() ); } else if ( LEDValue == "0" ) { digitalWrite(D0, 0); etatD0 = "Off"; server.send ( 200, "text/html", getPage() ); } else { Serial.println("Err Led Value"); } }
Paste the following complete code by changing WiFi ID and password.
#include <ESP8266WiFi.h> #include <ESP8266WebServer.h> const char* ssid = "XXXX"; // Identifiant WiFi const char* password = "XXXXXXXX"; // Mot de passe WiFi ESP8266WebServer server(80); // On instancie un serveur qui ecoute sur le port 80 int led = D0; String etatD0 = "Off"; String getPage(){ String page = "<html lang=fr-FR><head><meta http-equiv='refresh' content='10'/>"; // C'est du code HTML, la page s'auto-actualise page += "<title>ESP8266 Web Server Demo - www.projetsdiy.fr</title>"; // Titre de la barre du navigateur page += "<style> body { background-color: #fffff; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }</style>"; // style de la page page += "</head><body><h1>ESP8266 Web Server Demo</h1>"; // Titre de la page (H1) page += "<h3>GPIO</h3>"; // Sous-titre (H3) page += "<form action='/' method='POST'>"; // Le formulaire sera envoye avec une requete de type POST page += "<ul><li>D0 (etat: "; // Premiere ligne de la liste (ul) avec D0 page += etatD0; // on concatene la chaine contenant l'etat de la sortie page += ") "; page += "<INPUT type='radio' name='D0' value='1'>ON"; // Bouton pour activer D0 page += "<INPUT type='radio' name='D0' value='0'>OFF</li></ul>"; // et le desactiver page += "<INPUT type='submit' value='Actualiser'>"; // Bouton d'actualisation page += "<br><br><p><a hrf='http://www.projetsdiy.fr'>www.projetsdiy.fr</p>"; page += "</body></html>"; return page; } void handleRoot(){ if ( server.hasArg("D0") ) { handleSubmit(); } else { server.send ( 200, "text/html", getPage() ); } } void handleSubmit() { // Actualise le GPIO / Update GPIO String LEDValue; LEDValue = server.arg("D0"); Serial.print("Set GPIO to "); Serial.println(LEDValue); if ( LEDValue == "1" ) { digitalWrite(D0, 1); etatD0 = "On"; server.send ( 200, "text/html", getPage() ); } else if ( LEDValue == "0" ) { digitalWrite(D0, 0); etatD0 = "Off"; server.send ( 200, "text/html", getPage() ); } else { Serial.println("Err Led Value"); } } void setup() { Serial.begin(115200); WiFi.begin(ssid, password); Serial.println(""); // on attend d'etre connecte au WiFi avant de continuer while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // on affiche l'adresse IP qui nous a ete attribuee Serial.println(""); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // on definit les points d'entree (les URL a saisir dans le navigateur web) et on affiche un simple texte server.on ( "/", handleRoot ); // on demarre le serveur web server.begin(); pinMode(led, OUTPUT); // Initialise la broche "led" comme une sortie - Initialize the "LED" pin as an output } // Cette boucle s'exécute à l'infini - the loop function runs over and over again forever void loop() { // a chaque iteration, on appelle handleClient pour que les requetes soient traitees server.handleClient(); }
Here is the interface obtained
Now that it’s clearer, you can go a step further in the details of ESP8266’s Web Server programming by reading this article. You can achieve this type of interface by following this project of weather station in 5 steps.
All ESP8266 Web Server Programming Tutorials
Web Server (Communication + Interface)- ESP8266, retrieve time from a time server (NTP), elapsed time since last Reset, store time in SPIFFS [Update] 28 June 2017
- ESP8266. How to use WiFiManager library to manage WiFi connections 26 June 2017
- Driving the ESP8266 GPIO (Web Server) from Jeedom to TCP / IP Wireless – Part 2 14 April 2017
- Driving the GPIO of the ESP8266 (Web Server) from Domoticz to TCP/IP Wireless – Part 2 31 March 2017
- ESP8266. How to connect to the WiFi network (ESP8266WiFi and ESP8266WiFiMulti) 22 March 2017
- ESP8266 (Web Server – Part 5): how to use Google Charts to display gauges and charts 20 March 2017
- ESP8266 (Web Server): Fast development of HTML + js with Node.js and Pug 15 March 2017
- ESP8266 (Web Server – Part 4): ArduinoJson, load, save files (SPIFFS) 13 March 2017
- ESP8266 (Web Server – Part 2): Interaction between Arduino code and HTML interface 27 February 2017
- ESP8266 (Web Server – Part 1): Store the web interface in the SPIFFS area (HTML, CSS, JS) 22 February 2017
- Bootstrap (Web Server ESP8266): use the Bootswatch themes 15 February 2017
- How to create a beautiful Web Interface for projects ESP8266 / ESP32 with Bootstrap 13 February 2017
- ESP8266. Understand the Arduino code of a web server with HTML interface 10 February 2017
Web Client Programming:
The Web Client programming makes it possible to communicate an ESP8266 module with another server, another ESP8266, a mobile application … Here are some examples of applications:
- Transmit measurements (temperature, humidity, particle rate, atmospheric pressure, brightness, noise …)
- Transmit states (door or window opening detector, contactor …)
Here are several articles on the subject with examples of application to communicate the ESP8266 with Jeedom or Domoticz (remote display)
Web Client (Communication)- Temperature measurement with several DS18B20 probes, Arduino code compatible ESP8266 and ESP32, publication on Domoticz in HTTP 8 December 2017
- ESP8266. How to use WiFiManager library to manage WiFi connections 26 June 2017
- ESP8266 (Web Client): Sending Data to Jeedom in TCP / IP Wireless (JSON API) – Part 1 7 April 2017
- ESP8266 (Web Client): Sending Data to Domoticz in TCP/IP Wireless (API/JSON) – Part 1 24 March 2017
Frequently Asked Questions (FAQ)
What hardware to buy to start with the ESP8266?
To get started with the ESP8266 modules, you will need the same hardware as for an Arduino Uno. You can buy a basic kit including a breadboard, a Dupond jumper set and a regulated 5V / 3.3V power supply. If you start with the micro-controllers and the ESP8266, I recommend the Wemos d1 mini or the Wemos D1 R2 (a board in the same format as the Arduino Uno). These two boards are very economical and are perfectly managed from the Arduino IDE. It is very rare to install the CH341 driver on macOS, Linux or Windows.
On which platforms is the Arduino IDE available?
The Arduino IDE is available on all operating systems (Windows, MacOS, Linux, ARM Linux). Whatever your environment, you can develop your ESP8266 projects with the Arduino IDE. Go to the Arduino feature website to get the right installer for your computer or mini-PC.
Can I program an ESP8266 on a Mac?
Yes, the Arduino IDE is available on macOS as well. Since the Espressif SDK is written in python, it is possible to program the ESP8266 modules as on a Windows PC.
Can the ESP8266 be programmed from Linux ARM?
Yes, if you have a Raspberry Pi or an equivalent mini-PC running Linux ARM (an Orange Pi for example), it is quite possible to use the Arduino IDE.
How to develop without programming with the ESP Easy Firmware
If you’re new to micro-controllers and everything you’ve read before has scared you a little bit, no problem. The ESP Easy project is for you! ESP Easy is an interface that allows to develop probes or actuators by simple configuration. The interface is in English but everything is explained in these tutorials.
Which model of ESP8266 to choose to start?
Development boards based on ESP-12x (WeMos d1 Mini, Geekcreit …) are best for beginners. The upload is handled completely transparently by the ESP8266 SDK from the Arduino IDE. You can use the price comparator to find the best deal on the internet.
Can I use NodeMCU or MicroPython development boards?
Yes absolutely. These are other firmwares. NodeMCU is used to execute Lua code. As soon as the first upload, the firmware will be replaced by the Arduino code. You can re-install the firmware NodeMCU (follow this tutorial for that) or MicroPython later. If the MicroPython tempts you, here are some articles to start:
- ESP32 MicroPython project with several DS18B20 probes, publish the measurements to Domoticz using the HTTP JSON API
- OLED display SSD1306 in MicroPython, example with a I2C digital barometer BME280 (or BMP180)
- MicroPython tutorial, manage WiFi connection at startup on ESP8266 / ESP32
- uPiCraft, a MicroPython IDE dedicated to the development of IoT based on ESP8266, ESP32, microbit, pyBoard
- How to reinstall the MicroPython firmware on an ESP8266 or ESP32 with the esptool.py script
- Unpacking the Wemos ESP32 Lolin32 Lite, testing the firmware MicroPython with a Raspberry Pi 3
What is the ESP-WROOM-32 model?
The ESP-WROOM-32 module is the successor code name of the ESP8266, the ESP32. It is more powerful, less greedy, more secure, more pro (CAN bus), it also provides support for Bluetooth in addition to WiFi. The price of ESP32 development boards has fallen sharply in recent months. They are now almost the same price. To find out more, go to the ESP32 category of DIY Projects. Here, the Lolin32 Lite from Wemos.cc
Some books to start in C / C ++
Arduino programming uses notions of C/C ++ object programming. There are very good introductory books and tutorials on the web to go beyond the concepts discussed here.
- How to store data on a micro SD card. Arduino code compatible ESP32, ESP8266
- Getting started Arduino. Receive commands from the serial port (ESP32 ESP8266 compatible)
- C++ functions print•println•printf•sprintf for Arduino ESP32 ESP8266. Combine•format → serial port
- C++ String functions. concat•c_srt•indexOf•replace•subString… for Arduino, ESP32, ESP8266
- How to assign a fixed IP to an ESP32 ESP8266 or ESP01 project
That was really helpful! Thanks a lot of such a great effort!
I have a short question: Can I store the data in the serial monitor from ESP using the WiFi connection and link it to MATLAB?
Thank you very much. I don’t have any Matlab licence, so I can’t test anythings. I think that’s no problem. I imagine that on the ESP8266, you have to send the measurements with the command Serial.println(you_data). On Matlab, there are several commands to open the serial port and read data (in ascii for example) https://fr.mathworks.com/help/matlab/serial-port-devices.html. fopen / fgetl / fclose.
Hi,
Very intersting! I have another quesiton; can I upload the program it self using WiFi after connecting the Arduino with my home router. I mean let’s say, I will connect my ESP with WiFi and then I put somewhere where it’s difficult to connect it through USB again, at this stage can I send a new code through WiFi or not?
Great. To recover data in python, I advise you to communicate in HTTP or Websocket. You can do more elaborate things. For example since the pyhon code send settings, start or stop the publication of data. You can get inspired by these tutorials
Websockets https://diyprojects.io/websocket-communication-esp8266-arduino-python-test-ws4py-library-raspberry-pi/#.WpEMwZOdU_U
HTTP https://diyprojects.io/esp8266-web-client-tcp-ip-communication-examples-esp8266wifi-esp866httpclient/#.WpENQ5OdU_U
You can also use the awesome project johnny-five if you know the javascript.
https://diyprojects.io/start-programming-nodejs-johnny-five-iot-firmata-orangepi/#.WpEOSJOdU_U
Then to connect your code to Matlab
– In Pyhon https://fr.mathworks.com/help/matlab/matlab-engine-for-python.html?s_tid=gn_loc_drop
– Nodejs https://www.npmjs.com/browse/keyword/matlab
That’s it, I hope you have everything you need for your project or your studies. Have a nice week end
BIG THANK FOR YOU!
You’re welcome. I did not do much. You still have everything to do. Good luck and do not hesitate to explain your project when it is finished. He looks very interesting. See you soon. Have a nice week end
Hi. Yes it possible. All is explain in this post https://diyprojects.io/arduinoota-wireless-update-ota-arduino-ide-esp8266-programs/#.WpCbtpOdU_U Have a good week end
Amazing! Last question; can I check or see the serial monitor remotly through WiFi ? And finally import data from this monitor to Matlab or Python or any post process software? All two steps are being made wirelessly?