ESP8266 Home Automation Projects

4 (3 reviews total)
By Catalin Batrinu
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

The ESP8266 is a low-cost yet powerful Wi-Fi chip that is becoming more popular at an alarming rate, and people have adopted it to create interesting projects.

With this book, you will learn to create and program home automation projects using the ESP8266 Wi-Fi chip. You will learn how to build a thermostat to measure and adjust the temperature accordingly and how to build a security system using the ESP8266. Furthermore, you will design a complete home automation system from sensor to your own cloud. You will touch base on data monitoring, controlling appliances, and security aspects.

By the end of the book, you will understand how to completely control and monitor your home from the cloud and from a mobile application. You will be familiar with the capabilities of the ESP8266 and will have successfully designed a complete ready-to-sell home automated system.

Publication date:
November 2017
Publisher
Packt
Pages
196
ISBN
9781787282629

 

Chapter 1. Getting Started with the ESP8266

It is impossible not to hear about the Internet of Things (IoT), which is starting to enter into our homes and our lives, together with the necessity of consuming and controlling a huge amount of data every day. We all carry an internet-connected smartphone and we are able to instantly find and connect with people around the world.

If we are able to connect and discuss with people around the world, why not control our houses, our cars, and our offices from our smartphone? This is where the IoT comes into the picture and lets us connect almost any object to the internet.

Currently, there are a few chips that are capable of internet connection in the market but one little fellow has attracted developers' attention because of its features and price.

This chip is ESP8266, a low-cost TCP/IP and a Wi-Fi enabled microcontroller developed by EspressIf Systems, a company located in Shanghai, and we will find out more about it in this book. In this chapter, we will cover the following topics:

  • Installing Arduino IDE
  • Configuring the Arduino IDE for ESP8266
  • Discovering ESP8266
  • Connecting your ESP to a Wi-Fi network
 

Starting with the ESP8266 chip


In order to start working with ESP8266, you will need a series of software and hardware components. ESP8266 is a 32-bit RISC low-cost microcontroller with Wi-Fi connectivity, capable of running at 80 MHz or 160 MHz. It has 64 KiB of instruction RAM and 96 KiB of RAM data.

For firmware and other data storage, an external QSPI flash is connected to it and the size can vary from 512 KiB to 4 MiB. The chip itself exposes 16 General Purpose Input/Output (GPIO) pins but some of them are used for the QSPI flash connection. The remaining pins are capable of Serial Peripheral Interface (SPI), I2C, I2S, Universal Asynchronous Receiver/Transmitter (UART), and one 10-bit Analog to Digital Converter (ADC).

The Wi-Fi capabilities are according to IEEE 80.11 b/g/n and provide WPA/WPA2 and WEP authentication but can also connect to open networks.

For this chapter, you will need just an ESP8266 module of your choice, since nowadays, there are many producers and board types available.

A good board can be found on Sparkfun.com or on e-commerce sites, such as banggood.com, or aliexpress.com but don't stop searching for them at your local electronics stores.

Now, the form factor of your board depends on your project constraints but for getting started with this chip, we can use one of the following boards:

  • Witty ESP12-F board
  • NodeMCU v1.0
  • WeeMos D1 mini

Either board will work fine but if you are a beginner, I'd recommend you to start with the Witty ESP12-F board because it already has:

  • LDR (Light Dependent Resistor) connected to the analog A0 input
  • RGB LED connected to GPIO 15, GPIO 12, and GPIO13
  • A push button connected to GPIO 4

Later, when we add other sensors to ESP8266, this module can be replaced with any of the other ESP8266 modules.

 

Installing Arduino IDE


ESP8266 can be used with the official EspressIf's SDKs that contain the NonOS and FreeRTOS SDKs writing code in C/C++, but other companies and people add other programming languages to it, such as Lua, Javascript, or MicroPhyton.

This book will use the NonOS SDK and as a development IDE, the Arduino IDE. In this part you will download the Arduino Software (IDE), configure it and install the ESP8266 SDK.

Downloading the Arduino Software IDE

To download the Arduino IDE, go to https://www.arduino.cc/en/Main/Software and download the latest version:

Now, you can download the version you want depending on your operating system. There are versions for Windows with and without admin rights, macOS X, and Linux for 32 bits, 64 bits, or ARM processors so that you can install and work, even on a Raspberry Pi.

After you have downloaded the Arduino IDE, you need to install it on your local computer.

If you are on Linux, you need to use the xz and tar command to open the Arduino IDE archive, then you can go into Arduino-1.8.2 and start it with sudo ./arduino.

In Windows, just launch the Arduino executable file, as follows:

Congratulations! You have installed the Arduino IDE and now it is time to configure it for ESP8266.

Configure Arduino IDE

To configure the Arduino IDE for ESP8266 you need to go to File | Preferences. The initial screen looks as follows:

In this screen, you can customize some fields as follows:

  • Sketchbook location: Here you can choose where your project files are stored.
  • Editor language: If you prefer another language to the default one, you can change this field here; but after this, you need to restart the IDE.
  • Editor font size: This is the font size used in the IDE.
  • Show verbose output during: compilation and upload: I suggest you check both of them to have a detailed output during compilation, where you can see files and their paths and also the upload.
  • Display line numbers: This field is good to see the line number in the right part of your IDE number.
  • Enable Code Folding: This field gives you more space on the screen.
  • Additional Boards Manager URLs: Here is the field that allows us to get and install the ESP8266 Xtensagcc compiler, required tools to flash the obtained firmware into the ESP8266 flash memory along with other board types. In this field, you need to add http://arduino.esp8266.com/stable/package_esp8266com_index.json and the Preferencesscreen will look as follows:

After you set up your preferences, you can click on the OK button. Don't forget that you are behind a proxy server; you need to fill in the details required in the Network tab.

Installing the ESP8266 SDK

After the preferences have been configured, now it is time to actually get the ESP8266 SDK and tools.

For this, you need to go to the following path and follow these steps:

  1. Go to Tools | Board: "Arduino/Genuino Uno" | Boards Manager... :
  2. Subsequently, the Boards Manager will be opened.
  1. Go to the end of the list and select the ESP8266 board and click on Install:
  2. Now, depending on your internet connection, this can take some time. Sit back and relax, you are about to enter into the IoT world.
  3. Look for the INSTALLEDmessage, as in this picture:
  1. Now, go back to Tools | Board: "Arduino/Genuino Uno" and you should see a lot of ESP8266-based boards in the lower section:
  1. Select NodeMCU 1.0 (ESP-12E Module) and go back to the Tools menu, where you will see other configurations that you can perform for ESP8266:
    • CPU Frequency: "80 MHz": This can be changed from 80 MHz to 160 MHz
    • The memory size of your module and the size of SPIFFS (1 or 3 MiB)
    • The upload speed for the UART interface between your computer and the ESP8266 module. Select from Upload Speed: "115200" so that the binary file will be flashed 8 times faster than the default value of 115200:
  1. If you now have a module, you can connect it to your computer. Going again to Tools menu now, you will see this from the Port menu and you can go and select your serial interface connected to the ESP8266 module. For Linux, you can select /dev/ttyUSB0 and for Windows, one of your COM ports.

Before starting any program, let's look at the IDE buttons:

Let's start from left to right:

  • Verify:  This allows you to compile and check your code for errors
  • Upload: This does what Verify does plus uploads generated firmware into ESP8266's flash memory
  • New: This opens a new window so that you can create another program
  • Open: This opens an existing program from your local disk
  • Save: This saves your files on the disk
  • Serial Monitor: This opens a window where you will be able to see and debug what you add into your program
 

How to install a library


In some chapters of this book, different libraries are needed; so let's see how a library can be installed.

The installed SDK has some basic libraries, but for sure, you will need more libraries to read various sensors, to parse JSON data, or to send MQTT messages. For the libraries that are referenced in the SDK repository, you just need to install them but for those that are not, you need to install them manually.

Libraries from the Arduino's repository

Some libraries exist in the official repository and you can install them in the following steps:

  1. If it exists, then just go to Sketch | Include Library | Manage Libraries:
  1. In a new window, delete the "Filter your search..." and write Arduino Json. The Arduino IDE will then search this library for you and if it has found it, you will be able to install it by clicking on it. You can also use this menu for updating a previously installed library or to change between versions of a library:
  1. After the library is installed, you will see the following screen:

Note

As an exercise, do the same for WiFiManager and PubSubClient libraries.

Library is not in the repository

Sometimes the library you need may not exist in the official repository but you may have found it on http://github.com as a ZIP archive.

To install the library, in this case, you need to perform the following steps:

  1. Download the ZIP file and install it manually. For this, go to Sketch|Include Library|Add .ZIP Library... and select the downloaded library from your disk and press Open.
  2. Include an existing library.
  3. To include an existing library, go to Sketch | Include Library and select the library you want to include in your sketch.
  4. The .h file will be added to your sketch and now you have access to the function a in this library to use them in your own program:
 

It is time for your first program


To begin this, let's evaluate the basic input and output of the Witty ESP8266 module.

The definition of pins is Light Dependent Resistor (LDR) on Witty and is attached to A0 (the analog input), the push button is connected to GPIO 4, and the LEDs are connected to GPIO 12, GPIO 13, and GPIO 15:

Delete everything that is in your Arduino IDE and replace it with the following code:

#define LDR     A0 
#define BUTTON  4 
#define RED     15 
#define GREEN   12 
#define BLUE    13 

The setup section will run only once after the module is reset or powered. The serial UART is started with 115200 bps, so the messages can be seen in the Serial Monitor window, where you also need to set the same speed in the lower-right corner of the window; otherwise, weird characters will be seen.

All pins are defined as INPUT or OUTPUT depending on their usage. The button and LDR are configured as input pins and all LED connected pins are set as output:

void setup()  
{ 
Serial.begin(115200); 
 
pinMode(LDR, INPUT); 
pinMode(BUTTON, INPUT); 
pinMode(RED, OUTPUT); 
pinMode(GREEN, OUTPUT); 
pinMode(BLUE, OUTPUT); 
} 

The loop() function is continuously running after the setup() and, in it:

  1. The analogRead function reads the value of the ambient light provided as 0-1 V by the LDR.
  2. The digitalRead function reads the value of GPIO 4, that can be either 0 V when the button is pressed or VCC 3.3 V if the button is not pressed.
  3. Show the data to the Serial Monitor with the Serial.print function. Serial.println just adds a new line.
  4. Write a random value between 0 and 1023 to GPIO 15 and GPIO 12 that will control the red and green LED color intensity. This is Pulse Width Modulation (PWM).
  5. Turn on the blue LED connected to GPIO 13.
  6. Wait 1000 ms (one second).
  7. Turn off the blue LED and continue from step 1:
void loop() 
{ 
Serial.print("LDR: "); 
Serial.println(analogRead(LDR)); 
Serial.print("BUTTON: "); 
Serial.println(digitalRead(BUTTON)); 
 
analogWrite(RED,   random(0,1023)); 
analogWrite(GREEN, random(0,1023)); 
digitalWrite(BLUE, HIGH); 
delay(1000); 
digitalWrite(BLUE, LOW); 
} 

In order to compile and flush the binary into the ESP8266 chip you need to press the Upload button.

Seeing the result

In the Serial Monitor output, as shown in the following image, we can see the values for the ambient light and the status of the button, where 0 means pressed and 1 means not pressed:

If you don't have a Witty module, you will need some extra parts such as resistors, LED, push buttons, and LDR sensors, according to the following schematics:

Let's review now the functions that allow you to control GPIO pins and the function that will print values in the Serial Monitor:

  • analogRead(pin): This reads the value on the A0 pin
  • digitalRead(pin): This reads the value for a specified pin, either LOW or HIGH
  • digitalWrite(pin, value): This writes a LOW or HIGH value to a digital pin
  • Serial.println (val): This prints data to a serial port as human-readable ASCII characters ending with \r and a new line character \n

Note

Using analogWrite(val), where val can be in the 0 to 1023 interval, a PWM digital output pin will have a voltage between 0 and 3.3V in 1023 steps.

 

Connecting ESP8266 to Wi-Fi


Until now, you have installed and configured the Arduino IDE for ESP8266 and learned how to control a LED, read an analog input, and dim a LED.

Now it is time to connect ESP8266 to Wi-Fi. Include ESP8266's Wi-Fi library and set up the SSID name and the Wi-Fi password:

#include <ESP8266WiFi.h> 
const char* ssid     = "your_wifi_name"; 
const char* password = "your_wifi_password"; 

In the setup section, Serial is started and configured to send data at 115200 bps; a 10 ms delay is added to allow Serial to finish and the GPIO from 12 to 15 are configured as output and their value is set to LOW:

void setup() { 
Serial.begin(115200); 
delay(10); 
pinMode(12, OUTPUT); 
pinMode(13, OUTPUT); 
pinMode(14, OUTPUT); 
pinMode(15, OUTPUT); 
 
digitalWrite(12,LOW); 
digitalWrite(13,LOW); 
digitalWrite(14,LOW); 
digitalWrite(15,LOW); 

We will start by connecting to a Wi-Fi network:

 
Serial.println(); 
Serial.println(); 
Serial.print("Connecting to "); 
Serial.println(ssid); 
 
WiFi.begin(ssid, password); 

We wait until the status indicates that ESP8266 is connected to the Wi-Fi network. After this, the Wi-Fi connected message is displayed along with the IP address assigned to it by the router. Your router needs to be DHCP capable and have the DHCP feature enabled:

while (WiFi.status() != WL_CONNECTED) { 
delay(500); 
Serial.print("."); 
  } 
 
Serial.println(""); 
Serial.println("WiFi connected");   
Serial.println("IP address: "); 
Serial.println(WiFi.localIP()); 
} 

In the loop section, the code checks to see whether the chip is connected to Wi-Fi and if this is true, the green LED will light on the Witty module:

void loop() 
{ 
if(WiFi.status() == WL_CONNECTED) 
digitalWrite(12, HIGH);   
} 

Note

As an exercise, you can light the RED led if there is no connectivity to your router, and the green LED otherwise.

The Serial Monitor will show the IP address assigned by the router, as follows:

 

Getting data from the internet


Now that we have connected ESP8266 to the Wi-Fi network, we can receive and send data on the internet. More than this, we can read data from the input or from the sensors attached to the board and send their values to the internet.

First, let's read some data and what is more interesting than the current weather data? Let's create an account on http://www.wunderground.com and then, go to https://www.wunderground.com/weather/api/d/pricing.htm, where you will purchase a key for $0, as shown in the following image. After filling some data about the project, you will have your key:

As you can see, with the developer key, you have 10 limited calls per minute that means you can get data every 6 seconds. Later in the code, we will get the data every 10 seconds.

To check your API_KEY, use it in a browser and check that you get any data. Replace APY_KEY with your own key:

After this if you navigate to this link in your browser, http://api.wunderground.com/api/APY_KEY/conditions/q/NL/Eindhoven.json; you will get the following JSON formatted response from the wunderground.com server:

Include the ESP8266WiFi library and the ESP8266HTTPClient library that will allow you to do an HTTP GET action to get the same JSON formatted message like you get using a browser:

#include <ESP8266WiFi.h> 
#include <ESP8266HTTPClient.h> 

Declare the SSID and the password of your Wi-Fi network:

const char* ssid     = "Your_WiFi_Name"; 
const char* password = "Your_WiFi_Password"; 
 
const String WUNDERGROUND_API_KEY = "YOUR_Wunderground_API_KEY"; 
const String WUNDERGROUND_COUNTRY = "NL"; 
const String WUNDERGROUND_CITY = "Eindhoven"; 

Construct the URL that will be used to get the data:

const String dataURL = "http://api.wunderground.com/api/"+WUNDERGROUND_API_KEY+"/conditions/q/"+WUNDERGROUND_COUNTRY+"/"+WUNDERGROUND_CITY+".json"; 

