Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
ESP8266 Home Automation Projects
ESP8266 Home Automation Projects

ESP8266 Home Automation Projects: Leverage the power of this tiny WiFi chip to build exciting smart home projects

eBook
€15.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

ESP8266 Home Automation Projects

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 Preferences screen 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 INSTALLED message, 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:
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
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);   
} 
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:
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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Harness the power of the ESP8266 Wi-Fi chip to build an effective Home Automation System
  • Learn about the various ESP8266 modules
  • Configuring the ESP8266 and making interesting home automation projects
  • A step-by-step guide on the ESP8266 chip and how to convert your home into a smart home.

Description

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.

Who is this book for?

This book is targeted at people who want to build connected and inexpensive home automation projects using the ESP8266 Wi-Fi chip, and to completely automate their homes. A basic understanding of the board would be an added advantage.

What you will learn

  • Get, compile, install, and configure an MQTT server
  • Use the Wi-Fi connectivity feature to control appliances remotely
  • Control several home appliances using the ESP8266 Wi-Fi chip
  • Control and monitor your home from the cloud using ESP8266 modules
  • Stream real-time data from the ESP8266 to a server over WebSockets
  • Create an Android mobile application for your project
Estimated delivery fee Deliver to Slovakia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 28, 2017
Length: 196 pages
Edition : 1st
Language : English
ISBN-13 : 9781787282629
Category :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Slovakia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Nov 28, 2017
Length: 196 pages
Edition : 1st
Language : English
ISBN-13 : 9781787282629
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 87.97
ESP8266 Robotics Projects
€24.99
ESP8266 Home Automation Projects
€29.99
ESP8266 Internet of Things Cookbook
€32.99
Total 87.97 Stars icon
Banner background image

Table of Contents

8 Chapters
Getting Started with the ESP8266 Chevron down icon Chevron up icon
Building and Configuring Your Own MQTT Server Chevron down icon Chevron up icon
Building a Home Thermostat with the ESP8266 Chevron down icon Chevron up icon
Control Appliances from the ESP8266 Chevron down icon Chevron up icon
Using ESP8266 to Build a Security System Chevron down icon Chevron up icon
Securing Your Data Chevron down icon Chevron up icon
Real-Time Communication Chevron down icon Chevron up icon
Adding a Mobile Application to Your Smart Home Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(4 Ratings)
5 star 50%
4 star 0%
3 star 50%
2 star 0%
1 star 0%
Frank J DeCaro Sep 14, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good beginner book good examples
Amazon Verified review Amazon
Toth Andras Feb 12, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book for ESP8266 beginners and pro's too ! The Security chapter and ESP8266 MQTT broker sections are really surprizing!
Amazon Verified review Amazon
Angel Aug 29, 2019
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
It is a book that helps quickly to start in the programming of ESP8266 chps, in order to DIY IoT devices with WiFi connection. The downside of the Kindle edition (I do not know for paperback), when reading directly on the computer, is that many pages are badly formatted. The opening and closing curly brackets are not aligned and the code is not indented to the right. Sometimes the code is formatted in very narrow columns, so that each sentence is broken into 3 or more lines, which makes it very difficult to follow.I have some screenshots, to prove it.
Amazon Verified review Amazon
Amazon Customer Feb 11, 2020
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I don't often write reviews on books, but you probably need a heads up. I'm only at chapter 2 and the previous labs are out of date. It references APIs on a wunderground that are completely different and would take a lot of effort to reverse engineer them. The Thingspeak lab is also obsolete as that API is using https and not http which means change in the how the wifi library is used. I managed to get that one working with a bit of googling. I think its a good reference but don't expect all the labs to work. Like I said I'm only at chapter 2 and half the labs no longer work. The author has not bothered to create an amendment on the packtpub website to update the labs, only a minor typo correction.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela