Você está na página 1de 297

ABOUT US

BYTESTEM.ORG is a Non-Governmental Organization, created by three


like-minded people who are committed to making a difference in the lives
of underprivileged children particularly girls by empowering them through
STEM education. STEM is an acronym for Science, Technology,
Engineering and Math education. We believe that our STEM courses will
help in the all-round education of our students through inter-disciplinary and
hands on learning. We do our best to promote STEM education in as many
schools as possible. We plan to eventually take it to colleges in the near
future.

We focus on these areas together because the skills and knowledge in each
discipline are essential for a student to be successful in a science based
career. Further, these fields of study are deeply intertwined in the real world.
We create an interactive learning experience through workshops and
activities. We tap into the talents of students, encourage students to think
out of the box and be independent. We believe in the saying “You educate
a man; you educate a man. You educate a woman; you educate a
generation.” In keeping with this, we facilitate empowering girls/women
through motivational programs in addition to STEM courses.

Worldwide, STEM supports the study of engineering and technology even


at elementary school level. We at BYTESTEM.org strive to impact the lives
of students from the middle school level. We provide quality education free
of cost and all expenses are borne by us.

Started in late 2014 to offer excellent STEM education to students, we not


only educate students but we keenly look to increase the active participation
of girls in STEM fields.

With the additional knowledge and hands on application that we encourage,


we hope that it would widen the aspirations of students and prompt them to
enter STEM fields later. We at bytestem.org strive to provide a path for
students to pursue their dreams in the field of science and technology. It is
our passionate desire to aid in designing an approach to science that is driven
by problem-solving, discovery, exploratory learning, and which requires
students to actively engage with a challenge in order to find its solution.

Thanks for purchasing this book, your money will be spent on


educating students not for any personal use.

 
 Copyright 20146 by bytestem.org - All rights reserved.

This document is geared towards providing exact and reliable information in regards
to the topic and issue covered. The publication is sold with the idea that the publisher
is not required to render accounting, officially permitted, or otherwise, qualified
services. If advice is necessary, legal or professional, a practiced individual in the
profession should be ordered.

- From a Declaration of Principles which was accepted and approved equally by a


Committee of the American Bar Association and a Committee of Publishers and
Associations.

In no way is it legal to reproduce, duplicate, or transmit any part of this document in


either electronic means or in printed format. Recording of this publication is strictly
prohibited and any storage of this document is not allowed unless with written
permission from the publisher. All rights reserved.

The information provided herein is stated to be truthful and consistent, in that any
liability, in terms of inattention or otherwise, by any usage or abuse of any policies,
processes, or directions contained within is the solitary and utter responsibility of the
recipient reader. Under no circumstances will any legal responsibility or blame be held
against the publisher for any reparation, damages, or monetary loss due to the
information herein, either directly or indirectly.

Respective authors own all copyrights not held by the publisher.

The information herein is offered for informational purposes solely, and is universal as
so. The presentation of the information is without contract or any type of guarantee
assurance.

The trademarks that are used are without any consent, and the publication of the
trademark is without permission or backing by the trademark owner. All trademarks
and brands within this book are for clarifying purposes only and are the owned by the
owners themselves, not affiliated with this document.
Contents
BASICS OF ELECTRONICS ............................................................................................... 8
LED ........................................................................................................................................ 8
Resistors ................................................................................................................................. 8
Capacitors .............................................................................................................................. 9
Transistor ............................................................................................................................. 10
Diode .................................................................................................................................... 10
Variable Resistor .................................................................................................................. 11
Light Dependent Resistor .................................................................................................... 11
DC Motor ............................................................................................................................. 11
Push Button .......................................................................................................................... 12
Temperature Sensor ............................................................................................................. 12
DHT11 Digital Temperature and Humidity Sensor ............................................................. 12
Piezo Buzzer ........................................................................................................................ 12
Servo Motor ......................................................................................................................... 13
16x2 LCD display ................................................................................................................ 13
Sound Sensor ....................................................................................................................... 13
Connecting wires ................................................................................................................. 13
Breadboard ........................................................................................................................... 14
HARDWARE ARCHITECTURE ........................................................................................... 15
Internet of Things (IoT) ........................................................................................................... 18
SOFTWARE INSTALLATION .............................................................................................. 21
HARDWARE SETUP ............................................................................................................. 26
TYPES OF ESP8266 ............................................................................................................... 27
ESP8266 Hardware .................................................................................................................. 33
GETTING STARTED ............................................................................................................. 36
Basic Programming in Arduino IDE........................................................................................ 44
Programming Multiple LEDs .................................................................................................. 60
Programming for a Push button and a LED ............................................................................. 62
Using a Potentiometer (analog sensor) with ESP8266 ............................................................ 64
PWM using Potentiometer and LED ....................................................................................... 66
Servo Motor with ESP8266 ..................................................................................................... 69
GETTING STARTED WITH IOT .......................................................................................... 72
ESP Wi-Fi Library for Arduino IDE ................................................................................... 72
Control an LED from Browser ................................................................................................ 81
Home Automation .................................................................................................................... 89
Arduino IDE program for ESP8266 Home Automation...................................................... 96
Display Temperature and Humidity data on (I2C) LCD ........................................................ 105
Analog Temperature sensor with Nodemcu .......................................................................... 116
Sensors Data To Thingspeak ................................................................................................. 123
SD card with ESP8266........................................................................................................... 133
SD card Webserver ................................................................................................................ 138
Scan the Wi-Fi network surrounded by you .......................................................................... 151
Real-time clock Using ESP8266............................................................................................ 156
Create a weather widget using Nodemcu............................................................................... 166
ESP8266 Internet of Things with Ubidots ............................................................................. 177
Control an LED from Ubidots. .............................................................................................. 190
Security alerts creating by events in Ubidots ......................................................................... 197
Intruder alert using PIR sensor .............................................................................................. 203
Over the Air (OTA) ............................................................................................................... 205
ESP8266 as Access Point Webserver .................................................................................... 209
MQTT .................................................................................................................................... 223
Getting Started with Lua..................................................................................................... 239
Flashing ESP8266 or Nodemcu with latest lua firmware................................................. 239
Getting Started With ESPlorer........................................................................................... 246
ESPlorer IDE overview...................................................................................................... 248
Nodemcu API for Lua ......................................................................................................... 250
GPIO API ........................................................................................................................... 250
gpio.mode() .................................................................................................................... 250
gpio.read(): ..................................................................................................................... 251
gpio.write()..................................................................................................................... 251
gpio.trig() ....................................................................................................................... 251
ADC API............................................................................................................................ 252
adc.read() : ..................................................................................................................... 253
Bit API ............................................................................................................................... 253
Node API ........................................................................................................................... 255
FILE API............................................................................................................................ 259
Wi-Fi API........................................................................................................................... 262
wifi.getchannel() ............................................................................................................ 263
wifi.setmode() ................................................................................................................ 263
wifi.getmode() ................................................................................................................ 263
wifi.setphymode() .......................................................................................................... 264
wifi.getphymode() .......................................................................................................... 264
wifi.sleeptype() .............................................................................................................. 265
wifi.sta.config() .............................................................................................................. 265
wifi.sta.connect()............................................................................................................ 266
Wifi.sta.disconnect() ...................................................................................................... 266
wifi.sta.getbroadcast() .................................................................................................... 266
wifi.sta.getconfig() ......................................................................................................... 266
wifi.sta.gethostname() .................................................................................................... 267
wifi.sta.getip() ................................................................................................................ 267
wifi.sta.getmac() ............................................................................................................ 268
Wifi.sta.sethostname() ................................................................................................... 268
wifi.sta.setip() ................................................................................................................ 268
wifi.sta.setmac() ............................................................................................................. 269
wifi.sta.status() ............................................................................................................... 269
wifi.ap.config() .............................................................................................................. 270
wifi.ap.getbroadcast() .................................................................................................... 270
wifi.ap.getclient() ........................................................................................................... 271
wifi.ap.getip() ................................................................................................................. 271
wifi.ap.getmac() ............................................................................................................. 271
wifi.ap.setip() ................................................................................................................. 272
wifi.ap.setmac().............................................................................................................. 272
wifi.ap.dhcip.config()..................................................................................................... 272
wifi.ap.dhcp.start() ......................................................................................................... 272
wifi.ap.dhcp.stop() ......................................................................................................... 272
Timer API .......................................................................................................................... 273
tmr.alarm() ..................................................................................................................... 273
tmr.delay() ...................................................................................................................... 274
tmr.interval() .................................................................................................................. 274
tmr.now() ....................................................................................................................... 274
tmr.time() ....................................................................................................................... 275
tmr.wdclr() ..................................................................................................................... 275
tmr.unregister() .............................................................................................................. 275
tmr.stop()........................................................................................................................ 275
tmr.register() .................................................................................................................. 277
tmr.softwd() ................................................................................................................... 277
tmr.state() ....................................................................................................................... 277
tmr.start() ....................................................................................................................... 278
PWM API........................................................................................................................... 278
pwm.setup() ................................................................................................................... 278
pwm.start() ..................................................................................................................... 278
pwm.stop() ..................................................................................................................... 278
pwm.setduty() ................................................................................................................ 279
NET API ............................................................................................................................ 279
Constants ........................................................................................................................ 279
net.createConnection() ................................................................................................... 279
net.createServer() ........................................................................................................... 279
net.server.close() ............................................................................................................ 280
net.server.listen()............................................................................................................ 280
net.socket.close()............................................................................................................ 280
net.socket.connect() ....................................................................................................... 281
Net.socket.dns() ............................................................................................................. 281
net.socket.on() ................................................................................................................ 281
net.socket.send() ............................................................................................................ 282
net.dns.resolve() ............................................................................................................. 282
net.dns.setdnsserver() ..................................................................................................... 282
HTTP API ......................................................................................................................... 283
http.delete() .................................................................................................................... 283
http.get() ......................................................................................................................... 284
http.post() ....................................................................................................................... 284
http.put()......................................................................................................................... 285
http.request() .................................................................................................................. 285
Turn On and OFF an LED ..................................................................................................... 286
Working with LED ................................................................................................................ 292
Blink an LED ..................................................................................................................... 292
BASICS OF ELECTRONICS
LED
An LED is acronym for Light Emitting
Diode, it is a type of diode that illuminates
when electricity passes through it. Their
voltage drop is higher than a normal diode,
from1.2v for an infrared LED, up to 3.5v
for blue and ultraviolet LED. These
LED’s comes in different size and
different colours. If you take closer look to
that LED picture, one lead (leg) of the LED’s shorter and another one is longer.
Shorter one is known as cathode (negative (-) symbol) and the longer one is
known as anode (positive (+) symbol). If the current passing through the LED is
too high, you will lose LED. A LED can withstand up to 3.5v, output voltage
from the Arduino pins are 5V to step down this voltage, a resistor in series with
LED should use to prevent the LED from hurt.

Resistors
Resist the flow of electrical current in
circuit, in other words they limit the flow
of electrons. The SI unit of resistance is
Ohms, written as the Greek letter omega
(Ω). They are often used with the unit
prefixes kilo (k) and mega (M). The value
of resistor indicated by 4 or 5 colour band
bands, using the resistor color code:
The first 2 bands are the first digits of the
value, and the 3rd band is the power of ten
that comes after those 2 digits. This is also
called the multiplier, and is just the number of zeros you have to add. The last
band is the tolerance and mostly it will be silver or gold color.
“BB ROY Great Britain Very Good Wife”, try to memorise this sentence which
allows you to remember 9 color bands in the resistor. First b represents black,
second b represents brown, R represents Red, O represents Orange, Y represents
yellow, first word in Great G represents Green, first word in Britain B represents
Blue, first word in Very V represents violet, first letter in G represents Grey and,
first letter in Wife W represents White.
Color 1st Band 2nd Band 3rd Band 4th Band
(1st digit) (2nd digit) (Multiplier) (tolerance)
Black 0 0 1Ω
Brown 1 1 10Ω ±1%
Red 2 2 100Ω ±2%
Orange 3 3 1000 or 1kΩ
Yellow 4 4 10kΩ
Green 5 5 100kΩ ±0.5%
Blue 6 6 1MΩ ±0.25%
Violet 7 7 10MΩ ±0.1%
Grey 8 8 ±0.05%
White 9 9
Gold 0.1Ω ±5%
Silver 0.01Ω ±10%

Eg: The first resistor toward right, in the above picture shows Brown RED RED
color, First band is Brown look up the table to find 1st digital value for this color,
value for the brown color in the first digit is ‘1’, second color is Red, if you look
up the table for the 2nd digit value color for the Red is 2 and the third color is also
red, if you look up the table for 3rd Band it is multiplier and the value is 100 ohms
If we join all the value together, 1 2 * 100
And the final value will be 1200, the resistance value is 1200 Ω.

Capacitors
These components store and release
electrical energy in a circuit. It behaves like
a small rechargeable battery. Capacitors are
used in filters. The SI unit of capacitance is
farad, of F. This is a very large unit and most
often, you will see prefixes like pico(p),
nano (n) or micro (µ). Often placed across power and ground close to a sensor or
motor to help fluctuation in voltage.
Transistor
A transistor is a semiconductor device,
which is used to switch or amplify a signal.
You can think of it as a switch that can be
operated by using a very weak signal, a
current controlled switch.
A transistor has three terminals: they are
called the base (B), the emitter (E) and the
collector (C).
The emitter 'emits' electrons, and they are
'collected' by the collector. The base is used
to control this flow of electrons. If a small current flows from the base to the
emitter, a much larger current will flow from the collector to the emitter. How
much larger this C-E current is, depends on a constant, specific to the type of
transistor. This constant is called the DC current gain, and has the symbol of the
Greek letter bèta (β) or Hfe.
E.g. if you have a transistor with β = 100, and your B-E current = 10mA, your C-
E current will be 1A. This principle is used in amplifiers.
However, a transistor cannot keep on amplifying forever: at a certain point, the
transistor will just act like a switch.
Diode
Just like a transistor, a diode is a semiconductor
device. One of the interesting properties of a diode, is
that they only conduct electricity in one direction.
For example, Arduino boards have a diode in series
with their power input jack, to prevent you from
reversing the power, and damaging the chip.
Diodes have a forward voltage drop ranging from
0.5v to 0.7v. This means that if you measure the voltage before the diode, it will
be about 600mV higher than after the Diode, a diode has its limits: if the reverse
voltage is too high, it will break, causing it to let current pass in the wrong
direction. In some diodes, this is done in a controlled way. These diodes are called
zener diodes. They will only conduct if the voltage is higher than a certain value,
specific to the zener. This value is constant, so zener diodes are used as a
reference in voltage regulators.
Variable Resistor
We have seen about Resistors previously, and the
resistor value in those resistors cannot be changed,
but in this resistor it is possible to change the
resistance value. These resistors comes with three
pins. Two pins are connected to the ends of a fixed
resistor. The middle pin or wiper moves across the
resistor dividing it into two halves. When the external
sides of the potentiometer are connected to voltage
and ground the middle leg will give the difference in
voltage as you turn the knob. This type of resistor also called as potentiometer or
Pot. For example if you have a 10k ohms variable resistor, you can vary the
resistance from 0 to 10k by rotating the knob. Mostly these type of resistors used
with Arduino to control PWM pins available in the Arduino.

Light Dependent Resistor


As the name suggests these are type of
resistor where the resistance change
depends on the amount of light falls on the
resistor head. This is also known as photo
sensor or light sensor, most of the yester
years smart products use this simple sensor
to do some magic. If you want to make an
automatic light controller system it is
possible with this sensor. Resistance increase or decrease depends on type of
sensor.
DC Motor
A simple motor allow us to experiment with
Arduino and work with fun projects. This a
simple DC motor which cannot be used for
making movable objects, this motor cannot
produce necessary torque to move objects
that’s the reason these motor coupled with
gears to increase torque and do some useful
work. A motor converts electrical energy into
mechanical energy when electricity is applied
to its leads.
Push Button
Push button or momentary switch used for
giving inputs to Arduino. You can use this
device know how signal goes high or low
based on the switch state.

Temperature Sensor
Lm35 is an Analog temperature sensor. This
sensor can be used with any Arduino analog
pins A0 to A5. You have to do an analog read
and do some mathematical calculation to
change the analog value to Temperature in
Celsius or Fahrenheit. You can use any analog
type sensor to get a temperature value.

DHT11 Digital Temperature and Humidity


Sensor
The DHT11 is a basic, ultra low-cost digital
temperature and humidity sensor. It uses a
capacitive humidity sensor and a thermistor to
measure the surrounding air, and spits out a
digital signal on the data pin (no analog input
pins needed).

Piezo Buzzer
Piezo buzzer is an electronic device
commonly used to produce sound.
Servo Motor
These are special type of motor, these motor
are capable of rotating to a precise degree,
but these motor can move only from 0 to 180
degree. It is controlled by sending electrical
pulses from Arduino.

16x2 LCD display


Liquid display crystal are type of
alphanumeric or graphic display based on
liquid crystals. These displays are available
in many shapes and sizes, most popular are
the 16x2 type displays which has 2 rows
and capable of display 16 characters on
each row.
Sound Sensor
These sensor receive sound and covets to
electrical pulses. With help of these sensor
we can find noise or sound level in a room.

Connecting wires
These wires are very useful connecting
different components with Arduino. There
are different types of wires available male
to male, male to female, female to female.
You should have 5 wires from each type for
ease of connecting different components
with Arduino.
Breadboard
Most important component in any
project. This boards allows user to
build circuits. It’s like a patch panel,
with rows of holes that allow you to
connect wires and components
together. This eliminates the need for
soldering of components.
HARDWARE ARCHITECTURE
Basic Hardware setup
The ESP8266 board connects to your computer using an USB cable. The USB
cable provides 5 volts to your device, Most of the ESP8266 developer kit has
inbuilt 3.3v regulator to reduce the 5v to 3.3v, and it provides power enough to
run ESP8266 and to light up a couple of LEDs and some sensor, if you want to
use Servo motor or any other power hungry device with your ESP8266 connect
an external power to provide enough power.
Basic shopping list for getting started with ESP8266
 ESP8266 developer kit, you are provided with plenty of option to choose
a board.
 Mini breadboard and jumper cables
 Different color’s of LEDs
 Assorted resistor box
 Battery or a power bank
 Battery snap
 LDR (light dependent resistor)
 DHT11 or DHT22 ( Temperature and Humidity sensor)
 Servo motor
 Buzzer
 Potentiometer
 LM35 (analog temperature sensor)
 Relay (electro-Mechanical switch)
 TFT LCD
 SD card shield (if you want to save sensor details)

ESP8266 Modules:
However the first introduced board which not much breadboard friendly
integrated 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.
Connecting board to your computer for programming
Things requires to connect
1) Nodemcu
2) USB cable
Based on the manufacturer each device comes with different serial chip which
helps to connect to computer.
Make sure you have installed the correct driver for the device that you bought in
order to use with your system. A serial controller has a serial port through which
it communicates with a serially connected peripheral device.
Popular serial driver used for ESP8266 development boards
 CH340g driver
 CP210x driver
 FT232RL
Most ESP8266 WiFi developer kit requires type b USB cable which is exactly
looks like the one on the above picture.
Internet of Things (IoT)
- The next step in our Digital lives

“The IoT is a big trend, that it ups the ante. ‘Reach out and touch somebody’ is
becoming ‘reach out and touch everything’.”

What is IoT?
The Internet of Things (IoT) is a scenario in which objects, animals or people are
provided with unique identifiers and the ability to transfer data over a network
without requiring human-to-human or human-to-computer interaction.

Want to be Techgeek in IoT???


Make a Beginning now
In 2008, there were already more Internet connected objects than
people. Previously a couple of outlets listed “Internet of Things” (IoT) as one of
the words or phrases they hoped would die in 2015. Well, I hate to break it to
you, but no matter what you call it, the Internet of Things is here to stay.

By 2020, that number is expected to grow to more than 50 billion


objects. Projections estimate that the IoT market will sell more products than
the PC, tablet, and phone markets combined. There is no need of worrying
about running out of IP addresses (each connected thing needs one), because the
latest version IPv6, has enough that there are 100 IP addresses for every
single atom on earth.

Do You Go crazy for cars? Ever had a thought of making it smart?


