Sunteți pe pagina 1din 73

Table of Contents

INTRODUCTION
GETTING STARTED
CONTROL AN LED FROM BROWSER
Control Electrical Devices from Web browser.
Display Temperature and Humidity data on (I2C) LCD
Analog Temperature sensor with Nodemcu
Sensors Data To Thingspeak
SD card with ESP8266
SD card Webserver
Scan the Wi-Fi network surrounded you
Real-time clock Using ESP8266
Create a weather widget using Nodemcu
Components Need for this book
Port Forwarding Example
Contact and Source Codes:

2
3
INTRODUCTION
The ESP8266 is a highly integrated chip designed by Espressif Systems for the
needs of an increasingly demand for low cost IOT solutions. The manufacturer
advertises it offers a complete and self-contained Wi-Fi networking solution,
allowing it to either host applications or offload all Wi-Fi networking functions
from another application processor.
The ESP8266 has powerful on-board processing and storage capabilities that
allow it to be used with sensor and other application specific devices through it
GPIOs with minimal development up-front and minimal loading during runtime. Its
high degree of on-chip integration allows for minimal external circuitry. The entire
solution, including the modules, is designed to occupy minimal PCB area.
The ESP8266 was originally marketed as a low cost add-on to Arduino boards
which was in need of such devices to connect to external world, when people
started to work the low cost chip with arduino they realised that they can eliminate
the Arduino boards and understand this chip can be used as a stand-alone device. In
less than a year, the ESP8266 has rocketed in popularity, and is now so well
supported and developed.
Technical Features
802.11 b/g/n
WiFi Direct (P2P), soft-AP
Integrated TCP/IP protocol stack
Integrated TR switch, balun, LNA, power amplifier and matching network
Integrated PLLs, regulators, DCXO and power management units
+19.5dBm output power in 802.11b mode
Power down leakage current of <10uA
Integrated low power 32-bit CPU could be used as application processor
SDIO 1.1/2.0, SPI, UART
STBC, 11 MIMO, 21 MIMO
A-MPDU & A-MSDU aggregation & 0.4ms guard interval
Wake up and transmit packets in < 2ms
Standby power consumption of < 1.0mW (DTIM3)
Operating temperature range -40C ~ 125C.

4
The ESP8266 chip should be powered by a 3.3V Power supply, it can consume
10uA to 170mA, the vast difference can be explained, when transmitting at full
power, it can consume 170mA but when in a deep sleep, it only need 10uA. That is
a difference between current consumption. This means that the runtime of an
ESP8266 on a fixed current reservoir is not just a function of time but also of what
it is doing during that time and it depend upon on the function it is going to do
during the run time of the device.
ESP8266 can be used as an external Wi-Fi module, using the standard AT command
set Firmware by connecting it to any microcontroller using the serial UART, or
directly serves as a Wi-Fi enabled microcontroller, by programming a new
firmware using the SDK. The ESP8266 is designed to be used with a partner
memory module and this is most commonly flash memory. Most of the modules
come with some flash associated with them.
ESP8266 application subject
Smart Power Plug
Home Automation
mesh network
industrial wireless control
Baby Monitor
Network Camera
sensor networks
wearable electronics
wireless location-aware devices
Security ID tag
wireless positioning system signals

General Purpose IO
Esp8266-12 having total of 16 GPIO pins. The firmware can assign them different
functions. Each GPIO can be configured internal pullup / pulldown resistors
available software registers sampled input, triggering edge or level CPU interrupt
input, trigger level wake-up interrupt input, open-drain or complementary push-pull
output drivers, software register output source or sigma-delta PWM DAC. These
pins are multiplexed with other functions, such as the main interface, UART, SI,
Bluetooth co-existence and so on.

ESP8266 Modules:
However the first introduced board which not much breadboard friendly integrated

5
circuit comes in a small package. Obviously, unless you are a master in soldering
you are not going to do much with that. The good news is ESP8266-based boards
are available from several vendors with different breakout boards that make the job
much easier for us. Here is the list of some of the more common modules.

ESP-01

This is the first and simplest board using the ESP8266. It allows attaching serial
lines, and only breaks out two GPIO pins for native usage. This is also the cheapest
and can be purchased from many Chinese suppliers at $2
ESP-12
The current most popular and hot topic is the ESP-12 which has flexible
configuration available today. It exposes the most GPIO pins for use. The basic
ESP-12 module really needs its own expander module to make it breadboard and
0.1 strip board friendly. If you are currently using Arduino, you need to stand up

6
and take note. Buy a ESP8266 12 based Wi-Fi module, I have used a board called
NodeMCU development board, which has an on board ESP8266 and everything we
need to get started with awesome Wi-Fi chip, this board eliminates the need to have
external USB serial convertor to connect with your PC or Laptop to program it and
also comes with on board 3.3v Voltage regulator.

There are many ESP 12 development kit available on the market, some of the other
development board from popular vendors are listed below.
Adafruit HUZZAH ESP8266 breakout

The Adafruit Huzzah is a breakout board for the ESP8266. This was designed to
make working with ESP8266 chip super easy. This device comes with an on-board

7
antenna, and plenty of pins.
Wemos D1

This board is like arduino breakout board for ESP8266, which looks like an
Arduino and it has got everything to get start with. The arduino like feature allows
the user to use this board easily; this board has the entire pin marking as Nodemcu
boards. Behind the board we can find the real GPIO pin number which makes very
easy to use this board with any compiler for programming. I have used Nodemcu
development kit for the experiments that done in this book, lets get into deeper
with this board, you can also use any other vendor board, I highly recommend for
the novice user to get start with development board, instead of generic chips, where
the generic chips needs proper regulated voltage and it also requires a USB
programmer to upload the program into its memory.
Pin Definition of Nodemcu Development kit

Nodemcu Development kit circuit

8
9
GETTING STARTED
Installing the Arduino IDE with ESP8266 support
To install the support for ESP8266, one must download the current version of
Arduino IDE. This can be downloaded from the website here, file size is about
80.7 MB, make sure you are downloading Arduino 1.6.5 which is the stable
version which supports the ESP82366 package..
Install the Arduino Software which you have just downloaded, which is very easy
to install just click next to complete the installation process. Next launch the
Arduino IDE and go to files and click on preference in the Arduino IDE.

In the Additional Boards Manager URLs: copy and paste the ESP8266 support
Package URL which is http://arduino.esp8266.com/stable/package_esp8266com_index.json
Click ok to close the preference Tab, after completion of this step, go to Tools and
board, and select the Boards Manager.

10
Navigate to esp8266 by ESP8266 community and install the software for Arduino.
This will contact the Internet and download the necessary files for ESP8266
support. Once completed, in the Arduino IDE Board selections, you will find the
different ESP8266 modules that are supported from the Arduino IDE.
If you finding any difficulty in installation process you can also find the video
tutorial which explains all the steps here
Once all the above process has been completed we are ready to program our
ESP8266 using Arduino IDE.

I already said I am using Nodemcu development kit for ESP8266 for this tutorial;
the above fritzing explains how to connect the LED with Nodemcu kit. I connected
the anode (positive terminal) to the D7 pin of Nodemcu kit. If you go to the
previous chapter and check with the pin configuration of Nodemcu kit, you can
understand the pin 13 has mapped to D7 pin of Nodemcu. The reason why I used
D7 pin for this example is, I uploaded the basic blink program that comes with the
examples program in the Arduino IDE which is connected with 13th pin of Arduino.

11
Go to board and select the type of ESP8266 boards you are using and select the
correct COM port that you have connected your PC or Laptop and upload the
program to the ESP8266 device.

void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever


void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

This program just turn ON and OFF the LED that connected to the D7 pin of
Nodemcu development board or GPIO13 pin of ESP8266, this program will turn
ON the LED for a second and turn OFF the led for a second the time between ON
and OFF can be vary by increasing the delay time.

12
CONTROL AN LED FROM BROWSER
This is the actual start of the tutorial, in this chapter we going to learn how
to control an LED from web browser. The things you need to make is tutorial are an
ESP8266 based development board or a generic board and an LED. In this lesson,
you will use your ESP8266 to create a simple Web server using the inbuilt library;
your device will be able to answer a HTTP request with your ESP8266. After
opening a browser navigate to the IP address your device returning this can be find
by opening the serial monitor in the Arduino IDE, your ESP8266 will respond with
just enough HTML for a browser to display the On and Off buttons for the LED.

Connect the LED to D7 pin of Nodemcu or any other pin you like. If you are making
any changes to the hardware connection make sure you also changing the respective
pin number in the programming too, if you have any doubts regarding this tutorial
you can also follow the link to know how this can be done, click here.

Here comes the Program:


#include <ESP8266WiFi.h>

const char* ssid = "......"; // Edit your Wifi Name


const char* password = "......."; // Your Wifi password

int ledPin = 13; // GPIO13 pin mapped for D7 pin in nodemcu


WiFiServer server(80);

13
void setup() {
Serial.begin(115200);
delay(10);

pinMode(ledPin, OUTPUT); // 13th pin has configured to o/p


digitalWrite(ledPin, LOW); // beginning the pin will turned off

// Connect to WiFi network


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");

// Start the server


server.begin();
Serial.println("Server started");

// Print the IP address


Serial.print("Use this URL to connect: ");
Serial.print("http://");

14
Serial.print(WiFi.localIP());
Serial.println("/");

void loop() {

int sensorReading = analogRead(17);


// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Wait until the client sends some data


Serial.println("new client");
while(!client.available()){
delay(1);
}

// Read the first line of the request


String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

// Match the request

int value = LOW;


if (request.indexOf("/LED=ON") != -1) {

15
digitalWrite(ledPin, HIGH);
value = HIGH;
}
if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(ledPin, LOW);
value = LOW;
}

// Set ledPin according to the request


//digitalWrite(ledPin, value);

// Return the response


client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("analog input ");
client.print(" is ");
client.print(sensorReading);
client.println("<br />");

client.println("<br><br>");
client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a><br
/>");
client.println("</html>");

delay(1);
Serial.println("Client disonnected");

16
Serial.println("");

}
// code ends here

Copy the Program to your Arduino IDE and upload to your ESP8266. We will
connect the Esp8266 to the Wi-Fi router using SSID and password of your Home
network Wifi , where the esp8266 connect to our wifi and create a webserver,
which can be accessed by the ip address returned by the ESP8266 after
successfully connected to the Home network, IP address can be find by looking
through the serial Monitor of the Arduino window or you can also log into your
Wifi router and check for the list of clients connected to your Wi-Fi router.
Esp8266 code is very similar to the Arudino code.
Starts with a setup( ) function
Followed by a loop ( ) function
Serial commands are supported in order to send data to the terminal
Other arduino commands are supported as well. delay(), millis(),
digitalWrite() etc.
WiFi library - To connect WiFi simply use the code below:
WiFi.disconnect();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Client Library- With this library you can connect a host (client.connect() ) , send
a GET request (client.print()), listen and receive data (client.available(),
client.readstringUntil('\r')).
Server Library- Allows you to create a server, which upon
request (server.available()) creates a client that will handle the request and send a
response.

17
Control Electrical Devices from Web browser.
In the previous tutorial we have controlled an LED from a web browser;
this tutorial is same as the last one. In this tutorial instead of an LED we are going
to control electrical devices like lights , fans or any other electrical devices you
like to control can be done by following this tutorial, you might finding many
dedicated app that are used to control electrical devices, what if you want to
control a device from any device ? Yes that's possible by using this web server.
Components required for completing this experiment, you need relay, the number
relay needed based on the number of devices you'd like to control. A relay is an
electronic switch in simple words, a 5v relay module can be easily interfaced with
ESP8266, you should be very careful when using this tutorial, if you are not sure
how high voltage electrical devices work or how to use relay for connecting those
devices please don't follow this tutorial, some knowledge in electrical circuit and
devices needed for this tutorial.
As, I said earlier this is an extended version of the Previous tutorial, where extra
html codes were added to control four devices, and digitalRead() command is used
to return the status of the devices, you can also check the following video to know
how this works with different devices and how the electrical devices can be
controlled. click here.
Here comes the Arduino code:
#include <ESP8266WiFi.h>

