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

Arrow left icon
Profile Icon Batrinu Profile Icon Tambrea
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (4 Ratings)
Paperback Nov 2017 196 pages 1st Edition
eBook
$20.98 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Batrinu Profile Icon Tambrea
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (4 Ratings)
Paperback Nov 2017 196 pages 1st Edition
eBook
$20.98 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$20.98 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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

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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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
$19.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
$199.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
$279.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 $ 115.97
ESP8266 Robotics Projects
$32.99
ESP8266 Home Automation Projects
$38.99
ESP8266 Internet of Things Cookbook
$43.99
Total $ 115.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 included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.