Simple get connected to IoT and show off...
Just 10 percent of cars are connected to the Internet and by 2020 can assay that 90
percent will be. Google Driverless cars will generate $5.6 trillion in savings
worldwide. It is truly a great example of the Internet of Things technology and is
one of the greatest Internet of Things application of all time.

Today, a vision is taking shape around the world of people being connected
ubiquitously across smart cities, smart buildings, and smart cars and, perhaps,
even though sensors on or in their bodies, and the IoT is one of the foundational
platforms on which this notion of the “connected person” is predicated. The IoT
figures to touch all, and, so, all voices must be heard for the monumental benefits
promised in the connected-person vision to be fully realized.

Think of Smart Home or City!!


Connected homes will be the largest sector for IoT. In future it’s estimated to be
a $490 billion market, which is probably why Google acquired Nest (smart
thermostat makers) for $3.2 billion. Well, chances say that after few years from
now, percent of consumers will own a smart watch or smart refrigerator etc.
According to a different survey, more than two-thirds of consumers plan to buy
IoT technology for their homes.

Witnessed What GE says?


GE says that if IoT technology can make oil and gas exploration and development
even 1 percent more efficient, they can save $90 billion and technology for
industry has the potential to add $10 to $15 trillion to global GDP over the next
20 years.
Coolest IoT Gadgets:
Google Glass is a wearable head- mounted gadget from Google with a unique
optical display, which provides users with a peripheral vision on being attached
with especially designed lightweight glass frame.

Google Driver-less cars will generate $5.6 trillion in savings worldwide.

The Apple Watch is a slim and sleek gadget from this ace smart phone
manufacturing company and it is capable of communicating and syncing with all
the iOS powered devices without the need for any wired connections.

So what are your thoughts on the Internet of Things? Do you already own a smart
device??

“If you think that the internet has changed your life, think again. The IoT is about
to change it all over again!

STAY CONNECTED
SOFTWARE INSTALLATION
Install the Arduino IDE by going to the Arduino.cc website.

Click on the download page.

Download the Latest Arduino software, select the appropriate file that support
your system.
Click on the downloaded package and start your installation process.
Open the Arduino IDE that you installed on your system by clicking the Arduino
icon.

Click on the file and select preference.


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.

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.
Click on the esp8266 by ESP8266 community and install the hardware support
package for Arduino ide.

If the installation process is succeed and everything goes fine you can see
ESP8266 boards are added to your Arduino ide boards.
HARDWARE SETUP
Basic Hardware setup
The ESP8266 board connects to your computer using an USB cable. The USB
cable provides 5 volts to your device, Most of the ESP8266 developer kit has
inbuilt 3.3v regulator to reduce the 5v to 3.3v, and it provides power enough to
run ESP8266 and to light up a couple of LEDs and some sensor, if you want to
use Servo motor or any other power hungry device with your ESP8266 connect
an external power to provide enough power.
Basic shopping list for getting started with ESP8266
 ESP8266 developer kit, you are provided with plenty of option to choose
a board.
 Mini breadboard and jumper cables
 Different color’s of LEDs
 Assorted resistor box
 Battery or a power bank
 Battery snap
 LDR (light dependent resistor)
 DHT11 or DHT22 ( Temperature and Humidity sensor)
 Servo motor
 Buzzer
 Potentiometer
 LM35 (analog temperature sensor)
 Relay (electro-Mechanical switch)
 TFT LCD
 SD card shield (if you want to save sensor details)
TYPES OF ESP8266
ESPresso Lite V2.0 is a low-cost
Arduino-compatible ESP8266 Wi-
Fi development board
manufactured in Malaysia. This
board allows anyone to learn,
experiment and build their IoT
projects easily and quickly. The
core hardware inside ESPresso Lite
V2.0 is Espressif System's
ESP8266 WROOM-02 WiFi
module and is programmable using
the Arduino IDE like how anyone
would run their programs in other
Arduino boards.

The NodeMcu is an open-source


firmware and development kit that
helps you to Prototype your IOT
product within a few Lua script
lines. Less than $2 WI-FI MCU
ESP8266 integrated and easy to
prototyping development kit. The
Development Kit based on
ESP8266, integrates GPIO, PWM,
IIC, 1-Wire and ADC all in one
board. Power your development in the fastest way combining with NodeMCU
Firmware!
A replicate of Nodemcu available
in the market known as lolin, This
board is slightly larger than the
Nodemcu and it is not a bread-
board friendly, if you are
purchasing this board make sure
you also buying a support kit for
this hardware, it will not have
breadboard expose for connecting
other hardware to this dev board.

MOD-WIFI-ESP8266-DEV is a tiny
development board that can add WIFI
capabilities to existing boards. It uses espressif
system's chip ESP8266EX. All chip signals are
exposed for easier access. The board can be
soldered to PCB or used with a breadboard.
This board comes with UEXT and pads for
external antenna.

The SparkFun ESP8266 Thing is a breakout and


development board for the ESP8266 WiFi SoC –
a leading platform for Internet of Things (IoT) or
WiFi-related projects. The Thing is low-cost and
easy to use, and Arduino IDE integration can be
achieved in just a few steps, this board comes with
LiPo charger, power supply, and all of the other
supporting circuitry it requires.
The ESP210 is an ESP8266 based
module with a USB transceiver, 3.3V
voltage regulator (you can run it from 5v
or the USB port) and a 32MBit (that is 4
MByte!!) FLASH memory. Unlike many
other ESP8266 based modules this
module comes prepared for anyone that
wants to tinker and play around with it
without having to connect external
adapters and power supplies to it. In fact,
to start playing with it you only need to
plug it in to your computers USB port. The device will take all of its power from
the USB port. The ESP210 also has a user definable LED on the board so you can
start of by running your first blink test.

D1 mini is a mini Wi-Fi board


based on ESP-8266EX, it has 11
digital input/output pins. This is a
smallest IoT device available in
the market this can be bought
from aliexpress and other online
shops, one of the advantage of
this device is it comes with many
add on shields from the same
manufacturer.

This is an Arduino like ESP8266


board, this board does not
support any of the Arduino shield
and does not resemble the same
pin configuration that of
Arduino. Those who want’s an
ESP board with Arduino
lookalike can use this board and
it has no greater function than any other ESP boards available in the market. This
board supports external power jack which can be used to connect to a plug or a
battery during operation of this board.
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
antenna, and plenty of pins.

The Adafruit Feather Huzzah is


a breakout board for the
ESP8266. This was designed to
have a LiPo battery supporter on
the board. This device comes
with an on-board antenna, and
plenty of pins.
Throughout the tutorial we are going to use Nodemcu board for practicing IoT,
as the board is low cost, one can buy a board for few dollars at an online store.
This board is very good starter for a newbie or an expert who wants to make IoT
devices for low cost.
It is not mandatory to use Nodemcu to successfully complete the tutorial on IoT.
Any board which carry an ESP8266 can be used for the tutorials to follow. 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
ESP8266 Hardware

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, 1×1 MIMO, 2×1 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.
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.
General Purpose IO

A total of up to 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.
GETTING STARTED
Arduino Software Software programs, called sketches, are created on a
computer using the Arduino Integrated Development Environment (IDE). The
IDE enables you to write and edit code and convert this code into instructions that
ESP8266 understands. The IDE also transfers those instructions to the ESP8266
board by a process called uploading.
The programming cycle on ESP8266 is basically as follows:
 Plug your board into a USB port on your computer.
 Write a sketch that will bring the board to life.
 Upload this sketch to the board through the USB connection and wait a
couple of seconds for the board to restart.
 The board executes the sketch that you wrote.

Follow the steps to program your ESP8266 for the first time.
Step 1: Open the Arduino IDE This is a program window where you write your
code. As you can see it is divided into three sections. First section consists of 5
Tabs File, Edit, Sketch, Tools, and Help. Open one by one each tab and just study
different options inside it. Below it you can see few buttons like Tick Mark, Side
Arrow, New File Button, Up Arrow, and Down Arrow. And on the Right most
corner side in the same line you will see a button for Serial Monitor; this tab is
used when serial communication is needed with computer.
Second section comprises of a large empty white space. This space is used to
write your program or sketch. Program is written in C language which is the most
widely used language in computer programming and is also very easy to
understand. Third Section comprises of a Black window where the status is
shown, if there is an error on compiling the program then the error message is
shown in this window, if program gets uploaded successfully then that message
is shown here.
Step 2: Board Selection
Go to the tools tab, in the drop down menu select ―Board, another window by
its side will be opened showing different type of boards.

Choose the ESP8266 development board you are using currently. If your board
is not available in the list, you can select NodeMCU 1.0, this board will be
suitable for other boards that available in the market.
Step 3: Port Selection You need to select the port on which the board is
connected. To do that first you need to identify on which port the ESP8266
development board is connected.
Port Identification: Windows On windows, the process is a bit more
complicated. Open the device manager by clicking the Start menu, right-clicking
on Computer (Vista,) or My Computer (XP, Win 7, Win 8 and Win 10), and
choosing Properties. On Windows XP, Win 7, Win 8 and Win 10, click Hardware
and choose Device Manager. On other windows, click Device Manager (it
appears in the list of tasks on the left of the window).Look for the COM port
device in the list under ―Ports (COM & LPT) you will see Serial driver
Manufacturer name or as USB Serial Port. Check the port number which is
written.

Port Identification: Macintosh Select the serial device of the Arduino board
from the Tools > Serial Port menu. On the Mac, this should be something with
/dev/tty.usbmodem (for the Uno or Mega 2560) or /dev/tty.usbserial (for older
boards) in it.
Getting Started With Hello World
The LED blinking sketch is the first program that you should run to test whether
your ESP8266 board is working and is configured correctly. It is also usually the
very first programming exercise someone does when learning to program a
microcontroller.
LED as you see is round or dome shaped from top with two legs coming out at
the bottom. One of the leg is longer than the other; it is because to identify the
anode and cathode terminal. As said before LED is a form of diode thus will
conduct electricity or glow only when it is connected properly i.e. positive
terminal or anode of LED is connected to positive terminal of battery and negative
terminal or cathode of LED is connected to negative terminal of the battery.
When a LED is forward-biased (switched on), electrons are able to recombine
with electron holes within the device, releasing energy in the form of photons.
This effect is called electroluminescence and the color of the light (corresponding
to the energy of the photon) is determined by the energy gap of the
semiconductor. LEDs present many advantages over incandescent light sources
including lower energy consumption, longer lifetime, improved physical
robustness, smaller size, and faster switching. LEDs powerful enough for room
lighting are relatively expensive and require more precise current and heat
management than compact fluorescent lamp sources of comparable output.
For blinking an external LED you need to use an external resistor for it too as by
directly connecting the LED to other pins may harm your ESP8266 board. Once
the LED is connected, you need to tell ESP8266, what to do. This is done through
the code, that is, a list of instructions that we give the microcontroller to make it
do what we want.
The D7 pin in NodeMCU is mapped to GPIO 13 pin of ESP8266, when you
program NodeMCU in Arduino IDE you are supposed to use GPIO pin number
instead of the pin numbers available in the NodeMCU dev kit.
To write a sketch or a program first you need to open the Arduino IDE or Arduino
software where you installed it. After that select File>New and you will be asked
to choose a sketch folder name: this is where your Arduino sketch will be stored.
Name it Blinking_LED and click OK. Then type the following text (Program 1)
into the Arduino Sketch editor (The main window of the Arduino IDE).

// the setup function runs once when you press reset or power the board
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
}
Please do not copy paste the code until you become familiar with different
instructions, as you may find there are Capital letter in between an instruction for
example digitalWrite ; in this instruction W is the capital letter, type the
instructions in the Arduino IDE code editor and check whether you are typing the
instructions correctly.
Now type the code is in your IDE, you need to verify it. Press the Verify button;
if everything is correct, you will see the message ―Done compiling appear at the
bottom of the Arduino IDE in the black area. This message means that Arduino
IDE has translated your sketch into an executable program that can be run by the
board, a bit like an .exe file in Windows or an .app file on a Mac.
At this point, you can upload it into the board: press the Upload to I/O Board
button. This will reset the board, forcing it to stop what it‘s doing and listen for
instructions coming from the USB port. The Arduino IDE sends the current
sketch to the board, which will store it in its memory and eventually run it.
You will see a few messages appear in the black area at the bottom of the window,
and just above that area, you will see the message “Done uploading” appear to let
you know the process has completed correctly. The inbuilt LED, on the board;
will flash every time a byte is sent or received by the board. During the upload
process, it keep flickering.
If you don‘t see the LEDs flicker, or if you get an error message instead of “Done
uploading”, then there is a communication problem between your computer and
ESP8266. Make sure you have selected the right serial port in the Tools>Serial
Port menu. Also check the Tools>Board menu to confirm that ESP8266
development board is selected there.
Once the code is uploaded to your ESP8266 Board, it will stay there until you put
another sketch on it. The sketch will survive if the board is reset or turned off, a
bit like the data on your computer‘s hard drive.
Assuming that the sketch has been uploaded correctly, you will see the LED turn
On for a second and then turn Off for a second.
What you have just written and run is a “computer program”, or a sketch, as
Arduino programs are called. ESP8266 board, as I have mentioned before, is a
small computer, and it can be programmed to do what you want. This is done
using a programming language to type a series of instructions in the Arduino IDE,
which turns it into an executable for your ESP8266 board.
I will next show you to understand the sketch. First of all, the Arduino executes
the code from top to bottom, so the first line at the top is the first one read; then
it moves down, a bit like how the play head of a video player like QuickTime
Player or Windows Media Player moves from left to right showing where in the
move you are.
Arduino IDE expects two functions to exist- one called setup() and one called
loop(). setup() is where you put all the code that you want to execute once at the
beginning of your program and loop() contains the core of your program, which
is executed over and over again. This is done because ESP8266 is not like your
regular computer- it cannot run multiple programs at the same time and programs
can‘t quit. When you power up the board, the code runs; when you want to stop,
you just turn it off.
Any text beginning with // is ignored by Arduino. These lines are comments,
which are notes that you leave in the program for yourself, so that you can
remember what you did when you wrote it, or somebody else, so that they can
understand your code.
// the setup function runs once when you press reset or power the board
It is very common to write a piece of code, upload it onto the board, and say
―Okay-I‘m never going to have to touch this again! Only to realize six months
later that you need to update the code or fix a bug. At this point, you open up the
program, and if you haven‘t included any comments in the original program, you
will think, ―What a mess! Where do I start? As we move along, you will see
some tricks for how to make your programs more readable and easier to maintain.
Basic Programming in Arduino IDE
Programming in Arduino is very simple and easy to understand. Basically it is
derived from C language which is the most commonly used software language
globally. Also because it is easy to understand you can right away start with few
basic programs without going into much details. Also you can go for small
projects and can interface various components like motors, sensors, actuators
very easily to ESP8266.
Basic Structure of Program
The basic structure of the Arduino programming language is fairly simple and
runs in at least two parts. These two required parts, or functions, enclose blocks
of statements.
void setup()
{
statements;
}
void loop()
{
statements;
}
Where setup() is the preparation, loop() is the execution. Both functions are
required for the program to work. The setup function should follow the
declaration of any variables at the very beginning of the program. It is the first
function to run in the program, it runs only once, and is used to set pinMode or
initialize serial communication. pinMode is a command used in Arduino
programming to declare whether the I/O pin will be as an Input or as Output.
There are 9 Digital I/O pins on your ESP8266 board so out of these you can use
any of the 9 pins as an Input or an Output but you have to first declare how you
intend to use it. Means it will be used as an Output pin when you need to give
some current to an output device like an LED or Buzzer, and will be used as a
Input pin when you need to read the value from an input device such as a IR
Sensor or a Push Button(whether its pressed or not) or LDR.
Syntax for declaring 13 pin as Input and 12 pin as Output (you can use any pin):
pinMode(13,INPUT); // pin 13 of ESP8266 is declared as an Input pin
pinMode(12,OUTPUT); // pin 12 of ESP8266 is declared as an Output pin The
loop function follows next and includes the code to be executed continuously
reading inputs, triggering outputs, etc. This function is the core of all Arduino
programs and does the bulk of the work.
setup()
The setup() function is called once when your program starts. Use it to initialize
pin modes, or begin serial. It must be included in a program even if there are no
statements to run.
void setup()
{
pinMode(pin, OUTPUT); // sets the 'pin' as output
}
loop()
After calling the setup() function, the loop() function does precisely what its
name suggests, and loops consecutively, allowing the program to change,
respond, and control the Arduino board. The statements written inside the loop
runs over and over again, following the order from top to bottom and again
starting from top.
void loop()
{
digitalWrite(pin, HIGH); // turns 'pin' on
delay(1000); // pauses for one second
digitalWrite(pin, LOW); // turns 'pin' off
delay(1000); // pauses for one second
}

For reading or writing on any digital pin of ESP8266 board digitalRead and
digitalWrite are used respectively.
pinMode(pin, mode)
Used in void setup() to configure a specified pin to behave either as an INPUT or
an OUTPUT.
pinMode(pin, OUTPUT); // sets ‗pin‘ to output
pinMode(pin, INPUT); // set ‗pin‘ to input
Pins configured as OUTPUT can provide 40 mA (milliamps) of current to other
devices/circuits. This is enough current to brightly light up an LED (don't forget
the series resistor), but not enough current to run most relays, solenoids, or
motors.
Short circuits on ESP8266 pins and excessive current can damage or destroy the
output pin, or damage the entire chip. It is often a good idea to connect an
OUTPUT pin to an external device in series with a 470Ω or 1KΩ resistor.
digitalRead(pin)
Reads the value from a specified digital pin with the result either HIGH or LOW.
The pin can be specified as either a variable or constant
value = digitalRead(Pin); // sets 'value' equal to the input pin
digitalWrite(pin, value)
Outputs either logic level HIGH or LOW at (turns on or off) a specified digital
pin. The pin can be specified as either a variable or constant.
digitalWrite(pin, HIGH); // sets 'pin' to high
HIGH/LOW
These constants define pin levels as HIGH or LOW and are used when reading
or writing to digital pins. HIGH is defined as logic level 1, ON, or 3.3 volts while
LOW is logic level 0, OFF, or 0 volts.
digitalWrite(13, HIGH);
digitalWrite(8, LOW);
input/output
Constants used with the pinMode() function to define the mode of a digital pin
as either INPUT or OUTPUT.
pinMode(13, OUTPUT);
pinMode(8, INPUT);
PWM
Pulse Width Modulation, or PWM, is a technique for getting analog results with
digital means. Digital control is used to create a square wave, a signal switched
between on and off. This on-off pattern can simulate voltages in between full on
(3.3 Volts) and off (0 Volts) by changing the portion of the time the signal spends
on versus the time that the signal spends off. The duration of "on time" is called
the pulse width. To get varying analog values, you change, or modulate, that pulse
width. If you repeat this on-off pattern fast enough with an LED for example, the
result is as if the signal is a steady voltage between 0 and 3.3v controlling the
brightness of the LED.

Note: All the pins of ESP8266 can be used as a PWM pin except GPIO16.
analogWrite(pin, value)
Writes an analog value (PWM wave) to a pin. Can be used to light an LED at
varying brightnesses or drive a motor at various speeds. After a call to
analogWrite(), the pin will generate a steady square wave of the specified duty
cycle until the next call to analogWrite() (or a call to digitalRead() or
digitalWrite() on the same pin). The frequency of the PWM signal is
approximately 490 Hz.
analogWrite(pin, value); // writes 'value' to analog 'pin'
A value of 0 generates a steady 0 volts output at the specified pin; a value of 255
generates a steady 3.3 volts output at the specified pin. For values in between 0
and 255, the pin rapidly alternates between 0 and 3.3 volts - the higher the value,
the more often the pin is HIGH (3.3 volts). For example, a value of 64 will be 0
volts three-quarters of the time, and 3.3 volts one quarter of the time; a value of
128 will be at 0 half the time and 255 half the time; and a value of 192 will be 0
volts one quarter of the time and 3.3 volts three-quarters of the time.
Note: Analog pins unlike digital ones, do not need to be first declared as INPUT
nor OUTPUT.
analogRead(pin)
Reads the value from the specified analog pin with a 10-bit resolution. The
ESP8266 board contains a 1 channel 10-bit analog to digital converter. This
means that it will map input voltages between 0 and 3.3 volts into integer values
between 0 and 1023. This yields a resolution between readings of: 3.3 volts / 1024
units.
It takes about 100 microseconds (0.0001 s) to read an analog input, so the
maximum reading rate is about 10,000 times a second.
value = analogRead(pin); // sets 'value' equal to 'pin'
Difference between and analog signal and digital signals is that digital signal only
works with 2 values that is High (3.3) and Low (0) whereas analog signal has a
range of values.
Range of analog input values is from 0-1023 and analog output values is 0-255.
So when we use an analog input then the values we get are in the range of 0- 1023
and we can convert it into the range of 0-255 by just dividing it by 4. Whereas
when we write on analog output pin it has a range of 0-255 through which we can
write the values.
Functions
A function is a block of code that has a name and a block of statements that are
executed when the function is called. The functions void setup() and void loop()
have already been discussed and other built-in functions will be discussed later.
Custom functions can be written to perform repetitive tasks and reduce clutter in
a program. Functions are declared by first declaring the function type. This is the
type of value to be returned by the function such as 'int' for an integer type
function. If no value is to be returned the function type would be void. After type,
declare the name given to the function and in parenthesis any parameters being
passed to the function.
type functionName(parameters)
{
statements;
}
The following integer type function delayVal() is used to set a delay value in a
program by reading the value of a potentiometer. It first declares a local variable
v, sets v to the value of the potentiometer which gives a number between 0- 1023,
then divides that value by 4 for a final value between 0-255, and finally returns
that value back to the main program.
int delayVal()
{
int v; // create temporary variable 'v'
v = analogRead(pot); // read potentiometer value
v /= 4; // converts 0-1023 to 0-255
return v; // return final value
}
{} curly braces
Curly braces (also referred to as just "braces" or "curly brackets") define the
beginning and end of function blocks and statement blocks such as the void loop()
function and the for and if statements.
type function()
{
statements;
}
An opening curly brace {must always be followed by a closing curly brace}. This
is often referred to as the braces being balanced. Unbalanced braces can often
lead to cryptic, impenetrable compiler errors that can sometimes be hard to track
down in a large program. The Arduino environment includes a convenient feature
to check the balance of curly braces. Just select a brace, or even click the insertion
point immediately following a brace, and its logical companion will be
highlighted.
; Semicolon
A semicolon must be used to end a statement and separate elements of the
program. A semicolon is also used to separate elements in a( for loop ).
int x = 13; // declares variable 'x' as the integer 13
Note: Forgetting to end a line in a semicolon will result in a compiler error. The
error text may be obvious, and refer to a missing semicolon, or it may not. If an
impenetrable or seemingly illogical compiler error comes up, one of the first
things to check is a missing semicolon, near the line where the compiler
complained.
/*… */ block comments
Block comments, or multi-line comments, are areas of text ignored by the
program and are used for large text descriptions of code or comments that help
others understand parts of the program. They begin with /* and end with */ and
can span multiple lines.
/* this is an enclosed block comment don‘t forget the closing comment –
They have to be balanced! */
Because comments are ignored by the program and take no memory space they
should be used generously and can also be used to “comment out” blocks of code
for debugging purposes.
// line comments
Single line comments begin with // and end with the next line of code. Like block
comments, they are ignored by the program and take no memory space.
// this is a single line comment
Single line comments are often used after a valid statement to provide more
information about what the statement accomplishes or to provide a future
reminder.
Variables
A variable is a way of naming and storing a numerical value for later use by the
program. As their name suggests, variables are numbers that can be continually
changed as opposed to constants whose value never changes. A variable needs to
be declared and optionally assigned to the value needing to be stored.
int inputVariable = 0; // declares a variable and assigns value of 0
inputVariable = analogRead(0); // set variable to value of analog pin 0
“inputVariable” is the variable itself. The first line declares that it will contain an
int, short for integer. The second line sets the variable to the value at analog pin
0. This makes the value of pin 0 accessible elsewhere in the code. Once a variable
has been assigned, or re-assigned, you can test its value to see if it meets certain
conditions, or you can use its value directly.
Note: Variables should be given descriptive names, to make the code more
readable. Variable names like tiltSensor or pushButton help the programmer and
anyone else reading the code to understand what the variable represents. Variable
names like var or value, on the other hand, do little to make the code readable and
are only used here as examples. A variable can be named any word that is not
already one of the keywords in the Arduino language.
Variable declaration
All variables have to be declared before they can be used. Declaring a variable
means defining its value type, as in int, long, float, etc., setting a specified name,
and optionally assigning an initial value. This only needs to be done once in a
program but the value can be changed at any time using arithmetic and various
assignments.
The following example declares that inputVariable is an int, or integer type, and
that its initial value equals zero. This is called a simple assignment.
int inputVariable = 0;
A variable can be declared in a number of locations throughout the program and
where this definition takes place determines what parts of the program can use
the variable.
Variable scope
A variable can be declared at the beginning of the program before void setup(),
locally inside of functions, and sometimes within a statement block such as for
loops. Where the variable is declared determines the variable scope, or the ability
of certain parts of a program to make use of the variable. A global variable is one
that can be seen and used by every function and statement in a program. This
variable is declared at the beginning of the program, before the setup() function.
A local variable is one that is defined inside a function or as part of a (for loop).
It is only visible and can only be used inside the function in which it was declared.
It is therefore possible to have two or more variables of the same name in different
parts of the same program that contain different values. Ensuring that only one
function has access to its variables simplifies the program and reduces the
potential for programming errors.
The following example shows how to declare a few different types of variables
and demonstrates each variable‘s visibility:
int value; // 'value' is visible to any function
void setup()
{
// no setup needed
}
void loop()
{
for (int i=0; i<20;) // 'i' is only visible
{ // inside the for-loop
i++;
}
float f; // 'f' is only visible inside loop
}
byte
Byte stores an 8-bit numerical value without decimal points. They have a range
of 0-255.
byte someVariable = 180; // declares 'someVariable' as a byte type
int
Integers are the primary datatype for storage of numbers without decimal points
and store a 16-bit value with a range of 32,767 to -32,768.
int someVariable = 1500; // declares 'someVariable' as an integer type

long
Extended size datatype for long integers, without decimal points, stored in a 32-
bit value with a range of 2,147,483,647 to -2,147,483,648.
long someVariable = 90000; // declares 'someVariable' as a long type
float
A datatype for floating-point numbers, or numbers that have a decimal point.
Floating-point numbers have greater resolution than integers and are stored as a
32-bit value with a range of 3.4028235E+38 to -3.4028235E+38.
float someVariable = 3.14; // declares 'someVariable' as a floating-point type
Arithmetic
Arithmetic operators include addition, subtraction, multiplication, and division.
They return the sum, difference, product, or quotient (respectively) of two
operands.
y = y + 3;
x = x - 7;
j = j * 6;
r = r / 5;
The operation is conducted using the data type of the operands, so, for example,
9 / 4 results in 2 instead of 2.25 since 9 and 4 are ints and are incapable of using
decimal points. This also means that the operation can overflow if the result is
larger than what can be stored in the data type.
If the operands are of different types, the larger type is used for the calculation.
For example, if one of the numbers (operands) are of the type float and the other
of type integer, floating point math will be used for the calculation. Choose
variable sizes that are large enough to hold the largest results from your
calculations. Know at what point your variable will rollover and also what
happens in the other direction e.g. (0 - 1) OR (0 - - 32768). For math that requires
fractions, use float variables, but be aware of their drawbacks: large size and slow
computation speeds.
Comparison operators
Comparisons of one variable or constant against another are often used in if
statements to test if a specified condition is true. Different types of condition used
are:
x == y // x is equal to y
x != y // x is not equal to y
x < y // x is less than y
x > y // x is greater than y
x <= y // x is less than or equal to y
x >= y // x is greater than or equal to y
Logical operators
Logical operators are usually a way to compare two expressions and return a
TRUE or FALSE depending on the operator. There are three logical operators,
AND, OR, and NOT, that are often used in if statements:
Logical AND:
if (x > 0 && x < 5) // true only if both expressions are true
Logical OR:
if (x > 0 || y > 0) // true if either expression is true
Logical NOT:
if (!x > 0) // true only if expression is false
Constants
The Arduino language has a few predefined values, which are called constants.
They are used to make the programs easier to read. Constants are classified in
groups.
True/False These are Boolean constants that define logic levels. FALSE is easily
defined as 0 (zero) while TRUE is often defined as 1, but can also be anything
else except zero. So in a Boolean sense, -1, 2, and -200 are all also defined as
TRUE.
if (b == TRUE);
{ doSomething; }
If
if statements test whether a certain condition has been reached, such as an analog
value being above a certain number, and executes any statements inside the
brackets if the statement is true. If false the program skips over the statement. The
format for an if test is:
if (someVariable == value)
{
doSomething;
}
The above example compares someVariable to another value, which can be either
a variable or constant. If the comparison, or condition in parentheses is true, the
statements inside the brackets are run. If not, the program skips over them and
continues on after the brackets. Note: Beware of accidentally using ‗=‘, as in
if(x=10), while technically valid, defines the variable x to the value of 10 and is
as a result always true. Instead use “==”, as in if(x==10), which only tests whether
x happens to equal the value 10 or not. Think of “=” as “equals” opposed to “=
=” being “is equal to”.
if… else
if… else allows for ‗either-or‘ decisions to be made. For example, if you wanted
to test a digital input, and do one thing if the input went HIGH or instead do
another thing if the input was LOW, you would write that this way:
if (inputPin == HIGH)
{ doThingA;
} else
{ doThingB;
}
else can also precede another if test, so that multiple, mutually exclusive tests can
be run at the same time. It is even possible to have an unlimited number of these
else branches. Remember though, only one set of statements will be run
depending on the condition tests:

if (inputPin < 500)


{
doThingA;
}
else if (inputPin >= 1000)
{
doThingB;
}
else
{
doThingC;
}
Note: An if statement simply tests whether the condition inside the parenthesis is
true or false.
for
The for statement is used to repeat a block of statements enclosed in curly braces
a specified number of times. An increment counter is often used to increment and
terminate the loop. There are three parts, separated by semicolons (;), to the for
loop header:
for (initialization; condition; expression)
{
doSomething;
}
The initialization of a local variable, or increment counter, happens first and only
once. Each time through the loop, the following condition is tested. If the
condition remains true, the following statements and expression are executed and
the condition is tested again. When the condition becomes false, the loop ends.
The following example starts the integer i at 0, tests to see if i is still less than 20
and if true, increments i by 1 and executes the enclosed statements:

for (int i=0; i<20; i++) // declares i, tests if less // than 20, increments i by 1
{
digitalWrite(13, HIGH); // turns pin 13 on
delay(250); // pauses for 1/4 second
digitalWrite(13, LOW); // turns pin 13 off
delay(250); // pauses for 1/4 second
}
while
While loops will loop continuously, and infinitely, until the expression inside the
parenthesis becomes false. Something must change the tested variable, or the
while loop will never exit. This could be in your code, such as an incremented
variable, or an external condition, such as testing a sensor.
While (someVariable ?? value)
{
doSomething;
}
The following example tests whether “someVariable” is less than 200 and if true
executes the statements inside the brackets and will continue looping until
“someVariable” is no longer less than 200.
while (someVariable < 200) // tests if less than 200
{
doSomething; // executes enclosed statements s
omeVariable++; // increments variable by 1
}
do… while The do loop is a bottom driven loop that works in the same manner
as the while loop, with the exception that the condition is tested at the end of the
loop, so the do loop will always run at least once.
do
{
doSomething;
}
while (someVariable ?? value);
The following example assigns readSensors() to the variable ‘x‘, pauses for 50
milliseconds, then loops indefinitely until ‘x‘ is no longer less than 100:
do
{
x = readSensors(); // assigns the value of readSensors() to x
delay (50); // pauses 50 milliseconds
}
while (x < 100); // loops if x is less than 100
delay(ms)
Pauses a program for the amount of time as specified in milliseconds, where 1000
equals 1 second.
delay(1000); // waits for one second
millis()
Returns the number of milliseconds since the Arduino board began running the
current program as an unsigned long value.
value = millis(); // sets ‘value‘ equal to millis()
min(x, y)
Calculates the minimum of two numbers of any data type and returns the smaller
number.
value = min(value, 100); // sets 'value' to the smaller of . 'value' or 100, ensuring
that it never gets above 100.
max(x, y) Calculates the maximum of two numbers of any data type and returns
the larger number.
value = max(value, 100); // sets 'value' to the larger of 'value' or 100, ensuring
that it is at least 100.
Serial.begin(rate) Opens serial port and sets the baud rate for serial data
transmission. The typical baud rate for communicating with the computer is 9600
although other speeds are supported.
void setup()
{
Serial.begin(9600); // opens serial port sets data rate to 9600 bps
}
Serial.println(data) Prints data to the serial port, followed by an automatic
carriage return and line feed. This command takes the same form as Serial.print(),
but is easier for reading data on the Serial Monitor.
Serial.println(analogValue); // sends the value of 'analogValue'
Note: For more information on the various permutations of the Serial.println()
and Serial.print() functions please refer to the Arduino website.
The following simple example takes a reading from analog pin0 and sends this
data to the computer every 1 second.
void setup()
{
Serial.begin(9600); // sets serial to 9600bps
}
void loop()
{
Serial.println(analogRead(0)); // sends analog value
delay(1000); // pauses for 1 second
}
Programming Multiple LEDs

Connect LEDs to GPIO16, GPIO13, and GPIO15, don’t forget to connect a


resistor to the LED cathode and ground.
Arduino Program for Blinking 3 LEDs
void setup() {
pinMode(16, OUTPUT);
pinMode(13,OUTPUT);
pinMode(15,OUTPUT);
}
void loop() {
digitalWrite(16,HIGH);
digitalWrite(13,HIGH);
digitalWrite(15,HIGH);
delay(1000);
digitalWrite(16,LOW);
digitalWrite(13, LOW);
digitalWrite(15,LOW);
delay(1000);
}
Arduino program for blinking One after another.
void setup() {
pinMode(16, OUTPUT);
pinMode(13,OUTPUT);
pinMode(15,OUTPUT);
}
void loop() {
digitalWrite(16,HIGH);
digitalWrite(13,LOW);
digitalWrite(15,LOW);
delay(1000);
digitalWrite(16,LOW);
digitalWrite(13, HIGH);
digitalWrite(15,LOW);
delay(1000);
digitalWrite(16,LOW);
digitalWrite(13,LOW);
digitalWrite(15,HIGH);
delay(1000);
}

Find the difference between these two programs and upload the sketch to your
ESP8266 board and check what’s happening to your LEDs connected to your
board. This is a very simple program to do and allow you to be familiarise on
Arduino sketch.
Task: Write a program for Blinking 5 LEDs and connect 5 LEDs to your hardware
and upload the sketch and check the working.
Programming for a Push button and a
LED
Arduino IDE program for turn on and off a LED using a pushbutton
const int pinButton = 5; // GPIO 5 is named as PinButton
const int pinLed = 13; //GPIO 13 named as pinLed
void setup()
{
// Configure the button's pin for input signals.
pinMode(pinButton, INPUT);

// Configure the LED's pin for output.


pinMode(pinLed, OUTPUT);
}

void loop()
{
if(digitalRead(pinButton))
{
// When the button is pressed, turn the LED on.
digitalWrite(pinLed, HIGH);
}
else
{
// Otherwise, turn the LED off.
digitalWrite(pinLed, LOW);
}
delay(10);
}
Note: change the logic of the program to the condition, when you press a button
led should turn off and when you release the button led should go on.
Using a Potentiometer (analog sensor)
with ESP8266
Arduino Program for Reading a Potentiometer value.

// Define the pin to which the angle sensor is connected.


const int potentiometer = A0;

void setup()
{
// Configure the serial communication line at 9600 baud (bits per second.)
Serial.begin(9600);

// Configure the angle sensor's pin for input.


pinMode(potentiometer, INPUT);
}

void loop()
{
// Read the value of the sensor and print it to the serial console.
int value = analogRead(potentiometer);
Serial.println(value);

// Wait 0.1 seconds between readings.


delay(100);
}
Open the serial monitor and change the knob of the potentiometer and observer
the potentiometer reading on your serial monitor. If you are using ESP8266
generic board you can find that senor reaches maximum value of 1024 without
reaching the end of potentiometer. Find why it is happening and try to arrive to a
solution.
PWM using Potentiometer and LED
Arduino IDE program for controlling a brightness of an LED using Potentiometer
There are a variety of purposes for PWM. Some are output data encoders. One
commonly seen purpose is to control the brightness of an LED. If we apply
maximum voltage to an LED, it is maximally bright. If we apply 1/2 the voltage,
it is about 1/2 the brightness. By applying a fast period PWM signal to the input
of an LED, the duty cycle becomes the brightness of the LED.
The way this works is that either full voltage or no voltage is applied to the LED
but because the period is so short, the "average" voltage over time follows the
duty cycle and even though the LED is flickering on or off, it is so fast that our
eyes can't detect it and all we see is the apparent brightness change.
// These constants won't change. They're used to give names
// to the pins used:
const int analogInPin = A0; // Analog input pin that the potentiometer is attached
to
const int analogOutPin = 13; // Analog output pin that the LED is attached to

int sensorValue = 0; // value read from the pot


int outputValue = 0; // value output to the PWM (analog out)

void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}

void loop() {
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255);
// change the analog out value:
analogWrite(analogOutPin, outputValue);

// print the results to the serial monitor:


Serial.print("sensor = ");
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);

// wait 2 milliseconds before the next loop


// for the analog-to-digital converter to settle
// after the last reading:
delay(2);
The idea behind pulse width modulation is that we can think of regular pulses of
output signals encoding information as a function of how long the signal is kept
high. Let us imagine that we have a period of 1HZ (one thing per second). Now
let us assume that we raise the output voltage to a level of 1 for 1/2 of a second
at the start of the period. This would give us a square wave which starts high, lasts
for 500 milliseconds and then drops low for the next 500 milliseconds. This
repeats on into the future. The duration that the pulse is high relative to the period
allows us to encode an analog value onto digital signals. If the pulse is 100% high
for the period then the encoded value would be 1.0. If the pulse is 100% low for
the period, then the encoded value would be 0.0. If the pulse is on for "n"
milliseconds (where n is less than 1000), then the encoded value would be n/1000.
Typically, the length of a period is not a second but much, much smaller allowing
us to output many differing values very quickly. The ratio of the on signal to the
period is called the "duty cycle". This encoding technique is called "Pulse Width
Modulation" or "PWM".
For the ESP8266, the period of the PWM can range from 1 millisecond to 10
milliseconds. This is a frequency of 1KHz to 100Hz. The resolution of the duty
cycle is down to 45 nanoseconds which is 14 bits of resolution data. The device
provides support for up to 8 PWM channels where each channel can be associated
with its own pin and duty cycle. The period is the same for all PWM channels.
Servo Motor with ESP8266
A servomotor is a rotary actuator or linear actuator that allows for precise control
of angular or linear position, velocity and acceleration. It consists of a
suitable motor coupled to a sensor for position feedback.
Connect the servo motor as shown in the figure, provide an external power supply
for servo motor, I have tested without an external power supply and it was worked
well with Nodemcu board but it is not safety to use a servo motor without any
external power as it may draw more current from the ESP8266 and cause damage
to the board.
Connect the output of the servo motor to the GPIO2 pin of ESP8266, note the
fritzing circuit carefully I have connected a common ground to the Servo and
ESP8266 it is essential to connect a common ground between these device even
though the servo motor uses external power, if you don’t connect common ground
then your servo motor will not respond.
Servo Motor sweep code for ESP8266
#include <Servo.h>

Servo myservo; // create servo object to control a servo


// twelve servo objects can be created on most boards

void setup()
{
myservo.attach(2); // attaches the servo on GPIO2 to the servo object
}