const char* ssid = "......."; // change the ssid and password


const char* password = ".....";// change your password dont forget

WiFiServer server(80);

void setup() {
Serial.begin(115200);
delay(10);
pinMode(5, OUTPUT); // D1 in nodemcu
pinMode(4, OUTPUT); // D2 in nodemcu
pinMode(0, OUTPUT); // D3 in nodemcu
pinMode(13, OUTPUT); // D7 in nodemcu
digitalWrite(5, LOW);
digitalWrite(4, LOW);

18
digitalWrite(0, LOW);
digitalWrite(13, LOW);

// Connect to WiFi network


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");

// Start the server


server.begin();
Serial.println("Server started");

// Print the IP address


Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");

void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

19
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Match the request
if (request.indexOf("/light1on") > 0) {
digitalWrite(5, HIGH);
}
if (request.indexOf("/light1off") >0) {
digitalWrite(5, LOW);
}
if (request.indexOf("/light2on") > 0) {
digitalWrite(4, HIGH);
}
if (request.indexOf("/light2off") >0) {
digitalWrite(4, LOW);
}
if (request.indexOf("/light3on") >0) {
digitalWrite(0, HIGH);
}
if (request.indexOf("/light3off") > 0) {
digitalWrite(0, LOW);
}
if (request.indexOf("/light4on") > 0) {
digitalWrite(13, HIGH);
}
if (request.indexOf("/light4off") > 0) {
digitalWrite(13, LOW);
}
// Set ledPin according to the request
//digitalWrite(ledPin, value);

20
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head>");
client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
client.println("</head>");
client.println("<body bgcolor = \"#f7e6ec\">");
client.println("<hr/><hr>");
client.println("<h4><center> Esp8266 Electrical Device Control </center></h4>");
client.println("<hr/><hr>");
client.println("<br><br>");
client.println("<br><br>");
client.println("<center>");
client.println("Device 1");
client.println("<a href=\"/light1on\"\"><button>Turn On </button></a>");
client.println("<a href=\"/light1off\"\"><button>Turn Off </button></a><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Device 2");
client.println("<a href=\"/light2on\"\"><button>Turn On </button></a>");
client.println("<a href=\"/light2off\"\"><button>Turn Off </button></a><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Device 3");
client.println("<a href=\"/light3on\"\"><button>Turn On </button></a>");
client.println("<a href=\"/light3off\"\"><button>Turn Off </button></a><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Device 4");

21
client.println("<a href=\"/light4on\"\"><button>Turn On </button></a>");
client.println("<a href=\"/light4off\"\"><button>Turn Off </button></a><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("<table border=\"5\">");
client.println("<tr>");
if (digitalRead(5))// read digital pin 5
{
client.print("<td>Light 1 is ON</td>");
}
else
{
client.print("<td>Light 1 is OFF</td>");
}
client.println("<br />");

if (digitalRead(4))// read digital pin 4


{
client.print("<td>Light 2 is ON</td>");
}
else
{
client.print("<td>Light 2 is OFF</td>");
}
client.println("</tr>");
client.println("<tr>");
if (digitalRead(0))// read digital pin 0
{
client.print("<td>Light 3 is ON</td>");
}
else
{
client.print("<td>Light 3 is OFF</td>");
}
if (digitalRead(13))// read digital pin 13

22
{
client.print("<td>Light 4 is ON</td>");
}
else
{
client.print("<td>Light 4 is OFF</td>");
}
client.println("</tr>");
client.println("</table>");
client.println("</center>");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
// code ends here

Copy the above code to Arduino IDE and upload to the ESP8266 device, make sure
to change the SSID and Password, you might be thinking that this code may be too
complicated but the reality is just same as the previous LED control program,
whereas in this program I have added many additional html tags to make the output
to looks good in the browser window. When you turn On or Off a device from a
web browser the status of that particular device will displayed in the web browser
for this tutorial.
I have used D1, D2, D3, and D7 pin in Nodemcu , follow the pin map correctly to
make it work. This program has developed to control 4 devices by following the
code it's easy to add more devices for controlling.
Note: If you want to control your device from any part of the world, it's very simple
you are just few steps behind to make it possible.
This tutorial has not created for that purpose but it is possible to make it happen by
just using the above program, all you have to do is to port forward the IP address
that your ESP8266 has connected to your router.
If you are not sure about port forwarding, you can check with your router
manufacturer website, I am sure there will be plenty of details given by the product
manufacturer. There are plenty of routers available and which not allowing me to
write a tutorial for one particular device.
Just check about port forwarding and play with your devices.

23
It's very simple to use relay with your electrical devices, Make sure you taking
necessary precautions before continuing this tutorial. I suggest to buy a Relay
module, it will be look like the black plate with blue box, don't buy the relay alone
which is really hectic work for a starter to find which pin will go in which way,
you can also use this tutorial to automate your home. Connect all your electrical
devices and control it and have fun with it.

24
Display Temperature and Humidity data on (I2C) LCD
The Inter-integrated Circuit (I2C) Protocol developed by Philips and is a protocol
intended to allow multiple slave digital integrated circuits (chips) to
communicate with one or more master chips. Like the Serial Peripheral Interface
(SPI), it is a two-wire protocol where you can hook up multiple slaves to the same
communication lines in any order you want, since all the slaves are given an unique
ID to keep track of them, keeping track of the communication is the master job so no
more than one slave can communicate at a time. In the case of this example, we only
have two devices, the nodemcu which will be acting as a master and the LCD
acting as a slave, this protocol only intended for short distance communications
within a single device. Like Asynchronous Serial Interfaces (such as RS-232 or
UARTs), it only requires two signal wires to exchange information. The sensor we
used for this tutorial is DHT11 Temperature and Humidity sensor features a
temperature & humidity sensor complex with a calibrated digital output signal, by
using exclusive digital-signal-acquisition technique and temperature and humidity
sensing technology, it ensures high reliability and excellent long-term stability. This
sensor includes a resistive-type humidity measurement component and an NTC
temperature measurement component.

25
I used Seeedstudio I2C RGB LCD for this tutorial, which is very easy to use with
ESP8266 or Nodemcu which requires only two wires to connect with Nodemcu
unlike traditional LCD's which has many wires to connect with a micro-controller.
The Nodemcu which has inbuilt I2C feature, the pins D1(GPIO5) and D2(GPIO4)
act as a I2C pins, pin D1 is the SCL pin and D2 is the SDA pin and the other two
wires are power supply and ground. Connect the 2nd pin of DHT11 sensor to the
D3 pin of Nodemcu. In order to make this example work you need two libraries to
be downloaded one is for RGB LCD and other one for the DHT11 sensor. The
DHT11 sensor library can be downloaded from Arduino IDE, go to sketch in the
arduino ide and select the => include library from sketch => after that select
Manage Libraries..

26
Type DHT11 in the filter your search box, and select the DHT11 library to be
installed on your system.

after completing the installation for the DHT11 sensor you need to download
library for the RGB LCD , most of the coding involved in the tutorial will suit to
all the I2C LCD's, make sure you are downloading correct library from your
manufacturer. Go to the link give here, to download the library for LCD, download
it as zip file

Extract the zip file from your system and copy and paste in the Arduino library
directory, you can follow it from the screen shown below, if you installed your
Arduino in C directory got to C > Program Files(x86) > Arduino > libraries.

27
You can also find a video of this project execution in this link, you can check
yourself on how this work and what are things need to be done to make this project
work in real-time for you.
Here comes the program:
#include "DHT.h"
#include <Wire.h>
#include "rgb_lcd.h" // make sure you downloaded the library for I2C lcd, I used //seeed grove lcd , and I
downloaded the files from seeedstudio.com
rgb_lcd lcd;
const int colorR = 255; // choose the color of RGB backlight If you choose colorG //to 255 then you will green
color light.
const int colorG = 0;
const int colorB = 0;
#define DHTPIN 2 // what digital pin we're connected to

#define DHTTYPE DHT11 // DHT 11


DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
lcd.begin(16,2);
lcd.setRGB(colorR, colorG, colorB);
lcd.print("Temp ");

28
lcd.print("humidity"); // these two line wil be printed on the first row of lcd
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
lcd.setCursor(0,1);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
float f;
lcd.print(t);
lcd.print((char)223);
lcd.print(" "); // space between two values
lcd.print(h);
lcd.print("%");
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");

29
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F"); // you can also open the serial monitor if the esp8266 //connected to your PC or laptop to
check the values of temperature humidity and //fahrenheit.
// program ends here
}

Copy and paste the above program into your Arduino IDE, and upload it to your
ESP8266 connected to your PC. If you missed any of the library to install it to your
arduino, this program will not work.

30
31
Analog Temperature sensor with Nodemcu
The ESP8266 v7 and v12 include an ADC (analog to digital converter)
pin. This means that the ESP8266 module can process inputs from analog sensors.
Light sensors, analog temperature sensors, force sensor, sound sensors etc,. can be
interfaced with ESP8266 but the disadvantage is that it can support only one ADC
which means only one analog pin is available in ESP8266 v12 and Nodemcu. The
ADC pin is having 10 bit resolution, which can read 0 to 1024, you will get a value
somewhere within this range. The ADC pin only reads upto 1V only. Any reading
over that, say 1.1V to Vcc of 3.3V will be maxed out to 1024.
The Nodemcu has inbuilt voltage divider that has connected to A0 pin, which
means any pin connected to this will be corrected automatically we don't need to
provide any voltage divider or any other resistor but if you are using any other
ESP8266 make sure which has inbuilt voltage divider or you need to make an
voltage divider to make this example to work with your ESP8266.

For R1, I used a 220R and for R2, I used 100R resistors. On my voltmeter the
actual resistance was 225 and 103.7 respectfully. The math indicates that 220R and
100R should divide 3.3v to 1.03v. 225R and 103.7 should be ~1.04v. All very
close. On the breadboard, my voltmeter is reading .98v. This relationship should
hold true for 22R and 10R as well as 20K and 10K. However, caution! The small
ones heat up.
For this tutorial I used LM35 temperature sensor, which is an analog sensor and it
is very cheap compare to the other analog sensor, this is also gives precise
temperature if we calibrate it correctly. This sensor is very easy to use with
ESP8266, which has only 3 wires, the first wire is Vcc, middle wire is Output
which should be connected to the A0 pin of Nodemcu and the third pin is the
ground.

32
The demonstration of this tutorial working and what are the necessary things to
make this tutorial work can be find in the video link here.
Here the code for LM35 sensor
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); // which allows serial communicaiton to begin
}
void loop() {
// put your main code here, to run repeatedly:
int analog = analogRead(17); // pin 17 is the analog pin esp8266
temp = analog*0.322265625; // the reason for this calculation is given in //datasheet of lm35
Serial.println(temp);// open your serial monitor to check it.
}
// code ends here

copy and paste the code into Arduino IDE and upload it to ESP8266 once the code
uploaded successfully to your ESP8266 you can check the serial monitor in the
Arduino IDE to know current temperature of the place the sensor is placed
currently. This is the code to check with analog sensor with ESP8266 or Nodemcu.
Now we will connect the Nodemcu to the WiFi and create a webserver, by creating
a webserver we can see the temperature by opening a browser instead of the serial
monitor.

Here comes the code:


#include <ESP8266WiFi.h>
const char* ssid = "......";
const char* password = ".......";
float temp =0;

33
int analog = 0;
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);

// Connect to WiFi network


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");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");

34
while(!client.available()){
delay(1);
}

// Read the first line of the request


String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

// Return the response


client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<meta http-equiv=\"refresh\" content=\"10\">");
client.print("LM35 Temp Sensor ");
client.println("<br><br>");
client.println("temperature :");
analog = analogRead(17);
temp = analog*0.322265625;
client.print(temp);
client.println("<br><br>");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");

}
// code ends here

Copy the and paste the above code in your Arduino IDE and upload the code to the
ESP8266 device, open the serial monitor you will return with an IP address your
ESP8266 has connected, copy the IP address and paste it into your browser and
check the temperature from the browser. This code can used to note the temperature
from any part of the world by Port forwarding your ESP8266.

35
36
Sensors Data To Thingspeak
ThingSpeak is an open source Internet of Things application and API to
store and retrieve data from things using HTTP over the Internet or via a Local
Area Network. With ThingSpeak, you can create sensor logging applications,
location tracking applications, and a social network of things with status updates. In
this tutorial you are going to learn about how temperature data can be uploaded to
thingspeak.com using Nodemcu.

We going to use only two components for this tutorial one is Nodemcu and other
one is DHT11 temperature and humidity sensor, in the very beginning we have seen
how to download library for this sensor if you skipped that tutorial you can check
back to know how to install the library for this sensor.
One more thing you need to do for this tutorial is to register to thingspeak.com to
get your api key, the api key must to upload your data to thingspeak.com
You can also check this video tutorial on how to upload your sensor data's to
thingspeak and how to register in this website are explained in this video link.
Steps to be followed to upload data to thingspeak.
1. Go to https://thingspeak.com/
2. Log in with your ID and Password.

37
3. Click the Create New channel Icon

4. Give Name to your new channel and edit the description for your channel and
create the Names for your field, fields are going to hold the sensor data's, if your
uploading temperature data give the name as temperature to the field and choose
how many field you require for your project.

5. After completing the above steps save your channel.


6. Go to API keys and copy the Write API key.

7. Paste your API key to the Arduino program.

Here comes the Code:


#include <DHT.h>

38
#include <ESP8266WiFi.h>

// replace with your channel's thingspeak API key,


String apiKey = "..............";
const char* ssid = "......."; // your Wifi Name
const char* password = "........."; // Your Wifi Password

const char* server = "api.thingspeak.com";


#define DHTPIN 13 // D7 pin in nodemcu

DHT dht(DHTPIN, DHT11);


WiFiClient client;

void setup() {
Serial.begin(115200);
delay(10);
dht.begin();

WiFi.begin(ssid, password);

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");

39
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
float t = dht.readTemperature(); // Read temperature as Celsius (the default)
if (isnan(h) || isnan(t)) { // Check if any reads failed and exit early (to try again).
Serial.println("Failed to read from DHT sensor!");
return;
}

if (client.connect(server,80)) { // "184.106.153.149" or api.thingspeak.com


String postStr = apiKey;
postStr +="&field1=";
postStr += String(t);
postStr +="&field2=";
postStr += String(h);
postStr += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");


client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);

Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius Humidity: ");
Serial.print(h);
Serial.println("% send to Thingspeak");
}
client.stop();

40
Serial.println("Waiting...");
// thingspeak needs minimum 15 sec delay between updates
delay(20000);
}
// code ends here

Copy and paste code to Arduino IDE and upload it to ESP8266. After uploading the
code to your ESP8266 go to thingspeak.com and click the channels you can see
your temperature and humidity data on the thingspeak website.

The same process can be done with LM35 temperature sensor; lets upload the
temperature data of LM35 to Thingspeak.com

Here comes the code:


#include <ESP8266WiFi.h>

// replace with your channel's thingspeak API key,


String apiKey = "......."; // paste your api key from Thingspeak
const char* ssid = "......."; // change to your SSID
const char* password = "....."; // change to your Password

const char* server = "api.thingspeak.com"; // Thingspeakserver


float temp = 0; // variable for saving temperature data

41
int analog = 0; // variable to hold analog data
WiFiClient client;

void setup() {
Serial.begin(115200); // intialized serial communication to check data in serial monitor.
delay(10);

WiFi.begin(ssid, password);

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");

void loop() {
analog = analogRead(17);
float temp = analog * 0.322265625;

if (client.connect(server,80)) { // "184.106.153.149" or api.thingspeak.com


String postStr = apiKey;
postStr +="&field1=";
postStr += String(temp);
postStr += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");

42
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);

Serial.print("Temperature: ");
Serial.print(temp);
Serial.println("% send to Thingspeak");
}
client.stop();

Serial.println("Waiting...");
// thingspeak needs minimum 15 sec delay between updates
delay(20000);
}

Copy and paste the above code to Arduino IDE and upload it to the ESP8266
development kit or a generic board. If you struck in any line of this tutorial you can
also find the video tutorial of this project in the link here.

43
SD card with ESP8266
The communication between the ESP8266 and the SD card uses Serial
Peripheral Interface (SPI), it is a synchronous serial data protocol used by
microcontrollers for communicating with one or more peripheral devices quickly
over short distances. It can also be used for communication between two ESP8266.
With an SPI connection there is always one master device (usually a
microcontroller) which controls the peripheral devices. Typically there are three
lines common to all the devices as follows:
MISO (Master In Slave Out) - The slave line for sending data to the master.
MOSI (Master Out Slave In) - The Master line for sending data to the peripherals.
SCK (Serial Clock) - The clock pulses which synchronize data transmission
generated by the master
SS (Slave Select) - the pin on each device that the master can use to enable and
disable specific devices.
When a device's Slave Select pin is low, it communicates with the master. When
it's high it ignores the master. This allows you to have multiple SPI devices sharing
the same MISO, MOSI, and CLK lines.
Preparing the SD card to use with ESP8266
Most of the SD cards are supported by ESP8266 the Arduino library
supports SD card to have the format type FAT16 or FAT32, make sure you format
your SD card before using it with ESP8266.

44
You need a SD card Module with a SD card and a DHT Temperature and Humidity
sensor with Nodemcu to make this example work.
Connect the SD card module as follows to the Nodemcu.
D5 (GPIO 14 in generic boards) pin of Nodemcu to SCK (GPIO 14 in generic
boards)
D6 (GPIO 12 in generic boards) pin of Nodemcu to MISO
D7 (GPIO 13 in generic boards) pin of Nodemcu to MOSI
D8 (GPIO 15 in generic boards) pin of Nodemcu to CS
Vcc to 3.3v
Gnd to Gnd
This example will store the temperature and humidity data on SD card connected to
the Nodemcu, the temperature data's can be later on used for inspection by
connecting the SD card to the card reader. If you find difficulty in following this
tutorial you can also check the video tutorial here.
Here comes the code:
#include <SPI.h>
#include <SD.h>
#include "DHT.h"
#define DHTPIN 2
File Dhtemp;
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
dht.begin();
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only

