Introduction to the ESP8266 WiFi module

ESP8266 Overview

As I have already said, the main hardware part which we will give us connectivity is the ESP8266. What is it actually? You have probably used or at least heard of Arduino – a microcontroller platform people use to build all kind of electronics projects. Imagine a tiny chip that can be used for the same purposes like Arduino, plus it has built-in Wi-Fi capabilities and it can be acquired for roughly 2$! Also, it has considerably stronger processor – 32-bit, comparing to Arduino’s 8-bit. It outperforms Arduino in terms of processor speed and RAM memory. Unfortunately, it has limited number of GIPOs (General Purpose Input Output) and only one ADC (analog to digital converter). If there is a need for a higher number of GPIOs or ADCs, connecting an external microcontroller such as Arduino over some communication protocol (UART, I2C or SPI) solves a problem. Here is a more detailed specs list:   

You can check complete documentation here.

The ESP8266 is designed by a Chinese company Espressif and the production started in 2014. Thanks to its great features, this microcontroller attracted attention of many people – engineers, hobbyists, makers etc. There is even a blog dedicated to it.

 

Placing the ESP8266 on a Breadboard

We don’t use ESP8266 in our projects straight out from a factory. Other companies put chips together with some other components (flash memory, antenna, LEDs…) on breakout boards, which are then used as modules. Depending on the size and the number of exposed pins, there are many models available that are labeled as ESP-01, ESP-02, ESP-03… The most popular one is the ESP-12.

ESP-01 model

ESP-01

ESP-12

If you are building a very simple application or you want to add a connectivity to another microcontroller, you can use model ESP-01, which is very limited in terms of number of exposed pins, but even this model sometimes can be enough.
In case you want a board that doesn’t need any additional circuitry, doesn’t require any soldering and that you can start using by just plugging a USB cable, like the Arduino, than you can buy a board like this one. Also, companies like Sparkfun or Adafruit have their own breakout boards. However, I want to show you how you can set-up a bare module (ESP-12).

We have to add some additional circuitry to the module to work properly. First of all, you need to power your chip. These chips require 3.3V, and you shouldn’t apply higher voltage levels or you can damage your microcontroller! Also, you have to be careful if you are interfacing the ESP8266 with a device that uses 5V signal levels. A very convenient way to power your circuit is a board like this one, that is breadboard friendly and can be used to supply both 3.3V and 5V on the same breadboard. Then, you need a USB to TTL converter for programing the chip, like this one. It converts a signal that comes from a USB port of your computer to a signal suitable for the UART port of the ESP8266. Make sure that all signals are at the 3.3V level. Programs are stored in an external flash memory. In order to program the ESP8266, you need to connect a ground of the USB-TTL converter to a ground of the ESP8266. Then, connect TX and RX pins of the converter to RX and TX pins of the ESP8266, respectively. There are a few more steps to be done. The GPIO 2 should be high on boot. The GPIO 0 should be low while uploading a new program (flash update), and high on boot. If you are using the model ESP-12, then GPIO 15 should be low on boot as well. Connections should be done via resistors. I have used 2.2K resistors for this purpose. CH_PD pin which is chip-enable pin should be always high.  I suggest you to add a reset button as well. Your circuit should look like this:

Circuit design

Here is the pinout for the ESP 12 model:

Pinout for ESP 12 model

You have probably noticed that the voltage level at GIPO 0 depends on whether you want to upload a new program, or to read an old program from flash memory. This means that you have to switch that one resistor from GND to Vcc and vice versa each time you want to upload a new program. If you want to avoid this, then you can build a small circuit shown in the following scheme. You need a USB – TTL converter that has DTR and RTS pins. You can also use some other BJT transistors than those in the scheme, I used 2n3904. Check the third scheme http://www.wemos.cc/Products/images/d1_mini.pdf.

If you want to use any other module except ESP-01, you will have to acquire an adapter board on wich you solder your chip. Adapter board allows you to connect a chip to a breadboard. Also, you can solder jumper wires to directly to pins and avoid using the adapter board, although it is not that elegant solution. If you want to use ESP-01 module, you don't need the adapter board, but you will still need to use jumper wires because this module is not breadbord friendly.

 

Configuring the Arduino IDE

As I have already mentioned, we will use the Arduino IDE to program the ESP8266. If you don't have it installed, you can download it here. Make sure that your version is 1.6.4 or newer. The main reason for using the Arduino IDE for the ESP8266 over the original SDK is its simplicity and huge community.

Now you need to add an extension to the Arduino IDE so you can use it to program the ESP8266. Go to File > Preferences and in the Additonal Boards Managers URLs enter the URL for the ESP8266 package http://arduino.esp8266.com/stable/package_esp8266com_index.json. Then go to Tools > Board and open Boards Manager. Find esp8266 by ESP8266 community and install it. Go to Tools > Board and select appropriate board (Generic ESP8266 module if you are using model ESP-01). You are ready to upload your first program. You can choose a simple program (Blink for example) from File > Examples and upload it to verify that you have configured everything properly. The upload process takes some time and after it finishes, the bottom part of the window should look like this:

Window

So far I explained the minimum work you have to do to start programming and running the ESP8266. As I have already said, this was just a brief explanation and I assumed that you have some experience with electronics and microcontrollers. If you are missing some information or have any troubles setting everything up, feel free to ask here. Also, if you want more detailed instructions on these topics and many others, you can check this free book written by Neil Kolban.

 

Thingspeak

After successfully uploading and running a blink sketch, now you want do something more challenging. You want to communicate to the net and exchange data. When you add the extension for the ESP8266 to the Arduino IDE, go to File > Examples and you can see dozens of example programs intended for this microcontroller. I suggest you to go through several programs to familiarize yourself with common function blocks for connecting to a network, connecting to a server, setting up a client or webserver, sending HTTP requests etc. The ESP8266 is a versatile chip, with broad range of possible applications. It can function as a station connecting to a local access point, as an access point, or both at the same time, which can be handy in some applications. You can see extensive list of Arduino functions for the ESP8266 in the book by Neil Kolban.

If you search for the ESP8266 tutorials online, you will probably come across many tutorials that explain how to connect the ESP8266 to a platform called Thingspeak. This is open source IoT platform that allows you to connect your devices, collect and visualize data. Communication is conducted over the HTTP protocol. It gives you possibility to write Matlab code to manipulate received data, which is very handy. You can also use it to easily fetch any data from a webpage. As there are already plenty resources on this, I will not cover it here, instead, I will give you an example code that sends POST requests with ADC (Analogue to Digital Converter) values which are plotted on your Thingspeak channel (note that the ADC on the ESP8266 is 10-bit with 1V maxim voltage). I have connected a potentiometer to the ADC for this purpose (I’ve used 1k potentiometer with two 1k resistors in series to limit maximum output).

Circuit design

Thingspeak offers a possibility to set reacts that are triggered on particular data changes. For example, turn on the cooler when the temperature rises above certain level. Since it is open source, there is a limit of the exchanged data over time.      

After you make an account at https://thingspeak.com, go to Channels > My Channels and click New Channel. Give it appropriate name and description if needed. Then, check the box for a field and give it a name, for example, ADC Value. We need only one field for this demonstration. There are also some other options like making the channel public or adding latitude and longitude values. After filling these values, click Save Channel. Under Private View, you should see a chart corresponding to the first field from our channel we named ADC value. Now go to API keys. We want to send a number (ADC value) over POST request. Since we want to write to a channel, we need the Write API Key that will be specified in the body of a request. This API Key serves as an authentication method. Copy and save this string. Then go to Data Import/Export. On the right side you see a list of available API (Application Programing Interface) calls. You can see a format of a POST request we want to send. We have to specify API key and field value. This format is used in the following code:

#include <ESP8266WiFi.h>

//enter your values for ssid and password
const char* ssid     = "";
const char* password = "";
const char* host = "api.thingspeak.com";

//enter write API key 
String api_key = "";

void setup() {

  Serial.begin(115200);

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {

  int ADC_value = analogRead(A0); 
  
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  
  // We now create a URI for the request
  String url = "/update.json";
  
  String content = String("api_key=") + api_key + "&" + "field1=" + ADC_value;
  int content_length = content.length();
           
  Serial.print("Requesting URL: ");
  Serial.println(url);
    
  client.print(String("POST ") + url + " HTTP/1.1" + "\r\n" +
  "Host: " + String(host) + "\r\n"
  "Content-Length: " + content_length + "\r\n\r\n" + 
  content + "\r\n\r\n"
  );

  int _time = millis();
 
  while(!client.available()){
    delay(1);
    if(millis()-_time>3000){ //wait 3 seconds max for response
      Serial.println("No response.");
      break;
    }
  }
                
  while(client.available()){
    String line = client.readStringUntil('\r'); //print response
    Serial.print(line);
  }
       
  client.stop();
  Serial.println("closing connection"); 
  delay(15000); //thingspeak limit
}

After uploading this program, you should see points on the graph that represent ADC values. Right now, minimum time between two requests is 15 seconds.

ADC values

Now you can attach a sensor to your ADC to monitor some physical parameter, for example, a temperature sensor. I advise you to go to Apps and play around to see how you can extend your system. Add a Matlab code to manipulate data (visualize, store, convert, calculate mean values etc.), or set reacts that are triggered by your sensor values.

Power management is a very important aspect of the Internet of Things. Fortunately, there is a way to reduce power consumption of the ESP8266. It supports several sleep modes (modem, light and deep). The most efficient one is a deep sleep mode and radio capabilities are disabled when the chip goes in this mode. Power consumption drops dramatically to only 10 uA according to the documentation (around 70mA in normal operation), which can extend a battery life significantly. You can check the documentation for more details about different sleep modes.

If we want our chip to go to the deep sleep mode in the previous example, we could put this line of code ESP.deepSleep(15000000, WAKE_RF_DEFAULT) instead of delay(15000). Note that in this function time is set in microseconds. After 15 seconds, we want our chip to wakes up. We have to do a small hardware modification for this. You have to put a capacitor (I have used a 10uF electrolytic capacitor) between RST and GPIO 16 pins, and that’s it, we reduced power consumption of our chip significantly.

Circuit design

You have built your first IoT application! In the next posts, we will explore other communication protocols and IBM Bluemix platform that will allows us to build much more complex systems.

Lessons of this Series

Online computer science courses to jumpstart your future.
WP Engine Managed WordPress Hosting

Trending

Newsletter

Subscribe to our newsletter for good news, sent out every month.

Tags