Tải bản đầy đủ (.pdf) (226 trang)

Internet of things with ESP8266 by marco schwartz

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (13.69 MB, 226 trang )


Internet of Things with
ESP8266

Build amazing Internet of Things projects using the
ESP8266 Wi-Fi chip

Marco Schwartz

BIRMINGHAM - MUMBAI

[ FM-1 ]


Internet of Things with ESP8266
Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author(s), nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2016



Production reference: 1260716

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78646-802-4
www.packtpub.com

[ FM-2 ]


Credits
Author

Project Coordinator

Marco Schwartz

Kinjal Bari

Reviewer

Proofreader

Catalin Batrinu

Safis Editing


Commissioning Editor

Indexer

Pratik Shah

Pratik Shirodkar

Acquisition Editor

Graphics

Prachi Bisht

Kirk D'Penha

Content Development Editor
Mamta Walkar

Production Coordinator
Shantanu N. Zagade

Technical Editor

Cover Work

Naveenkumar Jain

Shantanu N. Zagade


Copy Editor
Sneha Singh

[ FM-3 ]


About the Author
Marco Schwartz is an electrical engineer, an entrepreneur, and a blogger. He has a

master's degree in electrical engineering and computer science from Supélec, France,
and a master's degree in micro engineering from the Ecole Polytechnique Fédérale de
Lausanne (EPFL) in Switzerland.
He has more than five years of experience working in the domain of electrical
engineering. Marco's interests gravitate around electronics, home automation,
the Arduino and Raspberry Pi platforms, open source hardware projects,
and 3D printing.
He has several websites about Arduino, including the Open Home Automation
website, which is dedicated to building home automation systems using open
source hardware.
Marco has written another book on home automation and Arduino, called Home
Automation With Arduino: Automate Your Home Using Open-source Hardware. He has
also written a book on how to build Internet of Things projects with Arduino, called
Internet of Things with the Arduino Yun, Packt Publishing.

[ FM-4 ]


About the Reviewer
Catalin Batrinu graduated from the Politehnica University of Bucharest in


Electronics, Telecommunications and Information Technology. He has been
working as a software developer in telecommunications for the past 16 years.
He has worked with old protocols and the latest network protocols and technologies,
so he has seen all the transformations in the telecommunication industry.
He has implemented many telecommunications protocols, from access adaptations
and backbone switches to high capacity, carrier-grade switches on various hardware
platforms from Wintegra and Broadcom.
Internet of Things came as a natural evolution for him and now he collaborates with
different companies to construct the world of tomorrow that will make our life more
comfortable and secure.
Using ESP8266, he has prototyped devices such as irrigation controllers, smart
sockets, window shutters, Digital Addressable Lighting Controls, and environment
controls, all of them being controlled directly from a mobile application over the
cloud. Even an MQTT broker with bridging and a websockets server was developed
for the ESP8266. Soon, all those devices will be part of our daily life, so we will all
enjoy their functionality.
You can read his blog at .

[ FM-5 ]


www.PacktPub.com
eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.
com and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt

books and eBooks.
TM

/>
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser

[ FM-6 ]


Table of Contents
Prefacev
Chapter 1: Getting Started with the ESP8266
1
How to choose your ESP8266 module
1
Hardware requirements
4
Hardware configuration
7
Installing the Arduino IDE for the ESP8266
10
Connecting your module to your Wi-Fi network
11

Summary13

Chapter 2: First Projects with the ESP8266

15

Chapter 3: Cloud Data Logging with the ESP8266

25

Chapter 4: Control Devices from Anywhere

37

Controlling an LED
15
Reading data from a GPIO pin
17
Grabbing the content from a web page
18
Reading data from a digital sensor
20
Summary24
Hardware and software requirements
25
Hardware configuration
26
Testing the sensor
28
Logging data to Dweet.io

30
Displaying data using Freeboard.io
31
Summary35
Hardware and software requirements
38
Configuring the ESP8266 module and controlling an LED
39
Controlling the LED from a cloud dashboard
44
Controlling the lamp from anywhere in the world
45
Summary47
[i]


Table of Contents

Chapter 5: Interacting With Web Services

49

Chapter 6: Machine-to-Machine Communications

71

Chapter 7: Sending Notifications from the ESP8266

89


Chapter 8: Controlling a Door Lock from the Cloud

109

Chapter 9: Building a Physical Bitcoin Ticker

121

Hardware and software requirements
Getting weather data from Yahoo
Posting temperature and humidity data to Twitter
Creating a new Facebook post from the ESP8266
Summary

49
51
56
62
69

Hardware and software requirements
71
Simple machine-to-machine communication
73
Building a light-activated relay
82
Summary87
Hardware and software requirements
89
Hardware configuration

91
Sending an e-mail notification
91
Sending data via text message
99
Receiving alerts via push notifications
103
Summary107
Hardware and software requirements
Configuring the hardware
Configuring the ESP8266 board
Controlling the lock from the cloud
Receiving notifications when the lock is opened
Summary

109
111
112
113
114
119

What is Bitcoin?
121
Online Bitcoin services
122
Hardware and software requirements
125
Configuring the hardware
126

Testing the ticker
127
Adding alert LEDs to the ticker
132
Summary134

[ ii ]


Table of Contents

Chapter 10: Wireless Gardening with the ESP8266

135

Chapter 11: Cloud-Based Home Automation System

151

Chapter 12: Cloud-Controlled ESP8266 Robot

175

Chapter 13: Building Your Own Cloud Platform to Control
ESP8266 Devices

191

Hardware and software requirements
Hardware configuration

Creating alerts to water your plant
Monitoring the temperature and humidity
Automating your gardening
Summary
Hardware and software requirements
Hardware configuration
Controlling your home from a dashboard
Creating a cloud alarm system
Automating your home
Summary

135
137
139
145
147
149

151
152
154
160
163
173

Hardware and software requirements
175
Hardware configuration
180
Testing the motors

182
Connecting the robot to the cloud
185
Controlling the robot from a dashboard
188
Summary190

Hardware and software requirements
191
Hardware configuration
192
Creating a cloud server
193
The aREST cloud server code
196
Deploying the server
198
Connecting the ESP8266 board to your cloud server
201
Summary204

Index205

[ iii ]



Preface
The Internet of Things (IoT) is an exciting field that proposes to have all the devices
that surround us connected to the Internet and interacting with us, but also between

each other. It's estimated that there will be 50 billion IoT devices in the world by
the year 2020.
On the other hand, the ESP8266 chip is a small, cheap (less than $5), and powerful
Wi-Fi chip that is also really easy to program. Therefore, it is just the perfect tool
to build inexpensive and nice IoT projects. In this book, you are going to learn
everything you need to know on how to build IoT projects using the ESP8266
Wi-Fi chip.

What this book covers

Chapter 1, Getting Started with the ESP8266, will teach all you need to know about how
to choose your ESP8266 board and upload your first sketch to the chip.
Chapter 2, First Projects with the ESP8266, will explain the basics of the ESP8266 by
making some real simple projects.
Chapter 3, Cloud Data Logging with the ESP8266, will dive right into the core of the
topic of the book, and build a project that can log measurement data on the cloud.
Chapter 4, Control Devices from Anywhere, will reveal how to control devices from
anywhere in the world using the ESP8266.
Chapter 5, Interacting With Web Services, will show how to use the ESP8266 to interact
with existing web platforms such as Twitter.

[v]


Preface

Chapter 6, Machine-to-Machine Communications, will explain how to make ESP8266
chips talk to each other via the cloud, to build applications that don't require
human intervention.
Chapter 7, Sending Notifications from the ESP8266, will show how to send automated

notifications from the ESP8266, for example, via text message or email.
Chapter 8, Controlling a Door Lock from the Cloud, will use what we learned so far in the
book to build our first application: a door lock that can be controlled remotely.
Chapter 9, Building a Physical Bitcoin Ticker, will use the ESP8266 for a fun project:
making a physical display of the current price of Bitcoin.
Chapter 10, Wireless Gardening with the ESP8266, will dive into a more complex,
by learning how to automate your garden with the ESP8266.
Chapter 11, Cloud-Based Home Automation System, will show how to build the essential
blocks of an home automation system using the ESP8266.
Chapter 12, Cloud-Controlled ESP8266 Robot, will explain how to use the ESP8266 to
control a mobile robot from anywhere in the world.
Chapter 13, Building Your Own Cloud Platform to Control ESP8266 Devices, will reveal
how to build our own cloud platform for your ESP8266 projects.

What you need for this book

For this book, you will need to have the Arduino IDE, which we will use for all
the projects of the book. You will learn how to install it and configure it in the first
chapter of the book.
The chapters of the book were also written with a progressive complexity, so even
if you don't know a lot about Arduino and/or the ESP8266 you will be able to learn
as you progress through the chapters. However, previous experience in programing
(especially in C++ and/or JavaScript) is recommend for this book.

Who this book is for

This book is for those who want to build powerful and inexpensive IoT projects
using the ESP8266 Wi-Fi chip, including those who are new to IoT, or those who
already have experience with other platforms such as Arduino.


[ vi ]


Preface

Conventions

In this book, you will find a number of text styles that distinguish between different
kinds of information. Here are some examples of these styles and an explanation of
their meaning.
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"We can include other contexts through the use of the include directive."
A block of code is set as follows:
void loop() {
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}

Any command-line input or output is written as follows:
# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample
/etc/asterisk/cdr_mysql.conf

New terms and important words are shown in bold. Words that you see on

the screen, for example, in menus or dialog boxes, appear in the text like this:
"Open Boards Manager from the Tools | Board menu and install the esp8266
platform, as shown."
Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

[ vii ]


Preface

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or disliked. Reader feedback is important for us as it
helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail , and mention
the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at

. If you purchased this book elsewhere, you can visit
and register to have the files e-mailed directly
to you.
You can download the code files by following these steps:
1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder
using the latest version of:
• WinRAR / 7-Zip for Windows
• Zipeg / iZip / UnRarX for Mac
• 7-Zip / PeaZip for Linux
[ viii ]


Preface

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/
diagrams used in this book. The color images will help you better understand the
changes in the output. You can download this file from />sites/default/files/downloads/InternetofThingswithESP8266_
ColorImages.pdf.

Errata


Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting ktpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or added
to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to />content/support and enter the name of the book in the search field. The required
information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.
Please contact us at with a link to the suspected
pirated material.
We appreciate your help in protecting our authors and our ability to bring you
valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at
, and we will do our best to address the problem.

[ ix ]




Getting Started with the
ESP8266
In this chapter, we are going to start by setting up the ESP8266 chip. We will learn
how to choose the right module for your project and get all the additional hardware
you need to use the chip. We will also see how to connect the ESP8266 to your
computer, so you can program it using a USB cable.
Then, we are going to see how to configure and upload code to the ESP8266 chip.
For that, we will be using the Arduino IDE. This makes using the ESP8266 much
easier, as we will be using a well-known interface and language to configure the
chip. We will also be able to use most of the already existing Arduino libraries for
our projects. Let's start!

How to choose your ESP8266 module

We are first going to see how to choose the right ESP8266 module for your project.
There are many modules available in the market and it is quite easy to get lost with
all the choices available.

[1]


Getting Started with the ESP8266

The first one that you have probably heard of is the small ESP8266 Serial Wireless
Transceiver module:

This module is the most famous one, as it is really small and only costs $5. However,

the number of accessible GPIO pins (input/output pins) is quite limited. It is also
difficult to plug it into a standard breadboard.
If you choose this module, there are some projects in this book that you might not be
able to do. For example, you won't be able to do the projects using analog sensors, as
the analog input pin is not accessible.
You can find more information about this module at:
/>
But there are many other modules on the market that give you access to all the pins
of the ESP8266. For example, I really like the ESP8266 Olimex module, which is also
cheap (around $10):
[2]


Chapter 1

This module can easily be mounted on a breadboard and you can easily access all the
pins of the ESP8266. This is the one I will use for most of this book and therefore I
also recommend that you use a similar module.
You can find additional details about this module at:
/>
One other choice is to use a board based on the ESP-12, which is a version of the
ESP8266 made to be integrated on PCBs. This version also gives you access to all the
pins of the ESP8266. It is relatively easy to find breakout boards for this chip. For
example, this is a board that I bought on Tindie:

[3]


Getting Started with the ESP8266


You can find more information about this module on:
/>
You can also get your hands on the Adafruit ESP8266 breakout board, which also
integrates the ESP-12:
/>
Another solution is to use the NodeMCU development kit, which is similar to the
Olimex board but also has an integrated USB-to-Serial converter, as well as an
onboard power supply. It is easier to use, but was hard to find at the time this book
was written. You can get more information on the NodeMCU website:
/>
Note that with the NodeMCU module, you will have to translate the pins from the
module to the pins defined in the ESP8266 Arduino IDE, which we are going to use.
You will find the correspondence between pins here:
/>gpio_map

Hardware requirements

Let's now take a look at the things we need to make the ESP8266 chip work. It is
usually, but incorrectly, assumed that you just need this little chip and nothing else
to make it work, but we are going to see that it is not true.
First, you will need some way to program the ESP8266. You can use an Arduino
board for that, but for me the really great thing about the ESP8266 is that it can
function completely autonomously, using the onboard processor.

[4]


Chapter 1

So to program the chip, I will use a USB FTDI programmer.

Note that it has to be compatible with the logic level of the
ESP8266 chip, so 3.3V.

I have used a module that can be switched between 3.3V and 5V:

You will also need a dedicated power supply to power the chip. This is a point that
is often forgotten and leads to a lot of issues. If you are, for example, trying to power
the ESP8266 chip from the 3.3V coming from the FTDI board or from an Arduino
board, it simply won't work correctly.

[5]


Getting Started with the ESP8266

Therefore, for most ESP8266 modules, you need a dedicated power supply that
can deliver at least 300 mA to be safe. Some boards have an integrated micro-USB
port and a voltage regulator that can provide the required current to the ESP8266,
but that's not the case with the board we will use in this first chapter. I used a
breadboard power supply that can deliver up to 500 mA at 3.3V:

This is a list of all the components that you will need to use the ESP8266 chip:
• ESP8266 Olimex module ( />• Breadboard 3.3V power supply ( />products/13032)
• 3.3V FTDI USB module ( />• Breadboard ( />• Jumper wires ( />
[6]


Chapter 1

Hardware configuration


We are now going to take a look at the way to configure the hardware for the first
use of your ESP8266 board. This is how we connect the different components:

Depending on the board you are using, the pins can have different names. Therefore,
I created pictures to help you out with each module. These are the pins you will need
on the small ESP board:

[7]


Getting Started with the ESP8266

This is the same for the ESP-12 board mounted on a breadboard adapter:

Finally, this is the picture for the Olimex board:

[8]


×