45
}
Serial.print("Initializing SD card...");
if (!SD.begin(15)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
}
void loop()
{
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

Dhtemp = SD.open("Temp.txt", FILE_WRITE);

// if the file opened okay, write to it:


if (Dhtemp) {
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("%\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println("*C");
Serial.print("Writing to test.txt...");

46
Dhtemp.print("Humidity: ");
Dhtemp.print(h);
Dhtemp.print("%\t");
Dhtemp.print("Temperature: ");
Dhtemp.print(t);
Dhtemp.println("*C");
// close the file:
Dhtemp.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening Temp.txt");
}
}
// code ends here

This code is really simple to follow as it uses the predefined arduino library to
write the data's of temperature and humidity to the SD card. It's just like writing the
data to the serial monitor, copy and paste the above code into Arduino IDE and
upload the code to the Nodemcu, if you are not getting the data or the file is not
saved properly in your SD card you can check the SD card whether you inserted it
correctly or not, if the problem persists format the SD card and check it again.

47
SD card Webserver
Have you ever thought of hosting your website? If yes then this tutorial
will help you to make your website hosted by you without buying space from a third
party vendors, you cannot expect to make a complete high end website but you can
serve a simple website using ESP8266 and a SD card, you can create and update a
website in real-time. Configure your home router to forward a port, if you not
configuring your router for port forward you access this website only in the devices
connected to your router.

Follow the circuit diagram to connect the SD card module to your ESP8266,
Connect the SD card module as follows to the Nodemcu.
D5 (GPIO 14 in generic boards) pin of Nodemcu to SCK (GPIO 14 in generic
boards)
D6 (GPIO 12 in generic boards) pin of Nodemcu to MISO
D7 (GPIO 13 in generic boards) pin of Nodemcu to MOSI
D8 (GPIO 15 in generic boards) pin of Nodemcu to CS
you need only two components one is the SD card module with a SD card and
Nodemcu to make this example to work for you, format the SD card to FAT16 or
FAT32 and upload the html files to your SD card, name your file as index.htm if you
are changing the file name that you copying to your SD card make sure you also

48
changing the file name in the program and note that your file name should not be
longer than 8 characters your file must be lesser than 8 character don't give a long
name for the file and the file extension should be longer than 3 characters, if you are
not following the above said conditions then it will not supported by the SD library.
Copy all your main files and subfolders that support your Website, you can also
check the video to know how to do this tutorial here.
once you copied the files into your SD card, now it's time to upload the program to
executes the files in the SD card, this file is already available in the example folder
comes with the ESP8266 library. Open the SDWebServer file and upload the code
to ESP8266 and check the IP address, your website is up and running.

49
50
Scan the Wi-Fi network surrounded you
In this project we will make a Wi-Fi network scanner and display the Wi-
Fi network surround by us in the TFT LCD Screen. This project is pretty simple if
you find the exact library for the TFT screen that will work with your ESP8266,
most of the library out there for display devices which uses SPI protocol are for
Arduino, you need to find a right one to make it work with ESP8266, click the link
here to download the appropriate library to work with this LCD. The library is the
modified version of Adafruit Library download and extracts the files to Arduino
Library.

Components you need to make this project are a Nodemcu and a TFT LCD screen
this is a cheap Chinese make which is available for under $5 online, this one is a
2.2 inch colour screen which is easy to control using ESP8266. Connect the LCD to
the ESP8266 as per the circuit diagram.
Here comes the program:
#include "ESP8266WiFi.h"
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#define TFT_DC 2
#define TFT_CS 5
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

51
void setup() {
tft.begin();
tft.setRotation(1);
tft.fillScreen(ILI9341_WHITE);

tft.setTextColor(ILI9341_BLACK, ILI9341_WHITE);

tft.setTextSize(2);
tft.setCursor(20, 46);

delay(2500); tft.fillScreen(ILI9341_WHITE);
Serial.begin(115200);

// Set WiFi to station mode and disconnect from an AP if it was previously connected
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
}
void loop() {
tft.setTextSize(2);
tft.setCursor(0, 0);
tft.println("scan start");
// WiFi.scanNetworks will return the number of networks found
int n = WiFi.scanNetworks();
tft.println("scan done");
if (n == 0){
tft.println(" no networks found");
}
else
{
tft.println("networks found");
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
tft.print(i +1);
tft.print( " : ");

52
tft.print(WiFi.SSID(i));
tft.print(" (");
tft.print(WiFi.RSSI(i));
tft.print(")");
tft.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
delay(10);
}
}
tft.println("");

// Wait a bit before scanning again


delay(5000);
}

Upload the code to ESP8266 and wait for the results on your TFT LCD screen, if
you having problem in following this tutorial you can follow the video tutorial here,
if you facing any trouble in compiling the code, make sure you also installed the
Adafruit GFx library, the library can be downloaded from manage libraries, go to
sketch and click include library and click the manage libraries and type for Adafruit
GFx library and install it.

53
Real-time clock Using ESP8266
In this project, you will use your ESP8266 to connect to query a Network
Time Protocol (NTP) server. This way, ESP8266 can get time from the Internet.

This project follows exactly as the same circuit connection to the TFT LCD to
Nodemcu, but the process is different where, the ESP8266 will synchronize the
time with NTP server and start to count the clock from there, until there is a change
in time this will not connect to the server to update the time.

54
Connect the circuit as shown in the above fritzing diagram. This is same connection
compare to the previous project, if you completed the previous project the same
circuit can be used to complete this project. In the previous project we have
downloaded two libraries for the LCD to work with ESP8266, one more library is
needed for this project, and this library will used to count the time once ESP8266
synchronized to NTP server. You can download the library from here, download the
library and extract the contents from the library copy and paste it to the Arduino
library, if you finding difficulty in following this tutorial you can watch the video
here.
Here comes the Code:
/*
* Time_NTP.pde

* Example showing time sync to NTP time source


*

* This sketch uses the ESP8266WiFi library


*/

#include <TimeLib.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#include "SPI.h"
#include "Adafruit_GFX.h"

#include "Adafruit_ILI9341.h"
#define TFT_DC 2

#define TFT_CS 5
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