void loop()
{
int pos;

for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=0; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
GETTING STARTED WITH IOT
ESP Wi-Fi Library for Arduino IDE
WiFi.begin()
This function initializes the WiFi library’s network settings and provides the
current status
Syntax
WiFi.begin();
WiFi.begin(ssid);
WiFi.begin(ssid,Pass);
WiFi.begin(ssid,keyindex,key);
Begin a WiFi connection as a station. The ssid parameter is mandatory but the
others can be left as default. The return value is WL_CONNECTED when
connected to a network. WL_IDLE_STATUS when not connected to a network.

WiFi.disconnect()
This function disconnects the WiFi shield from the current network.
Syntax
WiFi.disconnect()
This function does not require any parameter and returns nothing.

WiFi.config()
This function allows to configure a static IP address as well as change the DNS
gateway and subnet addresses on the WiFi shield.
Syntax
WiFi.config(ip);
WiFi.config(ip,dns);
WiFi.config(ip,dns,gateway);
WiFi.config(ip,dns,gateway,subnet);
The parameter required for this function are Ip, dns , gateway and subnet, This
function returns nothing.
WiFi.setDNS()
This function allows to configure the Domain Name System (DNS) server
Syntax
WiFi.setDNS(dns_server1)
WiFi.setDNS(dns_server1,dns_server2)
Parameter required for this function is:
dns_server1: the IP address of the primary DNS server
dns_server2: the IP address of the secondary DNS server
This function returns nothing.

WiFi.SSID()
This function returns the name of the current network.
Syntax:
WiFi.SSID()
WiFi.SSID(wifiAccessPoint)
WifiAccessPoint: specifies the network to get information.
This function returns the SSID the device is currently connected to.

WiFi.BSSID()
This function returns the MAC address of the router
Syntax:
WiFi.BSSID(bssid)
This function returns the MAC address of the router the device currently
connected to.
WiFi.RSSI()
This function gets the signal strength of the connection to the router
Syntax:
WiFi.RSSI();
WiFi.RSSI(wifiAccessPoint);
The parameter wifiAccessPoint specifies from which network to get the
information and this function returns the current Received Signal Strength in dBm

WiFi.encryptionType()
This function gets the encryption type of the current network.
Syntax
WiFi.encryptionType();
WiFi.encryptionType(wifiAccessPoint);
The parameter wifiAccessPoint specifies which network to get the information
from.
This function returns the byte.
TKIP (WPA) = 2
WEP = 5
CCMP (WPA) = 4
NONE = 7
AUTO = 8

WiFi.ScanNetwork()
This function searches for the number of available WiFi networks and returns the
discovered number.
Syntax
WiFi.ScanNetwork()
This function does not require any parameters and it returns the number of
discovered networks.

WiFi.status()
This function returns the connection status.
Syntax
WiFi.status();
This function returns the following connection status.
WL_CONNECTED : assigned when connected to a WiFi network;
WL_NO_SSID_AVAIL: assigned when the no SSID are available.
WL_SCAN_COMPLETED: assigned when the scanning the networks are
completed
WL_CONNECT_FAILED: assigned when the connection fails for all the
attempts
WL_CONNECTION_LOST: assigned when the connection is lost
WL_DISCONNECTED: assigned when disconnected from a network.

WiFi.getSocket()
This function gets the first socket available
Syntax:
WiFi.getSocket();
This function does not require any parameter and returns the first available socket
in the integer.

WiFi.macAddress()
This function gets the MAC address of the ESP8266 development board.
Syntax
WiFi.macAddress(mac);
The parameter is a 6 byte array to hold the MAC address
This function returns 6 bytes representing the MAC address of the dev kit.

WiFiServer()
This function creates a server that listens for incoming connections on the
specified port.
Syntax
Server(port);
The parameter port is the port to listen to and this function returns nothing.

Server.begin()
This functions tells the server to begin listening for incoming connections.
Syntax
server.begin()
This function does not require any parameters and it will not return anything.

Sever.available()
This function gets a client that is connected to the server and has data available
for reading. The connection persists when the returned client object goes out of
scope.
Syntax
server.available()
This function does not require any parameters. This function returns a client
object. If there is no client available for reading, this function will evaluate to
false in an if-statement that is provided in the program.
Server.write()
This function write data to all the clients connected to a server.
Syntax
server.write(data)
The parameter data is the value to write. (The data format in byte or char)
This function returns number of bytes written.

Server.print()
This function print data to all the clients connected to a server. Prints numbers as
a sequence of digits, each an ASCII character.
Syntax
server.print(data)
server.print(data,BASE)
The parameter data is the data to print (char, byte, int, long or string) and the
parameter BASE is optional. This function will return the number of bytes written

Server.println()
This function works same like server.print , but this function prints all the data in
new line.
Syntax
server.println();

WiFiClient()
This function creates a client that connect to a specified internet IP address and
port.
Syntax
WiFiClient()
This function does not require any parameter.
Client.Connected()
This function help us to know whether the client is connected or not.
Syntax
client.connected()
This function does not require any parameters and this function returns true or
false based on the successful connection with the client.

Client.Connect
This function connect to the IP address and port specified in the constructor. The
return value will indicate success or failure. This function also supports DNS
lookups when using a domain name.
Syntax
client.connect(ip, port)
client.connect(URL, port)
The parameters ip is the IP address that the client will connect to. URL is the
domain name of the client will connect to and the port is the port that the client
will connect to. This function returns true if the connection succeeds, false if the
connection failed.

Client.write()
This function writes data to the server the client has currently connected to.
Syntax:
client.write(data)
The parameter data is the byte or char to write and this function returns the
number of characters written.

Client.print()
This function prints data’s to the server that a client currently connected to.
Syntax
client.print(data)
client.print(data, BASE)
The parameter data is the data to print (char, byte, int, long or string) and the
parameter BASE is optional. This function will return the number of bytes written

Client.available()
This function returns the number of bytes available for reading.
Syntax
client.available()
This function does not require any parameter and the function returns the number
of bytes available.

Client.read()
This function read the next byte received from the server the client is currently
connected to.
Syntax
client.read()
This function does not require any parameters and the function will return a byte
or character.

Client.flush()
This function discard any bytes that have been written to the client but not yet
read.
Syntax
client.flush()
This function does not require any parameters and return none.
Client.stop()
This function disconnects from the server.
Syntax
client.stop()

WiFi.SoftAP
This function setup an access point.
Syntax
WiFi.softAP(ssid)
The above function will setup an open network
WiFi.softAP(ssid, password)
The above function will setup a WPA2-PSK network
The parameters are SSID and password should be provided for this function. If
ssid alone give this will act as an open network.

WiFi.mode
This function will set the operating mode. The ESP8266 can act in 4 different
modes.
Syntax
WiFi.mode(m)
WIFI_OFF – WiFi will be disabled in this mode.
WIFI_STA – In this mode the device will act as a WiFi station.
WIFI_AP – In this mode the device will act as an access point.
WIFI_AP_STA – In this mode the device act as WiFi station as well WiFi access
point.
Control an LED from Browser
Let’s begin the IoT journey with ESP8266 board. Connect an LED to GPIO 13
pin of ESP8266 board and ensure you also using a Resistor value of 470 ohms or
1k ohms with the LED in order to protect the LED as well as the board.
What is the first step for making an IoT device?
The device should have the capability to connect to internet and the device should
connect to Internet and the device should send data or receive data from the
internet. 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.
The ESP8266WebServer class provides the core implementation of an HTTP
server. This is software that responds to browser requests. To use this class we
create an instance of an ESP8266WebServer object specifying the TCP port
number on which it will listen. The default port for browsers is port 80 so this is
a good choice.
Once the object has been created, we define one or more callback functions that
will be invoked when a browser connection is received. The function called on()
is used to register these. These callback functions are keyed on the URL path
requested by the browser. For example, if our ESP8266 is running at IP address
192.168.1.2 and the browser URL is:
http://192.168.1.2/index.html
Connect the LED to D7 pin of Nodemcu and GPIO13 on ESP8266 boards 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.
Arduino IDE program
#include <ESP8266WiFi.h>

const char* ssid = "Magesh"; // change to your wifi name


const char* password = "jayakumar"; // change to your wifi password
int ledPin = 13; // GPIO13
WiFiServer server(80);

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

pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, 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;
}

// 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) {
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("Led pin is now: ");

if(value == HIGH) {
client.print("On");
} else {
client.print("Off");
}
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");
Serial.println("");

Go through the program and try to understand what’s happening the program, it
should be easy to follow and if you have any doubts regarding the code check the
previous chapter on instructions sets for WiFi and Arduino Programming.
Copy the Program to your Arduino IDE and upload to your ESP8266. The
Esp8266 connect to the Wi-Fi router using SSID and password of your Home
network Wifi , where the esp8266 connect to your 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.

Make sure the selected baud


rate matching the baud rate
with the program
If you have different baud rate
in the serial monitor then it will
read garbage value from
ESP8266 board, change the
baud rate and press the restart
button in the ESP8266 board.
Copy the IP address from the serial monitor and paste it into the browser, you
should connect your laptop or PC to the same WiFi system to access the
webserver information from ESP8266 board, if the device you are using to access
ESP8266 connected to a different WiFi service or any other means of internet
connectivity you cannot access the IP address returned from the ESP8266 board.
Home Automation
This chapter is going to be really exciting. "Why?” you ask. You are going to
control the lights, fans, and other electrical appliances, using your mobile phone
or a laptop or whatever the devices which supports browser and WiFi facility.
Materials required for this Project
ESP8266 development board
USB cable
5v Relay (the more the merrier)
Connecting wires
Electrical Lights or LEDs for testing this program.
Using relay to control appliances
Here, we learn what relays are and how they can be used to control everyday
electrical/electronic appliances. Also, to make them useful, we will connect them
to the ESP8266 and create a Blink.ino program, except this time it will be your lamp
that will be turning on and off.
Understanding the basics of the relay
A relay is basically an electrical device, usually consisting of an electromagnet,
which is activated by a passing of current in one circuit to open or close another
circuit. You could think of it as a switch that requires current to turn on or off.
Why can't we simply connect a pin of the ESP8266 to the switchboard, and switch
the fan on or off like we do with an LED? Well, an ESP8266 can output only 2-
3.3V, whereas the fan or any other appliance in your house uses around 200-250V
that comes from the electricity grid. This number is different depending on where
you are from. Also, we cannot simply connect the ESP8266 to the switch of the
fan because that 200-250V will get fed into the ESP8266, which would instantly
burn the chip, or worse.
Since the relay uses an electromagnet to flip a switch inside it, there is no physical
contact between the circuitry of the ESP8266 board and the circuitry of the fan;
hence, it is safe and very effective.
Diving deeper into relay functionality
If you have a good look at the relay (preceding image), you will notice that the
three male header pins on the left are to be connected to the ESP8266 board and
the three screws ‘are to be connected to an electronic appliance.
We need to understand how these two parts work with each other so that we can
program the ESP8266 as we require. The left part will simply be connected to an
Arduino OUTPUT pin, which we can control (turn ON and OFF—HIGH and
LOW) just like an LED. This, in turn, flips a switch on the right side of the relay.
Imagine wires are connected to each of the three screws (right side) of the relay.
This depiction will show how the circuitry will look like on the right side of the
relay comprising of its three pins/screws (ESP8266 LOW → Relay OFF):

When the relay state is 'OFF', the top screw and the middle screw of the relay
form a closed circuit (completed connection), allowing the current to pass through
it. Also, as you guessed it, when the relay state is 'ON', the bottom two screws
will form a closed circuit.

Connect the ground pin to ground pin of ESP8266 and Vcc to Vcc of ESP8266
and connect the signal pin to GPIO 13 or D7 pin of NodeMCU.
Open the Arduino IDE and click on the File and navigate to Examples and choose
basic and then choose Blink from it and upload the program to ESP8266 board.
You can observe the relay working by hearing a “click” sound inside a Relay for
every 1second.
For experimenting this exercise you can you a bulb holder and a 2 pin connector,
cut one of the wire and connect the wire into relay.

A relay has Three Output terminals 1) Normally open , 2) common and 3)


Normally closed. If you connect the two wires between Normally open and
common, whenever the relay gets input from ESP8266 it starts to turn on the
Light or electrical appliances connected with the relay. If you connect between
Normally close and common. Light will always glow and whenever relay gets
input from ESP8266 it turns Off the light or electrical appliances.
For controlling a single Electrical appliance, for this exercise you are going to use
the same program that used for controlling a single LED from a Web browser,
follow the same steps for controlling this electrical appliance instead of the LED.
Now Time to control more devices with an attractive browser instead of basic
HTML tags. 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,
Arduino IDE program for ESP8266 Home Automation
#include <ESP8266WiFi.h>

const char* ssid = "Magesh";// edit your wifi name here


const char* password = "jayakumar54321"; // type your password here

; //
WiFiServer server(80);

void setup() {
Serial.begin(115200);
delay(10);
pinMode(5, OUTPUT);
pinMode(4, OUTPUT);
pinMode(0, OUTPUT);
pinMode(13, OUTPUT);
digitalWrite(5, LOW);
digitalWrite(4, LOW);
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;
}
// 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);

// 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");
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))
{
client.print("<td>Light 1 is ON</td>");

}
else
{
client.print("<td>Light 1 is OFF</td>");

}
client.println("<br />");

if (digitalRead(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))
{
client.print("<td>Light 3 is ON</td>");
}
else
{
client.print("<td>Light 3 is OFF</td>");
}

if (digitalRead(13))
{
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("");
}
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.
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.
We can use a two-way switch instead of a simple switch, because a two-way
switch enables us to control the appliance through the ESP8266 board and the
physical switch independently. This means that you can turn ON a lamp via the
ESP8266, and physically flip the switch to turn it off.
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.
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 D4 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 => after that select
Manage Libraries.
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.
Adding external library to Arduino IDE
Go to sketch in the Arduino ide and select the => include library => after that
select add .zip library and then navigate to the library that you have downloaded
to use with your device.
If you are using 16x2 I2C LCD you can download the library from here, follow
the above step to include library to Arduino IDE.

Connect SCL to GPIO5


Connect SDA to GPIO4
DH11 signal pin to GPIO2
Connect Vcc to 5v
Connect GND to GND

Arduino IDE program for Seeedstudio I2C LCD and ESP8266 board.

#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.. connect D4 pin of
Nodemcu

#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 ");
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' (its 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: ");
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.
}

Arduino IDE program for 16x2 I2C LCD and ESP8266 board.

#include "DHT.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h> // make sure you downloaded the library for I2C
lcd,

LiquidCrystal_I2C lcd (0x20, 16, 2);


#define DHTPIN 2 // what digital pin we're connected to.. connect D4 pin of
Nodemcu

#define DHTTYPE DHT11 // DHT 11


DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
lcd.init();
lcd.backlight();
lcd.print("Temp ");
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' (its 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: ");
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.
}
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.
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 up to
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.
Arduino IDE program for LM35, Open serial monitor in Arduino IDE to know
your current room temperature.
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.

}
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.
Arduino IDE code for LM35 Temperature sensor Webserver.
#include <ESP8266WiFi.h>
const char* ssid = "........"; // edit your wifi name here
const char* password = "........."; // type your password here

float temp =0; // variable to hold temperature data


int analog = 0; // variable to hold analog data
WiFiServer server(80);

void setup() {
Serial.begin(115200);// preapring to use serial communication
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");
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("");
}
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.
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 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
Steps to be followed to upload data to thingspeak.
1. Go to https://thingspeak.com/
2. Log in with your ID and Password.

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.

Arduino IDE code for sending DHT11 sensor data to Thingspeak.com


#include <DHT.h>
#include <ESP8266WiFi.h>

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


String apiKey = "";// paste your api key
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");

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

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

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

Arduino IDE code for sending LM35 sensor data to Thingspeak.com


#include <ESP8266WiFi.h>
// replace with your channel's thingspeak API key,
String apiKey = "........."; // paste your Api key here
const char* ssid = "........"; // type your wifi name
const char* password = "....."; // type your wifi pasword

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


float temp = 0;
int analog = 0;
WiFiClient client;

void setup() {
Serial.begin(115200);
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");


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.
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.
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.
Arduino Ide program for storing DHT11 sensor data into an SD card

#include <SD.h>
#include <SPI.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
}

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...");
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");
}
}
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.
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 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.
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.
Arduino Ide code for ESP8266 SD webserver
/*
SDWebServer - Example WebServer with SD Card backend for esp8266

Copyright (c) 2015 Hristo Gochkov. All rights reserved.


This file is part of the ESP8266WebServer library for Arduino environment.

This library is free software; you can redistribute it and/or


modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Have a FAT Formatted SD Card connected to the SPI port of the ESP8266
The web root is the SD Card root folder
File extensions with more than 3 charecters are not supported by the SD Library
File Names longer than 8 charecters will be truncated by the SD library, so keep
filenames shorter
index.htm is the default index (works on subfolders as well)

Upload the contents of SdRoot to the root of the SDcard and access the editor
by going to http://esp8266sd.local/edit

*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#include <SD.h>
#define DBG_OUTPUT_PORT Serial

const char* ssid = "**********";


const char* password = "**********";
const char* host = "esp8266sd";

ESP8266WebServer server(80);

static bool hasSD = false;


File uploadFile;

void returnOK() {
server.send(200, "text/plain", "");
}

void returnFail(String msg) {


server.send(500, "text/plain", msg + "\r\n");
}

bool loadFromSdCard(String path){


String dataType = "text/plain";
if(path.endsWith("/")) path += "index.htm";

if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf("."));


else if(path.endsWith(".htm")) dataType = "text/html";
else if(path.endsWith(".css")) dataType = "text/css";
else if(path.endsWith(".js")) dataType = "application/javascript";
else if(path.endsWith(".png")) dataType = "image/png";
else if(path.endsWith(".gif")) dataType = "image/gif";
else if(path.endsWith(".jpg")) dataType = "image/jpeg";
else if(path.endsWith(".ico")) dataType = "image/x-icon";
else if(path.endsWith(".xml")) dataType = "text/xml";
else if(path.endsWith(".pdf")) dataType = "application/pdf";
else if(path.endsWith(".zip")) dataType = "application/zip";

File dataFile = SD.open(path.c_str());


if(dataFile.isDirectory()){
path += "/index.htm";
dataType = "text/html";
dataFile = SD.open(path.c_str());
}

if (!dataFile)
return false;

if (server.hasArg("download")) dataType = "application/octet-stream";

if (server.streamFile(dataFile, dataType) != dataFile.size()) {


DBG_OUTPUT_PORT.println("Sent less data than expected!");
}

dataFile.close();
return true;
}

void handleFileUpload(){
if(server.uri() != "/edit") return;
HTTPUpload& upload = server.upload();
if(upload.status == UPLOAD_FILE_START){
if(SD.exists((char *)upload.filename.c_str())) SD.remove((char
*)upload.filename.c_str());
uploadFile = SD.open(upload.filename.c_str(), FILE_WRITE);
DBG_OUTPUT_PORT.print("Upload: START, filename: ");
DBG_OUTPUT_PORT.println(upload.filename);
} else if(upload.status == UPLOAD_FILE_WRITE){
if(uploadFile) uploadFile.write(upload.buf, upload.currentSize);
DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: ");
DBG_OUTPUT_PORT.println(upload.currentSize);
} else if(upload.status == UPLOAD_FILE_END){
if(uploadFile) uploadFile.close();
DBG_OUTPUT_PORT.print("Upload: END, Size: ");
DBG_OUTPUT_PORT.println(upload.totalSize);
}
}

void deleteRecursive(String path){


File file = SD.open((char *)path.c_str());
if(!file.isDirectory()){
file.close();
SD.remove((char *)path.c_str());
return;
}

file.rewindDirectory();
while(true) {
File entry = file.openNextFile();
if (!entry) break;
String entryPath = path + "/" +entry.name();
if(entry.isDirectory()){
entry.close();
deleteRecursive(entryPath);
} else {
entry.close();
SD.remove((char *)entryPath.c_str());
}
yield();
}

SD.rmdir((char *)path.c_str());
file.close();
}

void handleDelete(){
if(server.args() == 0) return returnFail("BAD ARGS");
String path = server.arg(0);
if(path == "/" || !SD.exists((char *)path.c_str())) {
returnFail("BAD PATH");
return;
}
deleteRecursive(path);
returnOK();
}

void handleCreate(){
if(server.args() == 0) return returnFail("BAD ARGS");
String path = server.arg(0);
if(path == "/" || SD.exists((char *)path.c_str())) {
returnFail("BAD PATH");
return;
}

if(path.indexOf('.') > 0){


File file = SD.open((char *)path.c_str(), FILE_WRITE);
if(file){
file.write((const char *)0);
file.close();
}
} else {
SD.mkdir((char *)path.c_str());
}
returnOK();
}

void printDirectory() {
if(!server.hasArg("dir")) return returnFail("BAD ARGS");
String path = server.arg("dir");
if(path != "/" && !SD.exists((char *)path.c_str())) return returnFail("BAD
PATH");
File dir = SD.open((char *)path.c_str());
path = String();
if(!dir.isDirectory()){
dir.close();
return returnFail("NOT DIR");
}
dir.rewindDirectory();
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.send(200, "text/json", "");
WiFiClient client = server.client();

server.sendContent("[");
for (int cnt = 0; true; ++cnt) {
File entry = dir.openNextFile();
if (!entry)
break;

String output;
if (cnt > 0)
output = ',';

output += "{\"type\":\"";
output += (entry.isDirectory()) ? "dir" : "file";
output += "\",\"name\":\"";
output += entry.name();
output += "\"";
output += "}";
server.sendContent(output);
entry.close();
}
server.sendContent("]");
dir.close();
}

void handleNotFound(){
if(hasSD && loadFromSdCard(server.uri())) return;
String message = "SDCARD Not Detected\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " NAME:"+server.argName(i) + "\n VALUE:" + server.arg(i) +
"\n";
}
server.send(404, "text/plain", message);
DBG_OUTPUT_PORT.print(message);
}

void setup(void){
DBG_OUTPUT_PORT.begin(115200);
DBG_OUTPUT_PORT.setDebugOutput(true);
DBG_OUTPUT_PORT.print("\n");
WiFi.begin(ssid, password);
DBG_OUTPUT_PORT.print("Connecting to ");
DBG_OUTPUT_PORT.println(ssid);

// Wait for connection


uint8_t i = 0;
while (WiFi.status() != WL_CONNECTED && i++ < 20) {//wait 10 seconds
delay(500);
}
if(i == 21){
DBG_OUTPUT_PORT.print("Could not connect to");
DBG_OUTPUT_PORT.println(ssid);
while(1) delay(500);
}
DBG_OUTPUT_PORT.print("Connected! IP address: ");
DBG_OUTPUT_PORT.println(WiFi.localIP());

if (MDNS.begin(host)) {
MDNS.addService("http", "tcp", 80);
DBG_OUTPUT_PORT.println("MDNS responder started");
DBG_OUTPUT_PORT.print("You can now connect to http://");
DBG_OUTPUT_PORT.print(host);
DBG_OUTPUT_PORT.println(".local");
}
server.on("/list", HTTP_GET, printDirectory);
server.on("/edit", HTTP_DELETE, handleDelete);
server.on("/edit", HTTP_PUT, handleCreate);
server.on("/edit", HTTP_POST, [](){ returnOK(); }, handleFileUpload);
server.onNotFound(handleNotFound);

server.begin();
DBG_OUTPUT_PORT.println("HTTP server started");

if (SD.begin(SS)){
DBG_OUTPUT_PORT.println("SD Card initialized.");
hasSD = true;
}
}

void loop(void){
server.handleClient();
}
This file is located in the ESP8266 examples under webserver.
Scan the Wi-Fi network surrounded by
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 extract the files to
Arduino Library.
Components you need to make this projects 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.
Arduino IDE program for TFT LCD screen
/*
* This sketch demonstrates how to scan WiFi networks.
* The API is almost the same as with the WiFi Shield library,
* the most obvious difference being the different file you need to include:
*/
#include "ESP8266WiFi.h"
#include "SPI.h"

// Original Adafruit lib

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

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( " : ");
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,

Note: Make sure you are using the library provided with this book, if you use
unmodified version TFT library it will not work.
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.
Connect the circuit as shown in the below 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 add the library to Arduino libraries.
Arduino IDE program ESP8266 clock
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <time.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);

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


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

/* Don't hardwire the IP address or we won't get the benefits of the pool.
* Lookup the IP address for the host name instead */
static const char ntpServerName[] = "time.nist.gov";
static const char tzName[] = " UTC";
static const int timeZone = 0; // UTC
//static const int timeZone = -5; // Eastern Standard Time (USA)
//static const int timeZone = -4; // Eastern Daylight Time (USA)
//static const int timeZone = -8; // Pacific Standard Time (USA)
//static const int timeZone = -7; // Pacific Daylight Time (USA)

WiFiUDP Udp;
uint16_t localPort; // local port to listen for UDP packets

void setup()
{
Serial.begin(115200);
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.println(F("ESP8266 NTP clock on PCD8544 LCD display"));


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

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


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

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


Serial.println(WiFi.localIP());

// Seed random with values unique to this device


uint8_t macAddr[6];
WiFi.macAddress(macAddr);
uint32_t seed1 =
(macAddr[5] << 24) | (macAddr[4] << 16) |
(macAddr[3] << 8) | macAddr[2];
randomSeed(WiFi.localIP() + seed1 + micros());
localPort = random(1024, 65535);

Serial.println(F("Starting UDP"));
Udp.begin(localPort);
Serial.print(F("Local port: "));
Serial.println(Udp.localPort());
Serial.println(F("waiting for sync"));
setSyncProvider(getNtpTime);
setSyncInterval(5 * 60);

void loop()
{
static time_t prevDisplay = 0; // when the digital clock was displayed
timeStatus_t ts = timeStatus();

switch (ts) {
case timeNeedsSync:
case timeSet:
if (now() != prevDisplay) { //update the display only if time has changed
prevDisplay = now();
digitalClockDisplay();
if (ts == timeNeedsSync) {
Serial.println(F("time needs sync"));
}
}
break;
case timeNotSet:
Serial.println(F("Time not set"));
now();
break;
default:
break;
}
}

const uint8_t SKINNY_COLON[] PROGMEM = {


B00000000,
B00000000,
B01100000,
B11110000,
B11110000,
B01100000,
B00000000,
B00000000,
B01100000,
B11110000,
B11110000,
B01100000,
B00000000,
B00000000,
};

void digitalClockDisplay() {
tmElements_t tm;
char *dayOfWeek;

breakTime(now(), tm);
dayOfWeek = dayShortStr(tm.Wday);
// digital clock display of the time
Serial.printf("%s %02d %02d %04d %02d:%02d:%02d\r\n",
dayOfWeek, tm.Month, tm.Day, tm.Year + 1970,
tm.Hour, tm.Minute, tm.Second);

tft.clearDisplay();
tft.setTextSize(1);
tft.printf("%s %02d %02d %04d\n",
dayOfWeek, tm.Month, tm.Day, tm.Year + 1970);
tft.setTextSize(2);
tft.setCursor(0, 16);
tft.printf("%02d", tm.Hour);
tft.drawBitmap(24, 16, SKINNY_COLON, 4, 14, 1);
tft.setCursor(30, 16);
tft.printf("%02d", tm.Minute);
tft.drawBitmap(54, 16, SKINNY_COLON, 4, 14, 1);
tft.setCursor(60, 16);
tft.printf("%02d", tm.Second);

tft.setCursor(0, 32);
tft.print(tzName);
tft.display();
}

/*-------- 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()
{
IPAddress timeServerIP; // time.nist.gov NTP server address

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


Serial.print(F("Transmit NTP Request "));
//get a random server from the pool
WiFi.hostByName(ntpServerName, timeServerIP);
Serial.println(timeServerIP);
sendNTPpacket(timeServerIP);
uint32_t beginWait = millis();
while ((millis() - beginWait) < 1500) {
int size = Udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
Serial.println(F("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
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 * SECS_PER_HOUR);
}
}
Serial.println(F("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;
// 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
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.
Make sure you have downloaded the barometric and pressure sensor library
before uploading this code to your Nodemcu.

Arduino IDE program for ESP8266 Widget


/*
* 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 <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[] = "Magesh"; // your network SSID (name)


const char pass[] = "jayakumar54321"; // 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;
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());
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");

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());}
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(".");
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
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;
// 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();
}
ESP8266 Internet of Things with
Ubidots

Step 1: download the library for ubidots from here


https://github.com/ubidots/ubidots-nodemcu/archive/master.zip
Step 2: Go to sketch in the Arduino ide and select the => include library => after
that select add .zip library and then navigate to the library that you have
downloaded to use with your device.
Step 3: Restart Arduino IDE

Go to ubidots.com and sign up for an account.


In this tutorial, you are going to send Temperature and Humidity data to the web,
for that we need two things in place: a place that we can access and store the data,
and a way to communicate with it.
After creating the account we’re ready to setup the data source that will provide
the API to publish our data.
Step 1:
Click on the sources from the Top navigation Menu

Step 2:
Click add data source and rename it to weather station or whatever you would
like to name it.
Step 3: click on the newly created data source name to go onto the next screen.

Click on the
add variable
and choose
default and
name the new
variable as
Humidity.
Likewise add another variable and name it as Temperature.

Click on the icon next to delete button at the top of the Humidity board and copy
it to a notepad later on this id will be pasted in Arduino Ide. Copy both Humidity
and Temperature ID.
Click on your Profile at the top right and choose API credentials.

Copy the Tokens from after clicking API credentials by clicking on your profile.
Connect the circuit as shown in the above figure, for accurate temperature reading
please use a 1k ohm resistor between signal and voltage, as this sensors are
manufactured for working with a 5v device, it is necessary to use a resistor to get
accurate reading. If you don’t use any resistor still you will get the humidity and
temperature reading and there will be a slight variation from the actual and sensor
reading.
Instead of DHT22 sensor you can also use DHT11 sensor circuit diagram is same
for DHT11 sensor, refer the previous tutorials on sending data to Thingspeak.com
where we used DHT11 sensor for sending Temperature and Humidity data’s. You
have to uncomment DHT11 and comment on DHT22 in the program.
Make sure you have downloaded library for DHT sensor, if you haven’t installed
the library yet, download library from Manage library in the Arduino IDE.
Arduino IDE program for Sending Humidity and Temperature data to Ubidots
#include "DHT.h"
#include "UbidotsMicroESP8266.h"
#define ID "57412ca9762542026bd9f45a" // Ubidots Humidity variable ID
#define ID2 "57412cd076254203fb2fc965"// Ubidots Temp Variable ID
#define TOKEN "sUmMZnxUoD28NhALxJtnTNcH8GXYGk" // Put here your
Ubidots TOKEN
#define WIFISSID "Magesh" // Change this for your WiFi User
#define PASSWORD "jayakumar" // Change this for your WiFi pass

#define DHTPIN 2 // what digital pin we're connected to

// Uncomment whatever type you're using!


//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)

Ubidots client(TOKEN);

DHT dht(DHTPIN, DHTTYPE);


void setup(){
Serial.begin(115200);
delay(10);
Serial.println("DHTxx test!");
dht.begin();
client.wifiConnection(WIFISSID, PASSWORD);
}
void loop(){
delay(2000);
// 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();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);

// 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;
}
client.add(ID, h);
client.add(ID2, t);
client.sendAll();

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.println("Heat index: ");
delay(100);
}

Copy and paste the program into Arduino IDE and change the variable ID’s for
Temperature and Humidity and also Token ID. After uploading the program to
your ESP8266 board, open the serial monitor to know the device getting
communication with your WiFi and also sending data’s to Ubidots.
Login into ubidots to check your Humidity and Temperature Sensor data’s.

Click on the variable to expand and get more detail view of the sensor data.
Creating widgets in Ubidots

Click on the dashboard.


Click on the plus (+) sign on the top right side of the website.
Click on the indicator icon.

Select the Widget type, choose the Gauge from the Widget in this step.

Select the Data source, for this choose the data source we created for Temperature
and Humidity that is weather station which holds the temperature and humidity
variables.
First choose the Humidity, later on follow the same steps for creating a widget
for Temperature.

If you know the maximum range of your senor, provide the minimum and
maximum value in this step.

That’s the end you will have a widget to indicate humidity in the gauge, if you
want different visualization to see your data you can choose different indicator
and type in the widget menu. Follow the same step for creating a widget for
temperature.
Control an LED from Ubidots.
In this tutorial you are going to control an LED from Ubidots by creating a widget
on the ubidots site. This will not be a real-time control, there will be a time delay
on switching the LED from On state to Off state.
Step 1:
Click on the sources from the Top navigation Menu

Step 2:
Click add data source and rename it to LED control or whatever you would like
to name it.

Step 3: click on the newly created data source name to go onto the next screen.
Click on the
add variable
and choose
default and
name the new
variable as
LED.
Creating widgets in Ubidots

Click on the dashboard.


Click on the plus (+) sign on the top right side of the website.

Click on the control icon

Select switch from the widget.

Select LED control as the data source. If you named it as different data source
choose that name.
Select the Variable to control.

Leave the default message.


You have successfully created a widget on your Ubidots dashboard for
controlling and LED. Connect the LED to your ESP8266 board as shown in the
figure.
Go to your LED control variable and copy the variable ID and replace the ID in
your Arduino program.
Click on your Profile at the top right and choose API credentials.

Copy the Tokens from after clicking API credentials by clicking on your profile

Arduino IDE program for controlling an LED from Ubidots.


#include "UbidotsMicroESP8266.h"
#define ID "57413bc5762542142d227e33" // Put here your Ubidots variable ID
#define TOKEN "sUmMZnxUoD28NhALxJtnTNcH8GXYGk" // Put here your
Ubidots TOKEN
#define WIFISSID "Magesh" // Change this for your WiFi User
#define PASSWORD "jayakumar" // Change this for your WiFi pass
Ubidots client(TOKEN);
void setup() {
Serial.begin(115200);
pinMode(13,OUTPUT);
digitalWrite(13,LOW);
delay(10);
client.wifiConnection(WIFISSID, PASSWORD);
}

void loop() {
float value = client.getValue(ID);
Serial.println(value);

if (value == 0){
digitalWrite(13,HIGH);
}
else{
digitalWrite(13,LOW);
}
}
Copy paste the above program into your Arduino Ide and upload it into your
ESP8266 board. After successfully upload the program go to ubidots and change
the state of the switch that you created and notice the change in your LED
connected to ESP8266, it is not a real-time control it will take some time to update
from the website so please be patient to observe the result don’t hit restart or
switch off the ESP8266 if you are not getting any immediate results.
Security alerts creating by events in
Ubidots
Follow the previous tutorials if you have any doubts on creating a source in
ubidots.
Create a Data source and name it as security.

Click on the variable select default and name it as gas detection

Click on the events at the top right of your ubidots account.


Click on the add event (+) symbol

Choose security as the data source

Choose gas detection as variable


Click greater than symbol and type 0 in the box and click on continue for the next
step.

In the next step select send SMS

Type your Phone number and Message that you want to receive your ESP8266
detects LPG, don’t forget to select country code.

Leave the final steps as it is and click on the finish button to create an event for
sending SMS when there is a gas leakage at your Home or office or wherever you
installed the ESP8266 device. You can also subscribe to other services like email,
as a free user you can only receive up to 5 SMS per month in Ubidots.

You can use any gas


sensor module, this
project has used an Mq-
2 gas sensor module,
and this sensor has both
Analog and digital
output.
Connect Vcc to 5v
Connect Gnd to Gnd
Connect Dout to GPIO2
or “D4”.
Arduino IDE program for GAS leakage and sending an SMS to your
Mobile.

#include "UbidotsMicroESP8266.h"
#define ID "5741c273762542367eed3af4" // Put here your Ubidots variable ID
#define TOKEN "sUmMZnxUoD28NhALxJtnTNcH8GXYGk" // Put here
your Ubidots TOKEN
#define WIFISSID "Magesh" // Change this for your WiFi User
#define PASSWORD "jayakumar" // Change this for your WiFi pass
Ubidots client(TOKEN);
void setup(){
Serial.begin(115200);
pinMode(2, INPUT);
delay(10);
client.wifiConnection(WIFISSID, PASSWORD);
}
void loop(){
int security = digitalRead(2);
client.add(ID, security);
client.sendAll();
delay(15000);
}
Don’t forget to change WiFi SSID and Password in the above program. Make
sure you also using your Token ID in order to send the data to Ubidots.
Intruder alert using PIR sensor
Following the same program and same procedure for the gas sensor, just by
replacing the sensor this project can identify intruder and act as a security guard.
Fire Alarm detector using Flame sensor.
Following the same program and same procedure for the gas sensor, just by
replacing the sensor this project can identify intruder and act as a fire detector.

This is a flame
detection sensor, it
can be used for
detecting fire.
These sensor are
available in many
hobbyist and online
shops, make sure to
connect Dout pin to
GPIO2 pin of
ESP8266.
Over the Air (OTA)
For uploading over the air need to install python version 2.7xx, if you have any
other version this will not work, for successful operation of this work you need
python to be installed in your system. It can be downloaded from this link
https://www.python.org/downloads/.

Click on the downloaded python package to start installation process.


Click on the Add python.exe to path and click will be installed on local hard drive.

Once the installation process gets complete restart your PC or laptop for
successful completion of the installation process.
Open Arduino IDE
First the ESP8266 boards need to Upload OTA sketch via USB serial, for that
ESP8266 board needs to connect with PC or Laptop and upload the BasicOTA
sketch from example menu. After uploading the sketch, open serial monitor and
check if the ESP8266 module has joined to your WiFi network.
Edit SSID and Password before you uploading your sketch to ESP8266 board.

If the ESP8266 connected to WiFi network, open the Tools and check the port
and you can find ESP8266-ota port will show up in Arduino IDE. Select port with
IP address shown in Serial Monitor.
If the port does not shows up restart your Arduino IDE and this will solve the
problem mostly.
Select the Network ports and upload the BasicOTA sketch over the network
instead of connecting USB now it is possible to program the ESP8266 over the
Air. Make sure you include OTA routines in your sketch for uploading sketch
over the air.
ESP8266 as Access Point Webserver
Still now you have used ESP8266 to connect to your WiFi router and act as
webserver. ESP8266 can also support Access Point Mode.
Connect LEDs to the all the GPIO pins of ESP8266
#include <ESP8266WiFi.h>

//////////////////////
// WiFi Definitions //
//////////////////////
const char WiFiAPPSK[] = "esp82666"; //wifi password should be 8 characters
long. that's the reason added extra 6 to it.

/////////////////////
/////////////////////

WiFiServer server(80);

void setup()
{
initHardware();
setupWiFi();
server.begin();
}

void loop()
{
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();

// Match the request


int val = -1; // We'll use 'val' to keep track of both the
// request type (read/set) and value if set.
if (req.indexOf("/led/0") != -1)
digitalWrite(16, LOW);
else if (req.indexOf("/led/1") != -1)
digitalWrite(16, HIGH);
else if (req.indexOf("/led/2") != -1)
digitalWrite(5, HIGH);
else if (req.indexOf("/led/3") != -1)
digitalWrite(5, LOW);
else if (req.indexOf("/led/4") != -1)
digitalWrite(4, HIGH);
else if (req.indexOf("/led/5") != -1)
digitalWrite(4, LOW);
else if (req.indexOf("/led/6") != -1)
digitalWrite(0, HIGH);
else if (req.indexOf("/led/7") != -1)
digitalWrite(0, LOW);
else if (req.indexOf("/led/8") != -1)
digitalWrite(2, HIGH);
else if (req.indexOf("/led/9") != -1)
digitalWrite(2, LOW);
else if (req.indexOf("/led2/1") != -1)
digitalWrite(14, HIGH);
else if (req.indexOf("/led2/2") != -1)
digitalWrite(14, LOW);
else if (req.indexOf("/led2/3") != -1)
digitalWrite(12, HIGH);
else if (req.indexOf("/led2/4") != -1)
digitalWrite(12, LOW);
else if (req.indexOf("/led2/5") != -1)
digitalWrite(13, HIGH);
else if (req.indexOf("/led2/6") != -1)
digitalWrite(13, LOW);
else if (req.indexOf("/led2/7") != -1)
digitalWrite(15, HIGH);
else if (req.indexOf("/led2/8") != -1)
digitalWrite(15, LOW);

client.flush();
// Prepare the response. Start with the common header:
String s = "HTTP/1.1 200 OK\r\n";
s += "Content-Type: text/html\r\n\r\n";
s += "<!DOCTYPE HTML>\r\n<html>\r\n";
s += "Type or copy paste below codes on to your browser to turn on and off
an lED .";
s += "<br><br>";
s += "Type http://192.168.4.1/led/1 to turn on first led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led/0 to turn off first led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led/2 to turn on second led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led/3 to turn off seond led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led/4 to turn on third led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led/5 to turn off third led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led/6 to turn on fourth led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led/7 to turn off fourth led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led/8 to turn on fifth led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led/9 to turn off fifth led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led2/1 to turn on sixth led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led2/2 to turn off sixth led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led2/3 to turn on seventh led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led2/4 to turn off seventh led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led2/5 to turn on Eighth led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led2/6 to turn off Eighth led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led2/7 to turn on Ninth led. ";
s += "<br><br>";
s += "Type http://192.168.4.1/led2/8 to turn off Ninth led. ";
s += "<br><br>";
s += "</html>\n";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");

// The client will actually be disconnected


// when the function returns and 'client' object is detroyed
}
void setupWiFi()
{
WiFi.mode(WIFI_AP);
// Do a little work to get a unique-ish name. Append the
// last two bytes of the MAC (HEX'd) to "Thing-":
uint8_t mac[WL_MAC_ADDR_LENGTH];
WiFi.softAPmacAddress(mac);
String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) +
String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
macID.toUpperCase();
String AP_NameString = "ESP8266 Thing " + macID;
char AP_NameChar[AP_NameString.length() + 1];
memset(AP_NameChar, 0, AP_NameString.length() + 1);

for (int i=0; i<AP_NameString.length(); i++)


AP_NameChar[i] = AP_NameString.charAt(i);
WiFi.softAP(AP_NameChar, WiFiAPPSK);
}
void initHardware()
{
Serial.begin(115200);
pinMode(16, OUTPUT);
pinMode(5, OUTPUT);
pinMode(4, OUTPUT);
pinMode(0, OUTPUT);
pinMode(2, OUTPUT);
pinMode(14, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
pinMode(15, OUTPUT);
digitalWrite(16, LOW);
digitalWrite(5,LOW);
digitalWrite(4,LOW);
digitalWrite(0,LOW);
digitalWrite(2,LOW);
digitalWrite(14,LOW);
digitalWrite(12,LOW);
digitalWrite(13,LOW);
digitalWrite(15,LOW);
}
Copy and paste the above code in your Arduino IDE and upload to your ESP8266
device.
If you have any device that supports Wi-Fi and browser than this example will
work in that device without any problem.
Connect your Laptop Wi-Fi to ESP8266 Wi-Fi , you can refer to the attached
screen below to know ESP8266 device Wi-Fi name. Connect to the device with
the password esp82666, remember it has 666 the reason for that the device need
8 digit password.
After connecting your Wi-Fi to ESP8266 open your browser and type 192.168.4.1

Type the URL into address bar of your browser and see the changes in your
ESP8266 board. LEDs will turn on and off according to the commands you’re
typing in your browser address bar.
Connecting it your Android mobile.

Open your Android device Wi-Fi and connect it to ESP8266 Thing


The password for this device is esp82666
Install the ESP8266.apk app that you can find Codes folder that you can
download from the link given at the end of this book. If your mobile not allows
you to install apps from unknown source go to your security setting and allow
your android device to install apps from unknown source.

The app is very easy to use and it can use with any ESP8266 device, it was not
designed only for Nodemcu. This app was developed using MIT app inventor.
MIT app inventor block code for ESP8266 app.
MQTT
MQTT (formerly MQ Telemetry Transport) is an ISO standard (ISO/IEC PRF
20922) publish-subscribe based "light weight" messaging protocol for use on top
of the TCP/IP protocol. It is designed for connections with remote locations
where a "small code footprint" is required or the network bandwidth is limited.
The publish-subscribe messaging pattern requires a message broker. The broker is
responsible for distributing messages to interested clients based on the topic of a
message. Andy Stanford-Clark and Arlen Nipper of Cirrus Link
Solutions authored the first version of the protocol in 1999.
“A light weight event and message oriented protocol allowing devices to
asynchronously communicate efficiently across constrained networks to remote
systems”

Why not use HTTP?


Http is the protocol we used since 1991 in the web, widely known and adapted it
has request/response paradigm, and it also need point to point connection. It quite
robust, http is often too verbose, not suited for Internet of Things.
The HTTP standard revolutionized how people consume data. It is a single simple
model which send a request and read the response. It is available in tablet, laptop,
phone, PC etc. HTTP remains ideal for requesting data from a known source.
Characteristics of Internet Of Things
 Constrained resources
 Unreliable network connection
 Low cost for hardware and data plan
 No power – only battery
 No home base (out-in-the-field)

The Internet of Things has fundamentally different challenges


 Slim and lightweight protocols
 Bidirectional communication
 Little overhead
 Not to think about duplicates
 Not to care about different data consumers
 Emitting information one to many
 Listening for events whenever they happen
 Distributing minimal packets of data in huge volumes
 Pushing information over unreliable networks.
MQTT - Publish Subscribe Messaging

In the case of MQTT, there is a broker, and there are clients. The broker is the
“Post Office”, or in computer terms, the “server.”
Clients can publish (Pub) messages, or send letters, to the post office. Other
clients can subscribe (Sub) to topics, or receive letters, from the post office.
Moreover, clients can both publish and subscribe.
Publish Subscribe messaging protocol allowing a message to be published once
and multiple consumers (applications / devices) to receive the message providing
decoupling between the producer and consumer(s)
A producer sends (publishes) a message (publication) on a topic (subject)
A consumer subscribes (makes a subscription) for messages on a topic (subject)
A message server / broker matches publications to subscriptions
•If no matches the message is discarded
•If one or more matches the message is delivered to each matching
subscriber/consumer

A topic forms the namespace it is hierarchical with each “sub topic” separated by
a/
• A house publishes information about itself on
Country/region/town/postcode/house/energyconsumption
Country/region/town/postcode/house/solarenergy
Country/region/town/postcode/house/alarmstat
Country/region/town/postcode/house/temperature
Topic level separator is the “/ “

A subscriber can subscribe to an absolute topic or can use wildcards


Single-level wildcards “+” can appear anywhere in the topic string
Multi-level wildcards “#” must appear at the end of the string
Wildcards must be next to a separator
Cannot use wildcards when publishing
A subscription can be durable or non-durable
Durable:
Once a subscription is in place a broker will forward matching messages
to the subscriber, it will forward if the message immediately if the subscriber is
connected and if the subscriber is not connected messages are stored on the
server/broker until the next time the subscriber connects.
Non-durable subscription: The subscription lifetime is the same as the time the
subscriber is connected to the server/broker.
Mqtt provides multiple deterministic message delivery qualities of service
0 – message delivered at most once.
1 – Message will be delivered but may be duplicated
2 – One and once only delivery
Quality of service is maintained over fragile network even if connection breaks.

Mqtt with adafruit.io


Step 1: download Mqtt library for adafruit from Arduino Library Manager.

Create an account on io.adafruit.com


Open the ESP8266 example sketch from adafruit Mqtt examples. Upload the
sketch to your ESP8266 device and open the serial monitor for checking the
connection between your device and io.adafruit.com

When you open the account in io.adafruit.com, you can see a On and Off button
and a gauge. Follow the step by step Mqtt setup by adafruit here
Sending DHT22 Humidity and Temperature sensor data to adafruit.io
Arduino IDE program for sending sensor data to io.adafruit.
/***************************************************
Modified code for DHT22 Temp and Humidity Sensor.
Originally Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/

// Libraries
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include "DHT.h"

// DHT 22 sensor
#define DHTPIN 2 // DHT pin connect to GPIO2
#define DHTTYPE DHT22 // DHT sensor type

// WiFi parameters
#define WLAN_SSID "Magesh" // change this to your SSID
#define WLAN_PASS "jayakumar" // change this to your password

// Adafruit IO
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "Magesh" // change this to your adafruit username
#define AIO_KEY "514ad7fb1004409daf" // change this to your AIO_KEY
// DHT sensor
DHT dht(DHTPIN, DHTTYPE, 15);

// Functions
void connect();

// Create an ESP8266 WiFiClient class to connect to the MQTT server.


WiFiClient client;

// Store the MQTT server, client ID, username, and password in flash memory.
const char MQTT_SERVER[] PROGMEM = AIO_SERVER;

// Set a unique MQTT client ID using the AIO key + the date and time the sketch
// was compiled (so this should be unique across multiple devices for a user,
// alternatively you can manually set this to a GUID or other random value).
const char MQTT_CLIENTID[] PROGMEM = AIO_KEY __DATE__
__TIME__;
const char MQTT_USERNAME[] PROGMEM = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM = AIO_KEY;

// Setup the MQTT client class by passing in the WiFi client and MQTT server
and login details.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT,
MQTT_CLIENTID, MQTT_USERNAME,
MQTT_PASSWORD);/****************************** Feeds
***************************************/

// Setup feeds for temperature & humidity


const char TEMPERATURE_FEED[] PROGMEM = AIO_USERNAME
"/feeds/temperature";
Adafruit_MQTT_Publish temperature = Adafruit_MQTT_Publish(&mqtt,
TEMPERATURE_FEED);

const char HUMIDITY_FEED[] PROGMEM = AIO_USERNAME


"/feeds/humidity";
Adafruit_MQTT_Publish humidity = Adafruit_MQTT_Publish(&mqtt,
HUMIDITY_FEED);

/*************************** Sketch Code


************************************/

void setup() {

// Init sensor
dht.begin();

Serial.begin(115200);
Serial.println(F("Adafruit IO Example"));

// Connect to WiFi access point.


Serial.println(); Serial.println();
delay(10);
Serial.print(F("Connecting to "));
Serial.println(WLAN_SSID);

WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
}
Serial.println();

Serial.println(F("WiFi connected"));
Serial.println(F("IP address: "));
Serial.println(WiFi.localIP());

// connect to adafruit io
connect();

void loop() {

// ping adafruit io a few times to make sure we remain connected


if(! mqtt.ping(3)) {
// reconnect to adafruit io
if(! mqtt.connected())
connect();
}

// Grab the current state of the sensor


int humidity_data = (int)dht.readHumidity();
int temperature_data = (int)dht.readTemperature();
// Publish data
if (! temperature.publish(temperature_data))
Serial.println(F("Failed to publish temperature"));
else
Serial.println(F("Temperature published!"));

if (! humidity.publish(humidity_data))
Serial.println(F("Failed to publish humidity"));
else
Serial.println(F("Humidity published!"));

// Repeat every 10 seconds


delay(10000);

// connect to adafruit io via MQTT


void connect() {

Serial.print(F("Connecting to Adafruit IO... "));

int8_t ret;

while ((ret = mqtt.connect()) != 0) {

switch (ret) {
case 1: Serial.println(F("Wrong protocol")); break;
case 2: Serial.println(F("ID rejected")); break;
case 3: Serial.println(F("Server unavail")); break;
case 4: Serial.println(F("Bad user/pass")); break;
case 5: Serial.println(F("Not authed")); break;
case 6: Serial.println(F("Failed to subscribe")); break;
default: Serial.println(F("Connection failed")); break;
}

if(ret >= 0)
mqtt.disconnect();

Serial.println(F("Retrying connection..."));
delay(5000);

Serial.println(F("Adafruit IO Connected!"));

Login to io.adafruit.com

Click on the plus sign to create a new block.


Click on the create button near the gauge.
Type temperature and click create.
Choose temperature and click the Next STEP

Type the Min and Max Gauge value and click create block button.

Continue the same for Humidity block, follow the same procedure with name as
humidity create another gauge block for indicating humidity sensor data.
Click on the key to get your AIO key

Update your AIO key, AIO username, SSID and password of your WiFi router
and upload the program to ESP8266 and visualize the data in Adafruit.io
Getting Started with Lua

Flashing ESP8266 or Nodemcu with


latest lua firmware
Step 1: open your web browser and type https://github.com/nodemcu/nodemcu-
firmware/releases or click on the link.

Step 2: Click on the firmware links to download, download both the firmware
wire.

Step 3: download lua IDE from the link here , for this tutorial we going to use
ESPlorer one of the stable version for uploading lua files to ESP8266 chips, there
are other lua loaders available which are limited to windows or still in
development, as the ESPlorer is not a great IDE but it is most suitable for learning
lua programming with ESP8266 devices.
Step 4: Extract the Nodemcu Flasher which downloaded in the first step, if you
have yet to download, download it first before proceeding with this tutorial.
Step 5: Connect your Nodemcu or ESP8266 to your laptop or PC, if you are using
a generic ESP8266 device you need to connected with FTDI USB to serial adapter
or any other USB to serial adapter devices, if you are a beginner it is not advisable
to use a generic module as it may frustrate some beginner if they want to quick
start with this device.
Step 6: Open the extracted nodemcu-flasher-master file and select Win64 or
Win32 based on your system configuration, I use windows x64, and I choose the
folder Win64, open ESP8266 Flasher.

Click on Config and click on the gear, and navigate to the bin file (lua latest
firmware) that you downloaded in the step 2,
In the step 2, we have downloaded 2 firmware one is float and another one is
integer, select the second one integer type and click open.
These two firmware should flash to the ESP8266 based on requirement , if you
use Float firmware DHT library will not work with ESP8266 device, that’s the
reason we are choosing the integer type later on tutorials we will use the device
with DHT sensor and read temperature and humidity data.
Check on the Config tab, correct firmware has selected or not, if the firmware
path is correct it will display in green color else the color would turn to red.
On the advance tab restore it to default and don’t change it unnecessary
Step 7: Click on the Operation tab and select the correct COM port, if you have
connected only one device it will automatically detect the COM port if there are
any devices connected to your computer make sure to select the correct COM
port, if you are not sure about which COM port your device is currently
connected, right click on the My computer icon and select properties, choose
device manager and click on ports, it will display the available or currently
connected devices to your computer.

Click on Flash in the Operation tab, after you make sure that you selected correct
COM port in the ESP8266 flasher.
Once you hit the flash button in the Operation tab your ESP8266 Flasher will start
to upload the firmware to your Nodemcu device, you see this by checking the
progress bar in your ESP8266 Flasher screen.

Click on the log file and make sure you have successfully uploaded the firmware,
and you can also see a green color check arrow to indicate the successful upload
of the firmware, if there is a problem when uploading the firmware check the log
file and check the reason for uploading failed, mostly this problem occurs when
the ESP8266 device not responding when uploading firmware you can disconnect
and reconnect the device and try to upload the firmware again, if still the problem
continues check your device as it may have fault. If you are using generic type
and getting problem when you upload your firmware, make sure you are power
supply is providing enough power and not oscillating.
Getting Started With ESPlorer
The ESPlorer is an IDE ESP8266 devices. It’s a multiplatform IDE can be used
in any environment it is not developed for a target system as it was created in
JAVA, this simply means that it runs on Windows, Mac OS X or Linux.
 Supported platforms:
 Windows(x86, x86-64)
 Linux(x86, x86-64, ARM soft & hard float)
 Solaris(x86, x86-64)
 Mac OS X(x86, x86-64, PPC, PPC64)
This software allows you to establish a serial communications with your
ESP8266, send commands, and upload code and much more.

Extract the files that you have downloaded previously and open Esplorere.jar file.
If you are using MAC or linux type the following command in your terminal to
run ESPlorer.
Sudo java –jar Esplorer.jar
As the ESPlorer Ide created using JAVA it requires a java run time environment
for working, if you have not installed JAVA on your computer, downloaded it
and run the ESPlorer IDE, in some cases the jar files will be opened with the
WinRAR, in such cases you need to change some settings in your computer.
Method 1:
Go to your control panel and select default programs, and click associate a file
type or protocol with specific a specific program and wait for the programs to get
loaded in the window.
Navigate to .jar and select change program and choose java from there.

Method 2:
Open your WinRAR, and select options and click on settings.

On the setting, click on the Integration tab and uncheck JAR in the Associate
WinRAR with.
ESPlorer IDE overview
When you first open the ESPlorer IDE, it looks exactly shown below.

On the top right of ESP8266 choose Nodemcu+MicroPython tab, as we going to


use lua program we need to choose this section when communicating with
ESP8266 device or Nodemcu dev kit. Under Nodemcu+MicroPython tab there
are many sub tabs you can see, Scripts tab is the place where all the Programming
are done, program can be opened, save and close using the functions available in
the Scripts tab.
Next to this Main tab on the Left side you can see functions which enable serial
communication between Nodemcu dev kit and the IDE.
This functions allow to choose
COM port of the ESP8266
device that is currently
connected to your computer,
after selecting the Com port ,
Open button helps to establish
communication with the ESP8266 device that is associated with the selected
COM port, baud rate can also be choose by selecting the drop down button
available next to the Open button.

The window below the above functions tab is exactly work as the serial monitor,
which helps to visibly check communication with ESP8266 devices, display the
output result and also show the error if there is any during the execution of
program.
Nodemcu API for Lua
GPIO API
This GPIO(General Purpose Input/Output) allows us to access to pins of ESP8266
, all the pins of ESP8266 accessed using the command GPIO, all the access is
based on the I/O index number on the NoddMCU dev kits, not the internal GPIO
pin, for example, the pin ‘D7’ on the NodeMCU dev kit is mapped to the internal
GPIO pin 13, if you want to turn ‘High’ or ‘Low’ that particular pin you need to
called the pin number ‘7’ no the internal GPIO of the pin. When you are
programming with generic ESP8266 these confusion will arise which pin needs
to be called during programming, if you are using NodeMCU dev kit, it has come
prepared for working with Lua interpreter which can easily program by looking
the pin names associated on the lua board.
If you are using generic ESP8266 device or any other vendor boards please refer
to the table below to know which IO index is associated to the internal GPIO of
ESP8266.
Nodemcu dev kit ESP8266 Pin Nodemcu dev kit ESP8266 Pin
D0 GPIO16 D7 GPIO13
D1 GPIO5 D8 GPIO15
D2 GPIO4 D9 GPIO3
D3 GPIO0 D10 GPIO1
D4 GPIO2 D11 GPIO9
D5 GPIO14 D12 GPIO10
D6 GPIO12

D0 or GPIO16 can be used only as a read and write pin, no other options like
PWM/I2C are supported by this pin.
gpio.mode() : This command will initialize the GPIO mode and also used for
setting the input/output direction of the pin
Syntax : gpio.mode(pin, mode)
Pin : select any of the available gpio pins
Mode: set the selected pin mode to input or output.
Example: gpio.mode(7, gpio.OUTPUT)
gpio.read(): This command will read the pin value, whether the pin is in High state
or Low state will be returned when use this command.
Syntax: gpio.read(pin)
On the function type the pin number to read, this will return a number based on
the High or Low on the pin side, if the pin is in high state this will return 1 and if
it is low state this will return 0.
Example: gpio.read(7)
gpio.write() : This command will makes the pin to go High or Low, we use this
command to set a pin to go High or Low, if you want to turn on and off an LED
this command can be used in such situations.
Syntax: gpio.write(pin, state)
Pin : enter the pin that you want to change the state to high or Low
State: High or Low, gpio.HIGH or gpio.LOW
Example:
pin = 7
gpio.mode(pin, gpio.OUTPUT)
gpio.write(pin, gpio.HIGH)
above program will set the D7 pin of Nodemcu to go High, on the first line pin is
assigned to variable 7, and on the second line ‘D7’ pin as set to Output and on the
third line ‘D7’ pin has made to HIGH which will write value 1 to the pin, which
will make to to glow if you connect a LED to the pin ‘D7’,

gpio.trig() : This command act as interrupt function during programming, using


this command can cause the program to execute certain function when the
particular pin is triggered , this function will not be available if
GPIO_INTERRPUT_ENABLE was undefined at the time of compile.
Syntax: gpio.trig(pin, type [, function(level)])
Choose pin 1 to 12, as the pin D0 or GPIO16 is not support interrupt or any other
function.
Type: “up”, “down”, “both”, “low”, “high” which represent rising edge, falling
edge, both edge, low level, high level trigger mode, if you want to choose the
interrupt to occur when the pin goes low, you should choose low as type, which
means the pin will be actively high, when the pin goes to low state it should stop
the function and call the function to execute during interrupt.
Function(level) callback function when triggered.
Example:
local pin = 5
function pinValue ()
print('The pin value'..gpio.read(pin))
end
gpio.mode(pin, gpio.INT)
gpio.trig(pin, 'HIGH', pinValue)
The above example will return the pin value if the pin ‘D5’ goes high, for example
if you connected a push button to the pin ‘D7’, and whenever you push the
pushbutton, program will call the function pinValue, the pinValue function
executes the current value of the PIN 5, so it will return the value as ‘1’ on the
serial monitor.
ADC API
ADC API provides access to the inbuilt ADC, ESP-12 has an inbuilt ADC
pin, only pin is available and it is not much stable with the Generic ESP-12, you
should also aware that it can read only upto 1v. if you are using Generic ESP
devices you should use voltage divider in order to make it work, NodeMCU has
inbuilt voltage divider for the ADC pin and we can connected analog devices
directly to this device.
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.
adc.read() : samples the ADC.

Syntax : adc.read(channel)
There is only one channel available with esp devices so always choose 0, may in
future device we can expect more ADC with ESP chips. This will return the
sampled value in number.
Example : val = adc.read(0)
Bit API
NodeMCU supports Bit manipulation on 32bit integers.
bit.arshift() , bit.rshift(), bit.lshift()
Returns either the bitwise logical left-shift, bitwise logical right-shift, or
bitwisearithmetic right-shift of its first argument by the number of bits given by
the second argument.
Logical shifts treat the first argument as an unsigned number and shift in 0-bits.
Arithmetic right-shift treats the most-significant bit as a sign bit and replicates it.
Only the lower 5 bits of the shift count are used (reduces to the range [0..31]).
Syntax: bit.arshift(value,shift)
Enter value to shift and how many positions to shift, it returns the number shifted
right (arithmetically)
Syntax: bit.rshift(value,shift)
Enter a value to shift and how many positons to shift, it returns the number shifted
right (logically)
Syntax: bit.lshift(value,shift)
Enter a value to shift and how many positions to shift, it returns the number
shifted to left.
Example:
print(bit.lshift(1, 0)) 1
print(bit.lshift(1, 8))  256
print(bit.lshift(1, 40))  256
print(bit.rshift(256, 8)) 1
print(bit.rshift(-256, 8))  16777215
print(bit.arshift(256, 8)) 1
print(bit.arshift(-256, 8))  -1
printx(bit.lshift(0x87654321, 12))  0x54321000
printx(bit.rshift(0x87654321, 12))  0x00087654
printx(bit.arshift(0x87654321, 12))  0xfff87654

bit.band(), bit.bor(), bit.bxor()


Returns either the bitwise or, bitwise and, or bitwise xor of all of its arguments.
Note that more than two arguments are allowed.
Syntax : bit.band(val1, val2 [,……valn])
Val1 is the first AND argument Val2 is the Second AND argument and Valn is
the Nth AND argument, this will return the bitwise AND of all the arguments in
number.
Syntax: bit.bor(val1, val2 [,….valn])
Val1 is the first OR argument Val2 is the Second OR argument and Valn is the
Nth OR argument, this will return the bitwise OR of all the arguments in number.
Syntax: bit.bxor(val1, val2 [,….valn])
Val1 is the first XOR argument Val2 is the Second XOR argument and Valn is
the Nth XOR argument, this will return the bitwise XOR of all the arguments in
number.
Example:
print(bit.bor(1, 2, 4, 8))  15
printx(bit.band(0x12345678, 0xff))  0x00000078
printx(bit.bxor(0xa5a5f0f0, 0xaa55ff00))  0x0ff00ff0

bit.bit()
Generate a number with a 1 bit (used for mask generation).
Syntax: bit.bit(position)
Example:
bit.bit(3)  0x00000008
bit.clear()
Clear bits in a number
Syntax: bit.clear(value, pos1, pos2, …. posn)
Value is the base number and pos1 is the first bit to clear and posn is the nth bit
to clear and this will return the number with the bits cleared in the given positions.
V1 = 0x000000ff
bit.clear(V1, 4, 5, 6, 7)  0x000000f
bit.isset() : This function will test if a given bit is set or not.
Syntax: bit.isset(value, position)
The value is to test the bit position. This will returns true if the bit at the given
position is 0, else it will return as false if the bit at the position is non zero.
V1 = 0x000000ff
bit.clear(V1, 1)  result: true
Node API
Node API’s allow the user to provide access to system level features such
as restart, sleep and ID’s, which include ESP chip ID, flash chip ID.
node.bootreason()
This functions inspect boot cause and returns the boot reason and extended
rest info.
When you call this function this will return the raw code and the values are
Value Reset Information
1 Power-On
2 Reset (software)
3 Hardware reset via reset pin
4 WDT reset (watchdog timeout)

Second value returned is the extended reset cause and the values are given below:
Value Reset Information
1 Power on
2 Hardware watchdog reset
3 Exception reset
4 Software watchdog reset
5 Wake from deep sleep
6 External reset.

In general, the extended reset cause supercedes the raw code. The raw code is
kept for backwards compatibility only. For new applications it is highly
recommended to use the extended reset cause instead.
In case of extended reset cause 3 (exception reset), additional values are returned
containing the crash information. These are, in order, EXCCAUSE, EPC1, EPC2,
EPC3, EXCVADDR, and DEPC.
Syntax : node.bootreason()
It returns rawcode, reason [, exccause, epc1, epc2, epc3, excvaddr, depc]
Example:
flag=node.bootreason()
print("reasonis:")
print(flag)

This added to the firmware developed in the date 2015-06-27, Make sure you
have firmware which supports this function.
node.chipid()
This function returns the chip id, when you call this function in the program it
will store the chip id.
Syntax: node.chipid()
Example:
Chipid = node.chipid()
Print(“ chip id:”..Chipid)
node.compile()
This functions compiles a Lua text file into Lua bytecode, and it also saves it as
.lc file extension.
Syntax: node.compile(“filename.lua”)
The filename should be the name that you saved your Lua file.
Example:
file.open(“Myfile.lua”, “w+”)
file.writeline([[print( “Nodemcu”)]])
file.writeline([[print(node.heap())]])
file.close()
node.compile(“Myfile.lua”)
dofile(“Myfile.lua”)
dofile(“Myfile.lc”)
Above example will create file called Myfile.lua in the file “Nodemcu” will be
written and in the next line it returns the heap size or the balance memory in your
NodeMCU dev or ESP8266 device, and the file will be closed.
node.compile command open the file name Myfile.lua and compiles the file and
save the file in the .lc extension format.
node.dsleep()
The above function will make the ESP8266 device to enter into deep sleep mode
till the device timed out. Maximum sleep time for the device is 70 minutes, you
cannot extended the time limit as it was the limitation in the software , if you have
older Firmware the maximum sleep is less than 35.
This function can use in ESP device when it meet certain conditions, esp8266
PIN (RST) and PIN8 (GPIO16) should connected together. Using sleep (0) will
make the device to set no wake up timer, connect a GPIO to pin RST, the chip
will wake up by falling-edge on the RST pin. You should follow these steps for
proper working of this function.
Syntax: node.dsleep(us, option)
us is the sleep time in microsecond, if us == 0, it will sleep forever, if us ==nil,
will not set sleep time.
Example:
-- sleep time is 10s
sleep_time = 10 * 1000 * 1000

-- Do not forget to connect PIN32 and PIN8


node.dsleep(sleep_time);
0, init data byte 108 is valuable
> 0, init data byte 108 is valueless
0, RF_CAL or not after deep-sleep wake up, depends on init data byte 108
1, RF_CAL after deep-sleep wake up, there will be large current
2, no RF_CAL after deep-sleep wake up, there will only be small current
4, disable RF after deep-sleep wake up, just like modem sleep, there will be the
smallest current
node.heap()
This function returns the current available heap size in bytes, this will not
return exact heap size due to fragmentation and actual allocation due to this this
will return data but it should not take it as an exact required information.
Syntax: node.heap()
node.flashid()
This function returns the ID of the flash chip.
Syntax: node.flashid()

node.info()
This function returns firmware version, chipid, flashid, flash size, flash
mode and flash speed.
Syntax: node.info()

node.restart()
This function allow the chip to restart
Syntax: node.restart()

node.setcpufreq()
This function will change the CPU working frequency.
Syntax: node.secpufreq(speed)
Speed should be constant either 80MHZ or 160MHZ, should be careful when
changing this function as it may affect the chip working behaviour during the
execution of the program.
Example:
node.setcpufreq(node.CPU80MHZ)
or
node.setcupfreq(node.CPU160MHZ)

FILE API
File API provides access to the file system and its individual files, this allows
user to create a file inside a program and edit information on the file and save the
file using file API, only one file is possible to open at a time and it will not allow
to access multiple files, the file system follows a flat file system with no notion
of directories or folders.
file.open()
This function allows to open any file in the system for editing or creating a new
file, this function access to all the existing files in the system, if we want to create
any new file using this function can only be done, for creating a new file , we
need to open a file in write mode. All the file.open() function must be closed with
file.close function.
Syntax: file.open(filename, mode)
Filename, the file to be opened. There are different mode available to work on
the files.
“r”: read mode (default mode in the file access)
“w”: write mode
“a” : append mode ( adding data to existing file)
“r+”: update mode. All previous data are preserved
“w+”: update mode, all previous data is erased
“a+”: append update mode, previous data is preserved, writing is only allowed at
the end of file.
Example:
file.open(“init.lua”, “r”)
print(file.readline())
file.close()

file.close()
This function closes any of the opened file, this function should be used
with the function file.open() at the end.
Syntax: file.close()

file.flush()
Flushes any pending writes to the file system, ensuring no data is lost on a restart.
Syntax: file.flush()
Example:
file.open(“script.lua”, “a+”)
file.write(‘ hello’)
file.flush()
file.write(‘world’)
file.close()

file.format()
This function will erases all the existing files in the system and writes a
new one, depending on the size of the available flash chip in the ESP, it takes
time depend on its flash ID.
Syntax: file.format()

file.fsinfo()
This returns the file size information for the file system, in bytes.
Syntax: file.fsinfo()

file.list()
This function lists all the available files in the system.
Syntax: file.list()

file.write()
This function writes a string to the open file.

Syntax: file.write(string)
file.writeline()
This function will write a string to the opened file and append ‘\n’ at the end of
the file which will add a new line after append string.
Syntax: file.writeline(string)
Example:
file.open(“newfile.lua”, “a+”)
file.writeline(‘ this will add a new line at the end’)
file.close()

file.seek()
This function sets and gets the file position,
Syntax: file.seek([whence[, offset]])

file.rename()
Renames a file, if the file to be changed to some other name this function is used
for such cases.
Syntax: file.rename(oldname, newname)

file.remove()
This functions allows us to remove a file from system, to do this the file that needs
to remove should not be currently opened as a file anywhere.
Syntax: file.remove(filename)

Wi-Fi API
Very important API’s available with NodeMCU firmware, this allows NodeMCU
dev kit or ESP8266 chips to connect with other devices and access information
from internet and allow a user to control a device from any part of the world, on
chip Wi-Fi SoC is what made the ESP most popular among hobbyist and it grows
to phenomenal rate at this time.
wifi.getchannel()
This function gets current wifi channel that is currently connected. When this
function called in program this will return the wifi channel name.
Syntax: wifi.getchannel()
Example:
print(wifi.getchannel())

wifi.setmode()
This function configures the Wi-Fi mode to use, NodeMCU can run in four
different modes:
1) Station mode, where the NodeMCU device joins an existing network
2) Access point mode, where it creates its own network that other can join, it
serves as the Wi-Fi router for other devices.
3) Station + Access point mode
4) WiFi off

Syntax: wifisetmode(mode)
Mode value should one of the mode as follows
I) wifi.STATION this will mode set it to the first available mode, that
is station mode which allow the device connected to a WiFi router,
this mode is often used to access internet with ESP device.
II) wifi.SOFTAP this mode will set NodeMCU dev kit as an access
point.
III) wifi.STATIONAP this mode is the combination of both 1 and 2.
When using the combined station + AP mode, the same channel will
be used for both networks as the radio can only listen on a single
channel.
IV) wifi.NULLMODE this mode will turn off WiFi.

wifi.getmode()
This function will gets wifi operation mode, this will make us to know which
mode the wifi has currently set to. Just above the screen you can see the number
of available mode.
Syntax: wifi.getmode()
This will return as one of the following wifi.STATION, wifi.SOFTAP,
wifi.STATIONAP or wifi.NULLMODE constants.

wifi.setphymode()
This function will sets WiFi physical mode.
1) wifi.PHYMODE_B 802.11b, more range, llow Transfer rate, more current
draw
2) wifi.PHYMODE_G 802.11g, medium range, medium transfer rate,
medium current draw
3) wifi.PHYMODE_N 802.11n, least range, fast transfer rate, least current
draw (STATION ONLY) information from the Espressif datasheet v4.3

Parameters Typical Power Usage


Tx802.11b, CCK 11Mbps, P OUT= 170mA
+17dBm
Tx802.11g, OFDM 54Mbps, P 140mA
OUT = +15dBm
Tx802.11n, MCS7 65Mbps, P OUT 120mA
= +13dBm
Rx802.11b, 1024 bytes packet 50mA
length, -80dBm
Rx 802.11g, 1024 bytes packet 56 mA
length, - 70dBm
Rx802.11n, 1024 bytes packet 56mA
length, -65dBm

Syntax
wifi.setphymode(mode)
Mode one of the following parameters below

1) wifi.PHYMODE_B
2) wifi.PHYMODE_G
3) wifi.PHYMODE_N

wifi.getphymode()
This function returns WiFi physical mode that is currently set to the device.
Syntax: wifi.getpymode()
The above syntax will return wifi.PHYMODE_B, wifi.PHYMODE_G or
wifi.PHYMODE_N.

wifi.sleeptype()
This function configures the WiFi modem into sleep type.
Syntax: wifi.sleeptype(type_wanted)
Type wanted should be as follows

1) wifi.NONE_SLEEP to keep the modem on at all times


2) wifi.LIGHT_SLEEP to allow the modem to power down under some
circumstances.
3) wifi.MODEM_SLEEP to power down the modem as much as possible.

wifi.sta.config()
This function sets the WiFi station configuration.
Syntax: wifi.sta.config(ssid, password[, auto[, bssid]])
Ssid is the name of WiFi router and the string name should be less than 32 bytes.
Password is the wifi router password which is 8-64 or 0 bytes. Empty string
indicates an open WiFi access point.
Auto value of 0 or 1 (default value is 1)
0 will disable auto connect and remain disconnected from access point.
1 will enable auto connect and connect to access point.
bssid this string contains the MAC address of the access point and it is not
mandotary it is an option to be used.
You can set BSSID if you have multiple access points with the same SSID.
Note: if you set BSSID for a specific SSID and would like to configure station to
connect to the same SSID only without the BSSID requirement, you MUST first
configure to station to a different SSID first, then connect to the desired SSID
The following formats are valid:
"DE-C1-A5-51-F1-ED"
"AC-1D-1C-B1-0B-22"
"DE AD BE EF 7A C0"
Examples:
--Connect to access point automatically when in range
wifi.sta.config("myssid", "password")

--Connect to Unsecured access point automatically when in range


wifi.sta.config("myssid", "")

--Connect to access point, User decides when to connect/disconnect to/from AP


wifi.sta.config("myssid", "mypassword", 0)
wifi.sta.connect()
-- ... do some WiFi stuff
wifi.sta.disconnect()

--Connect to specific access point automatically when in range


wifi.sta.config("myssid", "mypassword", "12:34:56:78:90:12")

--Connect to specific access point, User decides when to connect/disconnect


to/from AP
wifi.sta.config("myssid", "mypassword", 0, "12:34:56:78:90:12")
wifi.sta.connect()
-- ... do some WiFi stuff
wifi.sta.disconnect()

wifi.sta.connect()
This functions connect to access point in station mode.
Syntax: wifi.sta.connect()

Wifi.sta.disconnect()
This function disconnect from access point in station mode.
Syntax: wifi.sta.disconnect()

wifi.sta.getbroadcast()
This function gets the broadcast address in station mode.
Syntax: wifi.sta.getbroadcast()
This will broadcast the address as string, for example “192.168.0.105”

wifi.sta.getconfig()
This function will gets the Wi-Fi station configuration.
Syntax: wifi.sta.getconfig()
When this function called in program this will return ssid, password, bssid_set,
bssid, if bssid_set is equal to 0 then bssid is irrelevant.
Example:
--Get current Station configuration
ssid, password, bssid_set, bssid=wifi.sta.getconfig()
print("\nCurrent Station configuration:\nSSID : "..ssid
.."\nPassword : "..password
.."\nBSSID_set : "..bssid_set
.."\nBSSID: "..bssid.."\n")
ssid, password, bssid_set, bssid=nil, nil, nil, nil

wifi.sta.gethostname()
This function will returns the currently connected hostname station.
Syntax: wifi.sta.gethostname()

When this function called in program, this will returns currently configured
hostname.
Example:
print("Current hostname is: \""..wifi.sta.gethostname().."\"")

wifi.sta.getip()
This function will gets IP address, netmask, and gateway address in station mode.
Syntax: wifi.sta.getip()
Example:
-- print current IP address, netmask, gateway
print(wifi.sta.getip())
-- 192.168.0.111 255.255.255.0 192.168.0.1
ip = wifi.sta.getip()
print(ip)
-- 192.168.0.111
ip, nm = wifi.sta.getip()
print(nm)
-- 255.255.255.0
wifi.sta.getmac()
This function get mac address in station mode.
Syntax: wifi.sta.getmac()
The above syntax when called in program will returns MAC address as string.

Wifi.sta.sethostname()
This function will sets station hostname.
Syntax: wifi.sta.sethostname(hostname)
Hostname must only contain letters, numbers and hyphens('-') and be 32
characters or less with first and last character being alphanumeric, and the
function will return true if the hostname has successfully set, else it will return
false if the hostname was not succeed.

Example:
if (wifi.sta.sethostname("NodeMCU") == true) then
print("hostname was successfully changed")
else
print("hostname was not changed")
end

wifi.sta.setip()
This function sets IP address, netmask, gateway address in station mode, if this
function has not used wifi router will automatically set the IP address, netmask
and gateway address, make sure the assigning IP address is not using by any other
device that has currently connected to the router.
Syntax: wifi.sta.setip(cfg)
Cfg table contain IP address, netmask and gateway
{
ip= “192.168.0.100”
Netmask = “255.255.255.0”,
gateway = “192.168.0.1”
}
If the function is successful it returns true else it will return false.

wifi.sta.setmac()
This function sets MAC address in station mode.
Syntax: wifi.sta.setmac(mac)
MAC address should be in string, this function returns true if success else this
will return false if the address was not successfully assigned.

wifi.sta.status()
This function will get the current status in station mode.
Syntax: wifi.sta.status()
This will return the number 0-5.
0: STATION_IDLE

1: STATION_ CONNECTING
2: STATION_WRONG_PASSWORD
3: STATION_NO_AP_FOUND,
4: STATION_CONNECT_FAIL
5: STATION_GOT_IP.
wifi.ap.config()
This function will set SSID and password in Access Point mode, make sure to
choose password as 8 characters or more if you fail to do this, device will
automatically set to default mode where it will automatically assign SSID and
password will be none.
Syntax: wifi.ap.config(cfg)
Ssid SSID chars should be 1-32 characters long.
Password should be more than 8 characters.
Authentication one of AUTH_OPEN, AUTH_WPA_PSK, AUTH_WPA2_PSK,
AUTH_WPA_WPA2_PSK, default = AUTH_OPEN
Channel number 1-14 default = 6
Hidden, if it is 0 then not hidden, if it is 1 it is set to hidden by default it is set to
0.
Maximum number of connections 1-4 by default = 4.
Beacon interval time in range 100 – 60000, default = 100.
Example:
Cfg ={}
Cfg.ssid = “myssid”
Cfg.pwd = “mypassword”
Wifi.ap.config(cfg)

wifi.ap.getbroadcast()
This function will gets broadcast address in access point mode.
Syntax: wifi.ap.getbroadcast()
This function will return broadcast address in string .
Example:
broadcast = wifi.ap.getbroadccast()

print(broadcast)
wifi.ap.getclient()
This function will get table of clients connected to the NodeMCU dev kit when
the kit act as an Access point to other devices.
Syntax: wifi.ap.getclient()
Examples:
table={}

table=wifi.ap.getclient()
for mac,ip in pairs(table) do
print(mac,ip)
end

-- or shorter
for mac,ip in pairs(wifi.ap.getclient()) do
print(mac,ip)
end

wifi.ap.getip()
This function will gets IP address, netmask and gateway in access point mode.
Syntax: wifi.ap.getip()
Example:
print current ip, netmask, gateway
print(wifi.ap.getip())
-- 192.168.4.1 255.255.255.0 192.168.4.1
ip = wifi.ap.getip()
print(ip)
-- 192.168.4.1
ip, nm = wifi.ap.getip()
print(nm)
-- 255.255.255.0
ip, nm, gw = wifi.ap.getip()
print(gw)
-- 192.168.4.1

