Program the ESP8266 with the Arduino IDE: Libraries, GPIO, Web Server, Web Client

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 cards 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.

ide arduino esp8266 preference

In the input field, paste the following internet address and validate

http://arduino.esp8266.com/staging/package_esp8266com_index.json

ide arduino libraire url esp8266

This will indicate to the Arduino IDE that it must go to the arduino.esp8266.com site in order to recover other compatible cards. Now go to the Tools menu and then Cards Type and finally board Manager

 ide arduino gestionnaire carte

In the search field, type esp8266 to find the new cards to install. If the cards do not appear, check in the preferences that the URL is correct. also check the internet connection. Click on Install.

ide arduino install esp8266 board

The installation lasts only a few minutes. When the installation is complete, close the card manager and open the Tools menu again. In the board Type submenu, you now have a new section called ESP8266 Modules.

ide arduino esp8266 board list

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 cards, if you just have to choose from the list then go to the File -> Examples.

Before going further, note on the ESP-01

esp8266 esp-01 module WifiThe 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

Genuino 101

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 cards, WeMos d1 mini for example, this operation is supported by the card 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.

Correspondance Pins GPIO WeMos D1 mini

If you want to start programming in Lua, the number of spindle to be used in the code is also indicated.

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.

Note. Even if the variable is of type int (integer), we write a string in the code. It’s normal. At the time of compilation, the reference to the spindle will be replaced in the code by the ESP8266 library.

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.

Warning. The connection is not encrypted. She is not protected. Everyone can access the controls on your interface. It will be necessary to add protections (password …)

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.

esp8266 web server spiffs bootstrap dht22 bmp180 google charts

All ESP8266 Web Server Programming Tutorials

Web Server (Interface)

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

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 card in the same format as the Arduino Uno). These two cards 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.

Last update was on: 25 September 2018 3 h 10 min

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 cards 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 cards?

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:

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 cards 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.

Last update was on: 24 September 2018 23 h 02 min

Subscribe to the weekly newsletter

No spam and no other use will be made of your email. You can unsubscribe anytime.

DIY Projects