const char ssid[] = "....."; // your network SSID (name)


const char pass[] = "....."; // your network password

// NTP Servers:

IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov


// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov

// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov

const int timeZone = 5.30; // India Time zone.


//const int timeZone = -5; // Eastern Standard Time (USA)

//const int timeZone = -4; // Eastern Daylight Time (USA)


//const int timeZone = -8; // Pacific Standard Time (USA)

//const int timeZone = -7; // Pacific Daylight Time (USA)

55
WiFiUDP Udp;

unsigned int localPort = 8888; // local port to listen for UDP packets

void setup()
{

tft.begin();
tft.setRotation(1);

tft.fillScreen(ILI9341_WHITE);
tft.setTextColor(ILI9341_BLACK, ILI9341_WHITE);
tft.setTextSize(2);
tft.setCursor(20,46);
tft.println("India Time Zone");

delay(2500);
tft.fillScreen(ILI9341_WHITE);

Serial.begin(9600);
while (!Serial) ; // Needed for Leonardo only
delay(250);

Serial.println("TimeNTP Example");
Serial.print("Connecting to ");

Serial.println(ssid);
WiFi.begin(ssid, pass);

while (WiFi.status() != WL_CONNECTED) {

delay(500);
Serial.print(".");
}

Serial.print("IP number assigned by DHCP is ");


Serial.println(WiFi.localIP());

Serial.println("Starting UDP");
Udp.begin(localPort);
Serial.print("Local port: ");

Serial.println(Udp.localPort());
Serial.println("waiting for sync");

setSyncProvider(getNtpTime);
}

time_t prevDisplay = 0; // when the digital clock was displayed

void loop()

56
{
if (timeStatus() != timeNotSet) {

if (now() != prevDisplay) { //update the display only if time has changed


prevDisplay = now();

digitalClockDisplay();
}

}
}

void digitalClockDisplay(){
// digital clock display of the time
Serial.print(hour());
printDigits(minute());

printDigits(second());

tft.setTextSize(2);
tft.setCursor(20, 158);
tft.print ("Time ");

if(hour() <10){
tft.print("0");}

if(hour() > 12){


tft.print("0");

tft.print(hour()-12);}
else{tft.print(hour());}

tft.print(":");

if(minute()<10){

tft.print("0");}
tft.print(minute() );

tft.print(":");

if(second() < 10){


tft.print("0");}
tft.print(second());

if(hour()>12){

tft.print(" PM ");}

else {tft.print(" AM ");}


tft.setTextSize(2);

tft.setCursor(20,198);
tft.print("M onth ");

57
if (month() < 10){
tft.print("0"); }

tft.print(month());
tft.print("/");

if (day() < 10){


tft.print("0"); }

tft.print(day());
tft.print("/");

tft.print(year());
Serial.print(" ");
Serial.print(day());
Serial.print(".");
Serial.print(month());

Serial.print(".");
Serial.print(year());

Serial.println();
}
void printDigits(int digits){

// utility for digital clock display: prints preceding colon and leading 0
Serial.print(":");

if(digits < 10)


Serial.print('0');

Serial.print(digits);
}

/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message

byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{

while (Udp.parsePacket() > 0) ; // discard any previously received packets


Serial.println("Transmit NTP Request");
sendNTPpacket(timeServer);

uint32_t beginWait = millis();


while (millis() - beginWait < 1500) {

int size = Udp.parsePacket();


if (size >= NTP_PACKET_SIZE) {

Serial.println("Receive NTP Response");


Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer

unsigned long secsSince1900;


// convert four bytes starting at location 40 to a long integer

58
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;

secsSince1900 |= (unsigned long)packetBuffer[42] << 8;


secsSince1900 |= (unsigned long)packetBuffer[43];

return secsSince1900 - 2208988800UL + timeZone * 3600;


}

}
Serial.println("No NTP Response :-(");

tft.println("No NTP Response :-(");


return 0; // return 0 if unable to get the time
}
// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)

{
// set all bytes in the buffer to 0

memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)

packetBuffer[0] = 0b11100011; // LI, Version, M ode


packetBuffer[1] = 0; // Stratum, or type of clock

packetBuffer[2] = 6; // Polling Interval


packetBuffer[3] = 0xEC; // Peer Clock Precision

// 8 bytes of zero for Root Delay & Root Dispersion


packetBuffer[12] = 49;

packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;

// all NTP fields have been given values, now


// you can send a packet requesting a timestamp:

Udp.beginPacket(address, 123); //NTP requests are to port 123


Udp.write(packetBuffer, NTP_PACKET_SIZE);

Udp.endPacket();
}

Make sure to change the Time Zone for this project to work on your Time zone and
also don't forget to change the SSID to your Wi-Fi name and password. Copy and
paste the code to your Arduino IDE and upload it to ESP8266, make sure you
downloaded all the required libraries to make this project work for you.

59
Create a weather widget using Nodemcu
In this project you going to create a home based weather widget using
Nodemcu and BMP180 (barometric pressure sensor) display the sensor values to
TFT LCD. To make this project to work you need a BMP library that can be
downloaded from the manage library in the Arduino IDE.

BMP180 sensor is a I2C type which uses only two wires as we see this in the early
tutorial for I2C LCD. Connecting the TFT LCD and BMP180 sensor to ESP8266
has shown in the above fritzing circuit.

You can also watch the demonstration video of this project by the following the link

60
here, make sure you have downloaded the barometric and pressure sensor library
before uploading this code to your Nodemcu.
Here comes the code.
#include <TimeLib.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Wire.h>
#include <Adafruit_BMP085.h>
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#define TFT_DC 2
#define TFT_CS 12
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
const char ssid[] = "............"; // your network SSID (name)
const char pass[] = "..........."; // your network password
// NTP Servers:
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov
// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov

const int timeZone = 5.30; // India Time zone.


//const int timeZone = -5; // Eastern Standard Time (USA)
//const int timeZone = -4; // Eastern Daylight Time (USA)
//const int timeZone = -8; // Pacific Standard Time (USA)
//const int timeZone = -7; // Pacific Daylight Time (USA)

Adafruit_BMP085 bmp;
WiFiUDP Udp;