wifi.ap.getmac()
This function will gets MAC address in access point mode.
Syntax: wifi.ap.getmac()
wifi.ap.setip()
This function will set IP address, gateway and netmask in access point mode.
Syntax: wifi.ap.setip(cfg)

wifi.ap.setmac()
This function will set MAC address in Access point mode.
Syntax: wifi.ap.setmac(mac)

wifi.ap.dhcip.config()
This function will configure the dhcp service.
Syntax: wifi.ap.dhcp.config(dhcp_config)
Example:
dhcp_config ={}
dhcp_config.start = "192.168.1.100"
wifi.ap.dhcp.config(dhcp_config)

wifi.ap.dhcp.start()
This function will starts the DHCP service
Syntax: wifi.ap.dhcp.start()

wifi.ap.dhcp.stop()
This function will stops the DHCP service.
Syntax: wifi.ap.dhcp.stop()
Timer API
The lua firmware provides an API with which can be used to set timeouts
and intervals, functions that execute after a period of time, either once or over and
over again. However, the modules only have capacity to have seven timers or
intervals running at the same time. Therefore, you need to reference them by
index (0 to 6) and make sure that different parts of your program don’t override
the same timer.
tmr.alarm()
This is a convenience function combining tmr.register() and tmr.start() into a
single call.
To free up the resources with this timer when done using it,
call tmr.unregister() on it. For one-shot timers this is not necessary, unless they
were stopped before they expired. We use the same function to create both
timeouts and intervals, tmr.alarm(). We differentiate which type of timer we
want to create using the third argument; 0 = timeout, 1= interval:
Syntax: tmr.alarm(id, interval, mode, function do())
Id is the timer id (0-6)
interval is the timer interval in milliseconds, Maximum value is 12884901
mode timer mode:
tmr.ALARM_SINGLE a one-shot alarm (and no need to call tmr.unregister())
tmr.ALARM_SEMI manually repeating alarm (call tmr.start() to restart)
tmr.ALARM_AUTO automatically repeating alarm

Example:
function sayHello ()
print 'Hello'
end
tmr.alarm(0, 2500, 0, sayHello)
Here we are creating a timeout at timer index zero and setting it to call
the sayHello() function after 2.5 seconds.
If we were to create another timeout (or interval) at index zero before this timer
executed, it would simply overwrite it and sayHello() would never be called.
tmr.delay()
Busyloops the processor for a specified number of microseconds.
This is in general a bad idea, because nothing else gets to run, and the networking
stack (and other things) can fall over as a result. The only time tmr.delay() may
be appropriate to use is if dealing with a peripheral device which needs a (very)
brief delay between commands, or similar. Use with caution!
Also note that the actual amount of time delayed for may be noticeably greater,
both as a result of timing inaccuracies as well as interrupts which may run during
this time.
Syntax: tmr.delay(us)
us is the microseconds to delay the loop.

tmr.interval()
This function changes a registerd timer’s expiry interval.
Syntax: tmr.interval(id, interval)
Example:
tmr.register(0, 60000, tmr.ALARM_SINGLE, function() print (“ Timer function”)
end)
tmr.inerval (0, 3000)

tmr.now()
This functions returns the system counter, which counts in microseconds. Limited
to 31 bits, after that it wraps around back to zero.
Syntax: tmr.now()
Example:
Print(tmr.now)

tmr.time()
This function returns the system uptime, in seconds, limited to 31 bits after that
it wraps around back to zero
Syntax: tmr.time()
Example: print(“uptime:”, tmr.time())

tmr.wdclr()
This function feed the system watchdog.
In general, if you ever need to use this function, you are doing it wrong.
The event-driven model of NodeMCU means that there is no need to be sitting in
hard loops waiting for things to occur. Rather, simply use the callbacks to get
notified when somethings happens. With this approach, there should never be a
need to manually feed the system watchdog.
Syntax: tmr.wdclr()

tmr.unregister()
Stops the timer (if running) and unregisters the associated callback.
This isn't necessary for one-shot timers (tmr.ALARM_SINGLE), as those
automatically unregister themselves when fired.
Syntax: tmr.unregister(id)
Id is the timer id between (0-6)
Example: tmr.unregister(0)

tmr.stop()
This functions stops a running timer, but does not unregister it, A stopped timer
can be restarted with tmr.start()
Syntax: tmr.stop(id)
Example:
If not
tmr.stop(2)
Then
Print (“ timer 2 not supped, not regisetered”)
end
tmr.register()
Configures a timer and registers the callback function to call on expiry.
To free up the resources with this timer when done using it,
call tmr.unregister() on it. For one-shot timers this is not necessary, unless they
were stopped before they expired.
Syntax: tmr.register(id, interval, mode, func)

tmr.softwd()
This function provides a simple software watchdog, which needs to be re-armed
or disabled before it expires, or the system will be restarted.
Syntax: tmr.softwd(timeout_s)
Timeout_s is the watchdog timeout, in seconds, to disable the watchdog use -1.
Example:
function on_success_callback()
tmr.softwd(-1)
print("Complex task done, soft watchdog disabled!")
end
tmr.softwd(5)
-- go off and attempt to do whatever might need a restart to recover from
complex_stuff_which_might_never_call_the_callback(on_success_callback

tmr.state()
This function checks the state of a timer.
Syntax: tmr.state(id)
This fucntions returns if the specified timer is registered, returns whether it is
currently started and its mode, if the timer is not registered, this function will
return nil.
Example:
Running, mode = tmr.state(0)
tmr.start()
This functions starts or restarts a previously configured timer.
Syntax: tmr.start(id)
This function will return true if the timer was started and gives false if there is an
error on starting the timer.
Example:
Tmr.register(0, 500, tmr.ALARM_SINGLE, function() print( “hello”) end)
If not tmr.start(0) then print (“yes”)end

PWM API
Pulse Width Modulation API’s allows us to use any of the I/O pin as PWM pin
except the D0 pin of NodeMCU DEV KIT, this API will be very useful when
controlling LED’s , Motors and many more devices which require PWM
functions to do crazy things.
pwm.setup()
This function allows to set a pin to PWM mode, only 6 pins can be set to PWM
mode at the most case.
Syntax: pwm.setup(pin, clock, duty)
Pins from 1 to 12 can be choose for PWM
Clock frequency should be set between 1- 1000, pwm frequency.
Duty cycle should be between 0-1023 , max is 1023(10bit)
Example: pwm.setup(1, 100, 512)  this example set the ‘D1’ pin as pwm output
and frequency is 100 hz and duty cycle is 512.

pwm.start()
This function starts the PWM, the waveform is applied to the GPIO pin.
Syntax: pwm.start(pin)

pwm.stop()
This function pause the output of the PWM waveform.
Syntax: pwm.stop(pin)
pwm.setduty()
This function allows to set the duty cycle for a pin.
Syntax: pwm.setduty(pin, duty)
Example:
pwm.setup(1, 500, 512)
pwm.setup(2, 500, 512)
pwm.setup(3, 500, 512)
pwm.start(1)
pwm.start(2)
pwm.start(3)
function led(r, g, b)
pwm.setduty(1, g)
pwm.setduty(2, b)
pwm.setduty(3, r)
end
led(512, 0, 0) -- set led to red
led(0, 0, 512) -- set led to blue.

NET API
Constants
net.TCP, net.UDP
net.createConnection()
This function creates a client connection.
Syntax: net.createConnection(type, secure)
Type must be net.TCP or net.UDP
Secure 1 for encrypted connection and 0 for plain connection.
Example:
net.createConnection(net.UDP,0)

net.createServer()
This function creates a server. Server is the base class for all the ESP8266 server
calls.
Syntax: net.createServer(type, timeout)
Timeout for a TCP server timeout is 1-28,000 seconds ( for an inactive client to
be disconnected) this function will returns net.server sub module.
Example:
net.createServer(net.TCP, 30)

net.server.close()
This function closes the server.
Syntax: net.server.close()
Example:
Sc = net.createServer(net.TCP, 30)
Sc:close()

net.server.listen()
This function listen on port from IP address.
Syntax: net.server.listen(port, [ip], function (net.socket))
Port is the port number
Ip address string, this can be omitted
Function (net.socket) callback function, pass to caller function as param if a
connection is created successfully.
Example:
-- 30s time out for a inactive client
sv = net.createServer(net.TCP, 30)
-- server listens on 80, if data received, print data to console and send "hello
world" back to caller
sv:listen(80, function(c)
c:on("receive", function(c, pl)
print(pl)
end)
c:send("hello world")
end)

net.socket.close()
This function closes socket connection
Syntax: net.socket.close()
net.socket.connect()
This function connect to a remote server.
Syntax: connect(port, ip| domain)
Port is the port number and ip address or domain name string

Net.socket.dns()
This function provides DNS resolution for a hostname
Syntax: dns(domain, function(net.socket, ip))
Domain name is the domain for the host, function(net.socket,ip) callback
function, this first parameter is the socket, the second parameter is the IP address
as a string.
Example:
sk = net.createConnection(net.TCP, 0)
sk:dns("www.nodemcu.com", function(conn, ip) print(ip) end)
sk = nil

net.socket.on()
This function register callback funtions for specific events.
Syntax: on(event, function())
Event is a string, which can be “ connection” , “ reconnection”, “ disconnection”,
“ receive” or “ sent” . function(net.socket[, string]) callback function, the first
parameter is the socket, if event is “ receive” the second parameter is the received
data as string.
Example:
sk = net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:connect(80,"192.168.0.66")
sk:on("connection", function(sck,c)
-- Wait for connection before sending.
sk:send("GET / HTTP/1.1\r\nHost: 192.168.0.66\r\nConnection: keep-
alive\r\nAccept: */*\r\n\r\n")
end)
net.socket.send()
This function sends data to server.
Syntax: send(string, function(sent))
String is the data in string which will be sent to server and function(sent) callback
function for sending string.
net.dns.getdnsserver()
This function gets the IP address of the DNS server used to resolve hostnames.
Syntax: net.dns.getdnsserver(dns_index)
dns_index which DNS server to get (range 0 -1) this function returns IP
address(string) on DNS server.
Example:
print(net.dns.getdnsserver(0)) -- 208.67.222.222
print(net.dns.getdnsserver(1)) -- nil

net.dns.setdnsserver("8.8.8.8", 0)
net.dns.setdnsserver("192.168.1.252", 1)

print(net.dns.getdnsserver(0)) -- 8.8.8.8
print(net.dns.getdnsserver(1)) -- 192.168.1.252

net.dns.resolve()
This function resolve a hostname to an IP address. Doesn’t require a socket like
net.socket.dns()
Syntax: net.dns.resolve(host, function(ip))
Example:
net.dns.resolve("www.google.com", function(sk, ip)
if (ip == nil) then print("DNS fail!") else print(ip) end
end)

net.dns.setdnsserver()
sets the IP of the DNS server used to resolve hostnames.
Default:resolver1.opendns.com(208.67.222.222). you can specify up to 2 DNS
servers.
Syntax: net.dns.setdnsserver(dns_ip_addr, dns_index)
dns_ip_addr is the IP address of a DNS server and dns_index is which DNS server
to set (range 0-1). Hence it supports max 2 servers.

HTTP API
Basic HTTP client module.
Provides an interface to do basic GET/POST/PUT/DELETE over HTTP(S), as
well as customized requests. Due to the memory constraints on ESP8266, the
supported page/body size is limited by available memory. Attempting to receive
pages larger than this will fail. If larger page/body sizes are necessary, consider
using net.createConnection() and stream in the data.
Each request method takes a callback which is invoked when the response has
been received from the server. The first argument is the status code, which is
either a regular HTTP status code, or -1 to denote a DNS, connection or out-of-
memory failure, or a timeout (currently at 10 seconds).
For each operation it is also possible to include custom headers. Note that
following headers cannot be overridden however: - Host - Connection - User-
Agent
The Host header is taken from the URL itself, the Connection is always set
to close, and theUser-Agent is ESP8266.
Note that it is not possible to execute concurrent HTTP requests using this
module. Starting a new request before the previous has completed will result in
undefined behaviour.
http.delete()
This functions executes a HTTP delete request.
Syntax: http.delete(url, headers, body, callback)
The URL to fetch, including the http:// or https:// prefix
Headers are optional and additional headers to append, including \r \n;
The body to post, must already be encoded in the appropriate format, but may be
empty
Callback function to be invoked when the response has been received. It is
invoked with arguments status_code and body.
Example:
http.delete('https://www.example.com/ask',
"",
"",
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)

http.get()
This function executes a HTTP get request to the server.
Syntax: http.get(url, headers, callback)
url to fetch including the http:// or https://
headers are optional, Callback function to be invoked when the response has been
received. It is invoked with arguments status_code and body.
Example:
http.get("https://www.vowstar.com/nodemcu/", nil, function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)

http.post()
This function executes a HTTP post request.
Syntax: http.post(url, headers, body, callback)
Exmple:
http.post('http://json.example.com/something',
'Content-Type: application/json\r\n',
'{"hello":"world"}',
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
http.put()
This function executes a HTTP PUT request
Syntax: http.put(url, headers, body, callback)
Example:
http.put('http://db.example.com/items.php?key=deckard',
'Content-Type: text/plain\r\n',
'Hello!\nStay a while, and listen...\n',
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)

http.request()
This function executes a custom HTTP request for any HTTP method.
Syntax: http.request(url, method, headers, body, callback)
Example:
http.request("https://www.example.com", "HEAD", "", "", function(code, data)
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
Turn On and OFF an LED
In this chapter we will see how to turn on and off an LED connected to NodeMCU
dev kit or an ESP8266 generic device.
Requirement for this project
1) an LED
2) NodeMCU or ESP8266 board
3) Connecting wires.

as you can see in your LED it


has two pins, the longer pin is
known as Anode and the
shorter pin is known as
cathode, connect longer pin to
the 7th pin of Nodemcu dev kit,
if you are using generic
ESP8266 module connect it to
GPIO13, if you still have not sure about GPIO’s available with generic ESP8266
chips check the lookup table for the chip. It is not necessary to connect a resistor
between the NodeMCU dev kit and the LED.
Connect your NodeMCU to computer.
Open ESPlorer IDE.
Click on the refresh button, it will automatically detect the COM port your
Nodemcu has currently connected, set the baud rate to 9600 for communicating
with your device check the port currently connected which display at the top right
of your ESPlorer, click the open button to establish communication with your
NodeMCU.

After clicking the Open button, check on the serial monitor of the ESPlorer, if the
serial monitor displays continues dots, without any message like the one attached
in the screen below.
Click on the reset button on your NodeMCU dev kit if your dev kit not connecting
to your ESPlorer.
Reset button available on the left side
near the USB connector, press it once
and you can see your device
communicating with your ESPlorer.

Once the connection establish with the NodeMCU dev kit, you can see the same
message that appears in your ESPlorer serial monitor.
gpio.mode( 7, gpio.OUTPUT )
-- turn on
gpio.write( 7, gpio.LOW )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.HIGH )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.LOW )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.HIGH )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.LOW )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.HIGH )
tmr.delay( 1500000 ) -- delay 1.5 second
gpio.write( 7, gpio.LOW )
tmr.delay( 1500000 ) -- delay 1.5 second

Type the above program in your ESPlorer


After completing the program click on the send to ESP button on the bottom left
of your ESPlorer.

When you click the send to ESP button , you can view on your serial monitor
code is sending to ESP line by line, when the first line send to ESP you can view
on your Nodemcu dev kit, the connected LED will go High and Low based on
the line of code that currently sending to the ESPlorer.
Lua program explanation:
gpio.mode(7,gpio.OUTPUT)
This command will initialize pin to GPIO mode, set the pin as Input or Output
based on our setting to the pin, the compiler will assign the state of the pin. When
you using this command the function should consist of pin to configure and the
mode of the pin, gpio.OUTPUT or gpio.INPUT, this command will also assign a
pin as a pullup. , if we not choose the pullup option by default all the gpio pin
will set to Float.

gpio.write(7, gpio.LOW)
This command will set the digital GPIO pin value either high or low, based on
the output level selected by the programmer. In the above command digital pin
‘D7’ of NodeMCU has assigned to LOW level, this will make the connected LED
to go LOW or OFF state.

tmr.delay(1500000)
This command will delay the function for the period that is entered into the
function ( )
1000000 which equals 1 sec.
As you can see the in the program same set of codes has repeated throughout the
completion of program, which is easy to understand by knowing the above
command, the program has not consist of any loop so the program will execute
only a single time and stops, if you see the LED connected to NodeMCU, LED
will go High for 3 times and Low for 4 times and stops forever.
To do:
Add more number of lines to the code and check how the process is going on,
change the delay timer and check the LED output and note how the delay function
causing the program to change.

Working with LED


Blink an LED
In the previous chapter we have seen how to turn on and off an LED, in
this chapter we will see how to blink an LED using NodeMCU,
Easy blink function make you cry 
while 1 do
gpio.write(0, gpio.HIGH)
tmr.delay(1000000) -- wait 1,000,000 us = 1 second
gpio.write(0, gpio.LOW)
tmr.delay(1000000) -- wait 1,000,000 us = 1 second
end)
The above is the simple blink function which can go wrong if you don’t know
what it can done to your ESP8266, as the code is infinite loop and if you save the
code to NodeMCU or any other ESP8266 device, this code will run forever after
uploading this code, your NodeMCU will not respond to you if you try to
establish communication with your ESPlorer, if you ever happened to caught in
a situation like this flash the firmware again and do all the process from the
beginning.
For this example we going to use the same setup which we have used for the
previous example.
Connect your LED to the 7th pin of NodeMCU and check you are connecting the
LED pins properly to the 7th pin and the ground, if you interchange your anode
and cathode then it may lead to damage your LED.
Connect NodeMCU to your computer using USB cable.
Open ESPlorer and start type your program to the ESPlorer.

LUA program:
lighton=0
pin=7
gpio.mode(pin,gpio.OUTPUT)
tmr.alarm(1,1000,1,function()
if lighton==0 then
lighton=1
gpio.write(pin,gpio.HIGH)
else
lighton=0
gpio.write(pin,gpio.LOW)
end
end)
After completing the program click on the send to ESP button on the bottom left
of your ESPlorer.

When you click the send to ESP button , you can view on your serial monitor
code is sending to ESP line by line, after sending the code to ESP8266 device or
NodeMCU dev kit you can see the LED goes On and Off between the 1sec
interval.
Program Explanation:
lighton = 0
Lighton is a variable and you can use any of the name you would like for the
variable and the variable currently holds 0 as the value to its memory.

Pin = 7
This is also a variable, which we can assign a name to the pin number and instead
of the pin number we can call the pin number by the name that is assigned to the
pin.

gpio.mode(pin, gpio.OUTPUT)
We have already seen about this function, this function will set a digital pin to
either input or output.

tmr.alarm (1, 1000, 1, function()


When using timer function we are limited to use only 7 timers in the function this
is a limitation when using tmr function in NodeMCU. , to keep track of how many
functions we are using in the program we can use timer ID, 1 in the begging of
the function before 1000 is the track ID for the timer function, and the number
1000 is the time interval in milliseconds, and call the function every 1 second.

if lighton==0 then
lighton=1
gpio.write(pin,gpio.HIGH)
else
lighton=0
gpio.write(pin,gpio.LOW)
end
command which follows the tmr.alram is the function inside the tmr.alram
function(), this code will execute the function , it will turn make the ‘D7’ pin to
go high for 1 sec and set the Lighton = 1 and this will make the ‘D7’ pin to go
low when lighton = 0;

Init.lua
Save the above program as init.lua
After saving the file in the
name init and upload it to
the ESP8266 or
NodeMCU dev kit.
Whenever a file named as
init and uploaded to
ESP8266 that program
will first run when the
ESP8266 booted up.
Usually this init function
is used for storing wifi
ssid and password, which will make this device connected to a wifi when the ESP
booted up.

To do:
Try to change the timer interval in the tmr.alarm function and change the timer
ID, and check how it works, and also create another tmr.alarm with same ID and
check whether the tmr.alarm function with same ID is executing or not.
Connect another pin and write a program for 2 LED’s and also create two separate
functions and give different interval between these functions.

Você também pode gostar