As usual, in the setup section, we will connect to the Wi-Fi network:

void setup() { 
Serial.begin(115200); 
delay(10); 
Serial.println(); 
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()); 
 
} 

In the loop, if the Wi-Fi status is connected, then you will instantiate an HTTPClient object named http and start getting data every 10 seconds from the previously constructed link. In the payload variable, you will have the entire response from the server:

void loop() 
{ 
if(WiFi.status() == WL_CONNECTED) 
  { 
HTTPClient http; 
http.begin(dataURL); 
inthttpCode = http.GET(); 
 
if(httpCode> 0) { 
            // HTTP header has been send and Server response header has been handled 
Serial.printf("[HTTP] GET... code: %d\n", httpCode); 
 
            // file found at server 
if(httpCode == HTTP_CODE_OK) { 
                String payload = http.getString(); 
Serial.println(payload); 
            } 
        }        
  } 
delay(10000); 
} 

If getting data every 10 seconds is too often, let's change it to once a minute by replacing the delay(10000) call that is blocking other code executions.

So, after const String WUNDERGROUND_CITY = "Eindhoven";, add two lines of code:

const long interval = 60 * 1000; 
unsigned long previousMillis = 0; 

Now, the loop function will change as follows:

void loop() 
{ 
unsigned long currentMillis = millis(); 
if(currentMillis - previousMillis >= interval)  
  { 
previousMillis = currentMillis;    
if(WiFi.status() == WL_CONNECTED) 
    { 
HTTPClient http; 
http.begin(dataURL); 
inthttpCode = http.GET(); 
 
if(httpCode > 0) { 
            // HTTP header has been send and Server response header has been handled 
Serial.printf("[HTTP] GET... code: %d\n", httpCode); 
 
            // file found at server 
if(httpCode == HTTP_CODE_OK) { 
                String payload = http.getString(); 
Serial.println(payload); 
            } 
        }        
    } 
  } 
} 

Now, the Serial Monitor will show a huge JSON with all the information about the weather from temperature to humidity, wind speed, dew point and much more every minute, as follows:

But what if you want to get only some specific data from this JSON? Fortunately, there is a Wunderground library for this. To install it, go to Sketch | Include Library | Manage Libraries and search for ESP8266 Weather Station. After installing this library, you also need to install the Json Straming Parser library that will parse the received JSON. You can follow these steps:

  1. Install the ESP8266 Weather Station library:
  1. Also, install the JSON Streaming Parser library:

Now, let's get the same data, so the same API_KEY will be used but the data is parsed by library functions:

  1. Include the headers' files for ESP8266 Wi-Fi.h, JSONListener.h, and WundergroundClient:
#include <ESP8266WiFi.h> 
#include <JsonListener.h> 
#include "WundergroundClient.h" 
  1. Define the API_KEY and set the metric Boolean variable:
const String  WUNDERGRROUND_API_KEY = "YOUR_API_KEY"; 
constboolean IS_METRIC = true; 
  1. Initialize WundergoundClient for the metric system:
WundergroundClientweather_data(IS_METRIC); 
  1. Also, initialize the Wi-Fi settings and constants used in getting the weather data:
const char* WIFI_SSID     = "YOUR_WIFI_SSID"; 
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD"; 
const String WUNDERGROUND_LANGUAGE = "EN"; 
const String WUNDERGROUND_COUNTRY = "NL"; 
const String WUNDERGROUND_CITY = "Eindhoven"; 
WiFiClientwifiClient; 
  1. Initialize the setup function to connect to the Wi-Fi network:
void setup() { 
Serial.begin(115200); 
delay(10); 
 
WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 
delay(20); 
Serial.print("Connecting to "); 
Serial.println(WIFI_SSID); 
while (WiFi.status() != WL_CONNECTED) { 
delay(500); 
Serial.print("."); 
  } 
Serial.println(""); 
Serial.println("WiFi connected!"); 
Serial.println(); 
} 
  1. In the loop function, get the data from the wunderground.com site every minute and show it in the Serial Monitor window:
void loop() { 
 
if ((millis() % (60 * 1000)) == 0) {  
Serial.println(); 
Serial.println("\n\nNext Loop-Step: " + String(millis()) + ":"); 
 
weather_data.updateConditions(WUNDERGRROUND_API_KEY, WUNDERGROUND_LANGUAGE, WUNDERGROUND_COUNTRY, WUNDERGROUND_CITY); 
 
Serial.println("wundergroundHours: " + weather_data.getHours()); 
Serial.println("wundergroundMinutes: " + weather_data.getMinutes()); 
Serial.println("wundergroundSeconds: " + weather_data.getSeconds()); 
Serial.println("wundergroundDate: " + weather_data.getDate()); 
 
Serial.println("wundergroundMoonPctIlum: " + weather_data.getMoonPctIlum()); 
Serial.println("wundergroundMoonAge: " + weather_data.getMoonAge()); 
Serial.println("wundergroundMoonPhase: " + weather_data.getMoonPhase()); 
Serial.println("wundergroundSunriseTime: " + weather_data.getSunriseTime()); 
Serial.println("wundergroundSunsetTime: " + weather_data.getSunsetTime()); 
Serial.println("wundergroundMoonriseTime: " + weather_data.getMoonriseTime()); 
Serial.println("wundergroundMoonsetTime: " + weather_data.getMoonsetTime()); 
Serial.println("wundergroundWindSpeed: " + weather_data.getWindSpeed()); 
Serial.println("wundergroundWindDir: " + weather_data.getWindDir()); 
 
Serial.println("wundergroundCurrentTemp: " + weather_data.getCurrentTemp()); 
Serial.println("wundergroundTodayIcon: " + weather_data.getTodayIcon()); 
Serial.println("wundergroundTodayIconText: " + weather_data.getTodayIconText()); 
Serial.println("wundergroundMeteoconIcon: " + weather_data.getMeteoconIcon(weather_data.getTodayIconText())); 
Serial.println("wundergroundWeatherText: " + weather_data.getWeatherText()); 
Serial.println("wundergroundHumidity: " + weather_data.getHumidity()); 
Serial.println("wundergroundPressure: " + weather_data.getPressure()); 
Serial.println("wundergroundDewPoint: " + weather_data.getDewPoint()); 
Serial.println("wundergroundPrecipitationToday: " + weather_data.getPrecipitationToday()); 
 
Serial.println(); 
Serial.println("---------------------------------------------------/\n"); 
  } 
} 
  1. The output for the Serial Monitor is as follows:

Note

Now, as an exercise, you can read the temperature and turn on or off an LED' if there are icing conditions or humidity and the temperature is too high outside.

 

Sending data to the internet


Now, let's send the same data to the internet. The first thing to do is to create an account on http://thingspeak.com and set up a channel. Each channel has eight fields that you can use to store the data transmitted by ESP8266.

As a free account, you need not send data more often than three times per minute. The advantage is that your data is stored on their server and you can see them on a nice graphic or embed them as an IFRAME in another web server.

In Channel Settings, create one field and name it Light, then go to the API key tab and get Write API KEY. Here, you can also define a read APY KEY if you have an application that wants to read data written by other modules. It is a rudimentary way of sharing data between modules.

Since the Witty module has the LDR, let's use it to log the data every minute on api.thingspeak.com:

#include <ESP8266WiFi.h> 
 
const char* WIFI_SSID     = "YOUR_WIFI_SSID"; 
const char* WIFI_PASSWORD = "YOUR WIFI_PASSWORD"; 
const char* host = "api.thingspeak.com"; 
const char* writeAPIKey = "YOUR_WRITE_API_KEY"; 
 
#define LDR     A0 

In the setup() function, which is executed once, the LDR pin is set as an INPUT pin and will connect the ESP8266 to the Wi-Fi network with the WiFi.begin(WIFI_SSID, WIFI_PASSWORD) function:

void setup()  
{ 
Serial.begin(115200); 
delay(10); 
pinMode(LDR, INPUT); 
WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 
delay(20); 
Serial.print("Connecting to "); 
Serial.println(WIFI_SSID); 
while (WiFi.status() != WL_CONNECTED) { 
delay(500); 
Serial.print("."); 
  } 
Serial.println(""); 
Serial.println("WiFi connected!"); 
Serial.println(); 
} 

In the loop() function every minute the light intensity will be read from the LDR sensor and post it on the Light field on a channel from https://thingspeak.com/:

void loop() 
{ 
if ((millis() % (60 * 1000)) == 0) {  
// make TCP connections 
WiFiClient client; 
const  int httpPort = 80; 
if (!client.connect(host, httpPort)) { 
return; 
  } 
 
  String url = "/update?key="; 
url+=writeAPIKey; 
url+="&field1="; 
url+=String(analogRead(LDR)); 
url+="\r\n"; 
Serial.println(url); 
  // Request to the server 
client.print(String("GET ") + url + " HTTP/1.1\r\n" + 
               "Host: " + host + "\r\n" +  
               "Connection: close\r\n\r\n"); 
  } 
 
} 

Let's see how the data looks after a few minutes:

Now, let's combine the sketches that read the weather from wunderground.com and this one that sends data to thingspeak.com. It will take the temperature, humidity, dew point, and precipitation and it will store them on thinkspeak.com so that later we can import them. Basically, this will be a weather logger:

#include <ESP8266WiFi.h> 
#include <JsonListener.h> 
#include "WundergroundClient.h" 

The following are the Wunderground settings:

const String  WUNDERGRROUND_API_KEY = "58dfbeb30d02af26"; 
const Boolean IS_METRIC = true; 
WundergroundClient weather_data(IS_METRIC); 
const char* WIFI_SSID     = "YOUR_WIFI_SSID"; 
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD"; 
const String WUNDERGROUND_LANGUAGE = "EN"; 
const String WUNDERGROUND_COUNTRY = "NL"; 
const String WUNDERGROUND_CITY = "Eindhoven"; 
const char* host = "api.thingspeak.com"; 
const char* writeAPIKey = "YOUR_WRITE_API_KEY"; 
WiFiClient wifiClient 

The following is the setup() function to connect to the Wi-Fi network:

void setup() { 
 
Serial.begin(115200); 
delay(10); 
 
WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 
delay(20); 
Serial.print("Connecting to "); 
Serial.println(WIFI_SSID); 
while (WiFi.status() != WL_CONNECTED) { 
delay(500); 
Serial.print("."); 
  } 
Serial.println(""); 
Serial.println("WiFi connected!"); 
Serial.println(); 
} 

In the loop() function, every minute weather data will be retrieved from wunderground.com and it will post it to thingspeak.com. Along with the temperature, pressure, precipitation and dew point more information will be printed in the serial output like moon phase, sunrise or sunset, information that can be used if you plan to add a display module to visualize all weather conditions:

void loop() { 
if ((millis() % (60 * 1000)) == 0) {  
Serial.println(); 
Serial.println("\n\nNext Loop-Step: " + String(millis()) + ":"); 
 
weather_data.updateConditions(WUNDERGRROUND_API_KEY, WUNDERGROUND_LANGUAGE, WUNDERGROUND_COUNTRY, WUNDERGROUND_CITY); 
 
Serial.println("wundergroundHours: " + weather_data.getHours()); 
Serial.println("wundergroundMinutes: " + weather_data.getMinutes()); 
Serial.println("wundergroundSeconds: " + weather_data.getSeconds()); 
Serial.println("wundergroundDate: " + weather_data.getDate()); 
 
Serial.println("wundergroundMoonPctIlum: " + weather_data.getMoonPctIlum()); 
Serial.println("wundergroundMoonAge: " + weather_data.getMoonAge()); 
Serial.println("wundergroundMoonPhase: " + weather_data.getMoonPhase()); 
Serial.println("wundergroundSunriseTime: " + weather_data.getSunriseTime()); 
Serial.println("wundergroundSunsetTime: " + weather_data.getSunsetTime()); 
Serial.println("wundergroundMoonriseTime: " + weather_data.getMoonriseTime()); 
Serial.println("wundergroundMoonsetTime: " + weather_data.getMoonsetTime()); 
Serial.println("wundergroundWindSpeed: " + weather_data.getWindSpeed()); 
Serial.println("wundergroundWindDir: " + weather_data.getWindDir()); 
 
Serial.println("wundergroundCurrentTemp: " + weather_data.getCurrentTemp()); 
Serial.println("wundergroundTodayIcon: " + weather_data.getTodayIcon()); 
Serial.println("wundergroundTodayIconText: " + weather_data.getTodayIconText()); 
Serial.println("wundergroundMeteoconIcon: " + weather_data.getMeteoconIcon(weather_data.getTodayIconText())); 
Serial.println("wundergroundWeatherText: " + weather_data.getWeatherText()); 
Serial.println("wundergroundHumidity: " + weather_data.getHumidity()); 
Serial.println("wundergroundPressure: " + weather_data.getPressure()); 
Serial.println("wundergroundDewPoint: " + weather_data.getDewPoint()); 
Serial.println("wundergroundPrecipitationToday: " + weather_data.getPrecipitationToday()); 
 
WiFiClient client; 
const int httpPort = 80;
if (!client.connect(host, httpPort)) { 
return; 
    } 
 
    String url = "/update?key="; 
url+=writeAPIKey; 
url+="&field1="; 
url+=String(weather_data.getCurrentTemp()); 
url+="&field2="; 
url+=String(weather_data.getPressure()); 
url+="&field3="; 
url+=String(weather_data.getDewPoint());   
url+="&field4="; 
url+=String(weather_data.getPrecipitationToday());    
url+="\r\n"; 
Serial.println(url); 
    // Request to the server 
client.print(String("GET ") + url + " HTTP/1.1\r\n" + 
               "Host: " + host + "\r\n" +  
               "Connection: close\r\n\r\n"); 
 
Serial.println("---------------------------------------------------/\n"); 
  } 
} 

After a few minutes, you can see the values received by the ESP8266 from wunderground.com and posted on thingspeak.com displayed on four graphs:

 

 

 

Summary


The first step in developing IoT applications has been completed. Now, you have the knowledge for installing and configuring the Arduino IDE for the ESP8266 development, and on how to transmit and receive data, to and from the internet. The next step will be to make the ESP8266 modules talk to each other, no matter where they are located.

About the Author

  • Catalin Batrinu

    Catalin Batrinu graduated from the Politehnica University of Bucharest in Electronics, Telecommunications, and Information Technology. He has been working as a software developer in telecommunications for the past 16 years. He has worked with old protocols and the latest network protocols and technologies, so he has experienced all transformations in the telecommunication industry. He has implemented many telecommunications protocols, from access adaptations and backbone switches to high-capacity, carrier-grade switches on various hardware platforms from Wintegra and Broadcom.

    Internet of Things came as a natural evolution for him and now he collaborates with different companies to construct the world of tomorrow that will make our life more comfortable and secure. Using the ESP8266, he has prototyped devices such as irrigation controllers, smart sockets, window shutters, Digital Addressable Lighting Controls, and environment controls, all of them controlled directly from a mobile application over the cloud. An MQTT broker with bridging and a WebSockets server was even developed for the ESP8266. Soon, all those devices will be part of our daily life, so we will all enjoy their functionality.

    Browse publications by this author

Latest Reviews

(3 reviews total)
Basically, an introduction to the Arduino IDE.
Alle aspecten van home worden behandeld zelfs MQTT is van de partij.
fast and no problems, i can do it again

Recommended For You

Internet of Things Projects with ESP32

Create and program Internet of Things projects using the Espressif ESP32.

By Agus Kurniawan
ESP8266 Internet of Things Cookbook

Exploring the low cost WiFi module

By Marco Schwartz
Hands-On Internet of Things with MQTT

Develop a variety of projects and connect them to microcontrollers and web servers using the lightweight messaging protocol MQTT

By Tim Pulver
ESP8266 Robotics Projects

Build simple yet amazing robotics projects using ESP8266

By Pradeeka Seneviratne