61
unsigned int localPort = 8888; // local port to listen for UDP packets
void setup()
{
tft.begin();
tft.setRotation(1);
tft.fillScreen(ILI9341_WHITE);
tft.setTextColor(ILI9341_BLACK, ILI9341_WHITE);
tft.setTextSize(2);
tft.setCursor(20,46);
tft.println("Weather Widget");
delay(2500);
tft.fillScreen(ILI9341_WHITE);
Serial.begin(9600);
while (!Serial) ; // Needed for Leonardo only
delay(250);
Serial.println("TimeNTP Example");
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
if (!bmp.begin()) {
tft.println("Could not find a valid BMP085 sensor, check wiring!");
}

while (WiFi.status() != WL_CONNECTED) {


delay(500);
Serial.print(".");
}
Serial.print("IP number assigned by DHCP is ");
Serial.println(WiFi.localIP());

62
Serial.println("Starting UDP");
Udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(Udp.localPort());
Serial.println("waiting for sync");
setSyncProvider(getNtpTime);
}
time_t prevDisplay = 0; // when the digital clock was displayed
void loop()
{
if (timeStatus() != timeNotSet) {
if (now() != prevDisplay) { //update the display only if time has changed
prevDisplay = now();
digitalClockDisplay();
weatherdata();
}
}
}
void weatherdata(){
tft.setTextSize(2);
tft.setCursor(20,10);
tft.print("Temperature = ");
tft.print(bmp.readTemperature());
tft.println(" *C");
tft.setTextSize(2);
tft.setCursor(20, 60);
tft.print("Pressure = ");
tft.print(bmp.readPressure());
tft.println(" Pa");

63
tft.setTextSize(1);
tft.setCursor(20,110);
tft.print("Altitude = ");
tft.print(bmp.readAltitude());
tft.print("m ");
tft.print("Real altitude =");
tft.print(bmp.readAltitude(101500));
tft.println("m");
tft.setTextSize(1);
tft.setCursor(20,140);
tft.print("Pressure at sealevel(calculated) = ");
tft.print(bmp.readSealevelPressure());
tft.println("Pa");
delay(500);
}
void digitalClockDisplay(){
// digital clock display of the time
Serial.print(hour());
printDigits(minute());
printDigits(second());
tft.setTextSize(2);
tft.setCursor(20, 158);
tft.print ("Time ");
if(hour() <10){
tft.print("0");}
if(hour() > 12){
tft.print("0");
tft.print(hour()-12);}
else{tft.print(hour());}

64
tft.print(":");

if(minute()<10){
tft.print("0");}
tft.print(minute() );
tft.print(":");
if(second() < 10){
tft.print("0");}
tft.print(second());
if(hour()>12){
tft.print(" PM");}
else {tft.print(" AM");}
tft.setTextSize(2);
tft.setCursor(20,198);
tft.print("Month ");
if (month() < 10){
tft.print("0"); }
tft.print(month());
tft.print("/");
if (day() < 10){
tft.print("0"); }
tft.print(day());
tft.print("/");
tft.print(year());
Serial.print(" ");
Serial.print(day());
Serial.print(".");
Serial.print(month());
Serial.print(".");

65
Serial.print(year());
Serial.println();
}

void printDigits(int digits){


// utility for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}

/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing
packets

time_t getNtpTime()
{
while (Udp.parsePacket() > 0) ; // discard any previously received packets
Serial.println("Transmit NTP Request");
sendNTPpacket(timeServer);
uint32_t beginWait = millis();
while (millis() - beginWait < 1500) {
int size = Udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
Serial.println("Receive NTP Response");
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
unsigned long secsSince1900;

66
// convert four bytes starting at location 40 to a long integer
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
secsSince1900 |= (unsigned long)packetBuffer[43];
return secsSince1900 - 2208988800UL + timeZone * 3600;
}
}
Serial.println("No NTP Response :-(");
tft.println("No NTP Response :-(");
return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address


void sendNTPpacket(IPAddress &address)
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;

67
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer, NTP_PACKET_SIZE);
Udp.endPacket();
}
This code combines the previous project in addition to the previous project
barometric and pressure sensor code is added and all the details from the sensors
are displayed to the TFT screen.

68
Components Need for this book
Esp8266 development kit or Nodemcu or any other development kit using
Esp8266
LED
RELAY
BMP180 (I2C) sensor
LM35 Temperature sensor
DHT11 Temperature and humidity sensor
TFT LCD Screen
I2C 16x2 LCD
SD card Module.

69
70
Port Forwarding Example
For this example I am using TP-Link router, I use this modem for my Wi-
Fi, if you are using different router you can check it out to know how to port
forward with your router, if you are using the same router then you can follow this
tutorial.
Step 1: Log into the router's web management page: This can be done by typing
192.168.0.1 in your browser and type admin and admin for user name and
password.
Step 2: Click forwarding > Virtual servers on the left side and then click add new
button

Step 3: after clicking the Add new button, Add or Modify a virtual Server Entry
page will be opened, in this you have to enter the details of Service port, Internal
Port, IP address
Service port is the Server port number you have entered in the Arduino program,
usually this will be 80 by default,

leave the internal port as black and type the IP address as the ESP8266 connected
with your router this is the IP address each time when a ESP8266 connected to your
router leave a local IP which can be find from the serial monitor.

71
Click the Save button to save the setting you have done previously
Step 5: Go to Status Page and check the WAN IP Address of the router. Copy the
WAN IP and port number to access the service from outside the network. Now you
can access your ESP8266 from any part of the world, you can control your Home
lights from anywhere by calling the IP address in your web browser or mobile
browser.

For the above example I used port number 80 which is the default number for my
router management, which should be changed to use the port number 80 by the
ESP8266 this can be done by clicking the Security tab on the left side of the router
management page.

If the WAN IP Address of the router is not a public IP Address, but a Private IP
Address, that means there is another NAT device connected to the WAN Port of the
TP-LINK router, you need open the service ports on that device as well.

72
Contact and Source Codes:
For suggestions and queries you can always mail me at
jayakumarmagesh@gmail.com
All the code and necessary documents for this book can be find here.

73

S-ar putea să vă placă și