[go: up one dir, main page]

0% found this document useful (0 votes)
2 views95 pages

IOT using ESP8266

The document provides an overview of the Internet of Things (IoT) using the ESP8266-12 module, detailing its installation, programming, and practical applications such as LED control and server setup. It includes code examples for various tasks, including LED blinking sequences, button interactions, and using the ESP8266 as a server or access point. Additionally, it introduces MIT App Inventor for creating Android apps to control IoT devices and mentions integration with Blynk for remote management.

Uploaded by

maneesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views95 pages

IOT using ESP8266

The document provides an overview of the Internet of Things (IoT) using the ESP8266-12 module, detailing its installation, programming, and practical applications such as LED control and server setup. It includes code examples for various tasks, including LED blinking sequences, button interactions, and using the ESP8266 as a server or access point. Additionally, it introduces MIT App Inventor for creating Android apps to control IoT devices and mentions integration with Blynk for remote management.

Uploaded by

maneesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 95

IOT using ESP8266-12

What is IoT?
• The Internet of Things (IoT) is the network
of physical objects
• Devices, vehicles, buildings and other items
embedded with electronics, software,
sensors, and network connectivity
• —that enables these objects to collect and
exchange data
NODE MCU devkit
Esp12 esp8266
Installing the ESP8266 Board

• 1. Open the preferences window


from the Arduino IDE. Go to File >
Preferences
• 2.Enter
http://arduino.esp8266.com/sta
ble/package_esp8266com_index.
json
• into Additional Board Manager
URLs field and click the “OK”
button
Open boards
manager. Go to
Tools > Board
> Boards
Manager…
• Scroll down, select the ESP8266
board menu and
install “esp8266 platform”
Choose your ESP8266 board from Tools >
Board > nodemcu -12E (ESP12E Module)
Programming Arduino
void setup()
{
preparation
-declaration of variables at the start of the
program
- sets pinMode or initialize serial communication
}
void loop()
{
execution
-Is the core of all Arduino programs and does the
bulk of the work.
-code to be executed continuously – reading inputs,
triggering outputs, etc.
}
{} curly braces
- define the beginning and end of function blocks and statement blocks such as
the void loop() function and the for and if statements.
; semicolon
semicolon must be used to end a statement and separate elements of the
program.
// line comments
Single line comments begin with // and end with the next line of code.
/*… */ block comments
used for large text descriptions of code or comments that help others
understand parts of the program
Variables
A variable is a way of naming and storing a numerical value for later
use by the program
• Int Integers are the primary datatype for storage of numbers without decimal
points
• store a 16-bit value with a range of 32,767 to -32,768
• float -A datatype for floating-point numbers, or numbers that have a decimal
point
• stored as a 32-bit value with a range of 3.4028235E+38 to -3.4028235E+38.
LED BLINK
void setup()
{
pinMode(D0, OUTPUT);
}
void loop() pinMode(pin number, OUTPUT or INPUT)
configure a specified pin to behave either as an INPUT or an OUTPUT
{ digitalWrite(pin number, HIGH or LOW)
digitalWrite(D0, HIGH); Outputs either logic level HIGH or LOW at (turns on or off)
delay(1000); a specified digital pin(13)
digitalWrite(D0, LOW); delay(miliseconds)
Waits for the given time
delay(1000);
}
Bread board
A light-emitting diode (LED)
It’s a semiconductor device that emits visible light when an electric
current passes through it.
TASK
• Using 3 led’s try blinking leds in order
• 1st led switches ON for 2 sec and OFF for 2 Sec
• 2nd led ON for 3 sec and OFF for 3 Sec
• 3rd led ON for 4 sec and OFF for 4 Sec
• using 3 led’s try blinking
• 1st led ON for 2 sec,
• Then 2nd led Switches ON for 3 sec
• Then 3rd led Switches ON for 4 sec
• and then reverse 3rd led switches OFF after 4 sec,
• 2nd switches OFF after 3 sec
• 1st led switches OFF after 2 sec and continue loop
• Hint use digitalWrite() and delay()
BUTTON SWITCH
BUTTON digitalRead(pin number)-reads from digital
void setup() pin i.e. 1 or 0 , ON or OFF, LOW or
{ HIGH
pinMode(D6, OUTPUT); ‘If’ is a condition given to program saying
pinMode(D5, INPUT); if you do this thing,then the output will be
} this or else it will be another.
void loop()
{
int buttonState = digitalRead(D5);
if (buttonState == HIGH)
{
digitalWrite(D6, HIGH);
} else {
digitalWrite(D6, LOW);
}
}
TASK

•Using 2 led and 1 button


• By pressing button 1st led should light and by releasing
2nd led should bright
• Using 2 led’s and 2 button
• By pressing 1st button switch on one led
• By pressing 2nd button switch on other led
LED IfON/OFF USING LDR
(condition) ,else if (condition) and else is used for
void setup()
{ having any arithmetic conditions
Serial.begin(9600); Various operations are
pinMode(D3, OUTPUT); x == y // x is equal to y
}
x != y // x is not equal to y
void loop() x < y // x is less than y
{ x > y // x is greater than y
int LDR = x <= y // x is less than or equal to y
analogRead(A0);
Serial.println(LDR); x >= y // x is greater than or equal to y
if (LDR>=100)
{ Logical AND:
digitalWrite(D3, HIGH);
}
if (x > 0 && x < 5) // true only if both
else // expressions are true
{ Logical OR:>>> if (x > 0 || y > 0) // true if either
digitalWrite(D3, LOW); // expression is true
}
delay(10); Logical NOT:>>> if (x= ! 0) // true only if
} // expression is false
ESP8266 AS A SERVER OR
ACCESS POINT
#include <ESP8266WiFi.h>
#include <ESP8266WiFi.h>
WiFiServer server(80);//initializing server on port 80
WiFiServer server(80);
Port 80 is the port number assigned to commonly used internet
void setup() communication protocol, Hypertext Transfer Protocol (HTTP). It is
{ the port from which a computer sends and receives Web client-based
WiFi.mode(WIFI_AP); communication and messages from a Web server and is used to send and
receive HTML pages or data.
WiFi.softAP("man","12345678");
void setup() {
server.begin();
// put your setup code here, to run once:
Serial.begin(115200); WiFi.mode(WIFI_AP);//AP means access point
IPAddress HTTPS_ServerIP WiFi.softAP("man","12345678"); // 1st is SSID and 2nd is its password
=WiFi.softAPIP(); server.begin(); //Server starts as access point in port 80
Serial.print("server IP is :"); Serial.begin(115200);// starts serial monitor to communication
Serial.println(HTTPS_ServerIP); IPAddress HTTPS_ServerIP =WiFi.softAPIP(); //obtain ip of server
} Serial.print("server IP is :");
void loop() Serial.println(HTTPS_ServerIP);
{ }
// put your main code here, to void loop() {
run repeatedly: // put your main code here, to run repeatedly:
}
void loop()
{
WiFiClient client=server.available(); WiFiClient client=server.available();
if(!client) //If wifi is connected to the server
{ esp8266 from mobile it will be available for
connection to esp server
return;
if(!client)// if not connected leave
}
{ return; }
Serial.println("somebody connected:");
Serial.println("somebody connected:");
}
//Displays the connection
}
void loop()
{
WiFiClient client=server.available();
if(!client)
{
return;
} String request=client.readString();
Serial.println("somebody connected:"); //Read what the browser has sent into a
String class and print the request to the
String request=client.readString();
monitor.
Serial.println(request);
Serial.println(request);
}
//displays in serial monitor the feed from
client
void loop()
{
WiFiClient client=server.available();
if(!client)
{
String request=client.readStringUntil('\r');
return; //reads only what is being send.
}
Things to send should be typed as
Serial.println("somebody connected:"); IP address/name (eg. 192.168.4.1/manee)
String request=client.readStringUntil('\r');
Serial.println(request); Serial.println(request);
// displays what is send from the browser
} As “ GET /manee HTTP/1.1 “ format
Serial.println("somebody connected:");
String request=client.readStringUntil('\r');
//reads only what is being send
Serial.println(request);
//// Handle the Request
if(request.indexOf("/OFF")!=-1)
// if client gives “192.168.4.1/OFF“, this command executes the command
{
digitalWrite(LED_BUILTIN,HIGH);
}
else if(request.indexOf("/ON")!=-1)
// if client gives “192.168.4.1/ON“, this command executes the command

{
digitalWrite(LED_BUILTIN,LOW);
//prepare the HTML document to responds and add button:
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+="<br><input type=\"button\"name=\"b1\"value=\"Turn LED ON\"onclick=\"location.href='/ON'\">";
//button is created and it contains text Turn LED ON when clicked address changes to 192.168.4.1/ON
s+="<br><br><br>"; // for spacing
s+="<br><input type=\"button\"name=\"b1\"value=\"Turn LED OFF\"onclick=\"location.href='/OFF'\">";
//button is created and it contains text Turn LED ON when clicked address changes to 192.168.4.1/ON
s+="</html>\n";
//Serve the HTML document to the browser.
client.flush(); //clear previous info in the stream
client.print(s); // Send the response to the client
delay(1);
Serial.println("Client disonnected"); //Looking under the hood
}
using an external WiFi modem to Control your
device
#include <ESP8266WiFi.h>
const char* ssid = "TP-LINK_472528"; //type your ssid
const char* password = "9961880990"; //type your password
int ledPin = LED_BUILTIN; // GPIO2 of ESP8266
WiFiServer server(80); //Service Port

void setup()
{
Serial.begin(115200);
delay(10);
pinMode(LED_BUILTIN, OUTPUT);
// Connect to WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
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());
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);

if (request.indexOf("/LED=ON") != -1)
{
digitalWrite(LED_BUILTIN, HIGH);
}
if (request.indexOf("/LED=OFF") != -1)
{
digitalWrite(LED_BUILTIN, LOW);
}
• // Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // importent
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("Click <a href=\"/LED=ON\">here turn the LED on pin 2 ON<br></a>");
client.println("Click <a href=\"/LED=OFF\">here turn the LED on pin 2 OFF<br></a>");
client.println("</html>");
client.flush(); //clear previous info in the stream
delay(1);
Serial.println("Client disconnected");
}
// Getting response to display
int value = LOW;
if (request.indexOf("/LED=ON") != -1) { digitalWrite(LED_BUILTIN, HIGH);
value = HIGH;
}
if (request.indexOf("/LED=OFF") != -1) { digitalWrite(LED_BUILTIN, LOW);
value = LOW;
}
…………………………………………………………..
client.println("<html>");
client.print("Led pin is now: ");
if(value == HIGH) {
client.print("On");
} else {
client.print("Off");
}
USING AN APP TO CONTROL
YOUR DEVICE (LOCAL AREA)
INTRODUCTION
• MIT App Inventor is a web-based tool for building
Android apps
• This is often referred to as visual programming,
• means the user is able to perform programming tasks
without entering any computer code.
• allows all sorts of people to program their phones using
a visual environment that involves
• snapping together color-coded instruction blocks
Lets Get Started
• Go to http://ai2.appinventor.mit.edu
• Select the Create button in the top right corner of the page:

• If you have a gmail account


• then login or create a new one
Select the New Project… button near the top
left corner of the page

• Give your project a name press OK.


Component Designer
Designer Window
• 5 Window Panes,
• Viewer, Palette, Components, Media, Properties
• VIEWER- is in the center, this is your “phone”
• You place and arrange components here
• Palette- collection of components that you may place in the viewer
• Components- lists all of the components in your project, default
component Screen1
• Media- adds media and lists all media uploaded
• Properties- refer to the properties of a specific component
Add A Label
• From the Palette, (Basic), drag a Label Component to the
Viewer Pane
• Check the Viewer to see the Label
• Examine the Components Pane
• You now have 2 components, Screen1, Label1
• (note that you may rename your components
• Properties Pane
• Change the Text
• Change the BackgroundColor
• Change the TextColor
• Change the size etc..
Connect your USB Phone
• Build apps with an Android device and WiFi Connection
• MIT App Inventor Companion app on your Android phone or tablet
• Don’t have an Android device? Use the Emulator
• emulator or the USB cable requires the use of a program named aiStarter. &
MIT App Inventor Companion app
• No WiFi? Build apps with an Android device and USB Cable
• USB cable requires the use of a program named aiStarter.
• On your Android device, go to System Settings-> Developer Options-> turn
them on, and be sure that "USB Debugging" is allowed.
• Developer options is hidden by default for some mobiles
• . To make it available, go to Settings -> About phone and tap Build number
seven times. Return to the previous screen to find Developer options,
including "USB Debugging".
Blocks Editor to tell your app
Switch
what to do!
BUTTON & LABEL
BLYNK
//Include the library files
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#define BLYNK_TEMPLATE_ID "TMPLUR87QHQv"
#define BLYNK_DEVICE_NAME "abc"
#define BLYNK_AUTH_TOKEN
"jyiXDh2nTAMzcuvrGxZgNztEjFuMWgzz"
char auth[] = BLYNK_AUTH_TOKEN;//Enter your Auth token
char ssid[] = "ASWATHY";//Enter your WIFI name
char pass[] = "04712410714";//Enter your WIFI password
BlynkTimer timer;
#define relay1 D7
#define relay2 D8
void setup() {
Serial.begin(9600);
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
digitalWrite(relay1, HIGH);
digitalWrite(relay2, HIGH);
Blynk.begin(auth, ssid, pass, "blynk.cloud", 80);
delay(4000);
}
//Get buttons values
BLYNK_WRITE(V1) {
bool RelayOne = param.asInt();
if (RelayOne == 1) {
digitalWrite(relay1, LOW);
} else {
digitalWrite(relay1, HIGH);
}
}

//Get buttons values


BLYNK_WRITE(V2) {
bool RelayTwo = param.asInt();
if (RelayTwo == 1) {
digitalWrite(relay2, LOW);
} else {
digitalWrite(relay2, HIGH);
}
}

void loop() {
Blynk.run();//Run the Blynk library
timer.run();//Run the Blynk timer
}
BLYNK_WRITE(V2) {
bool RelayTwo = param.asInt();
if (RelayTwo == 1) {
digitalWrite(relay2, LOW);
Blynk.virtualWrite(V3, 0);
} else {
digitalWrite(relay2, HIGH);
Blynk.virtualWrite(V3, 1);

}
}
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
char auth[] = "893aa5cb24a64a3db959ab99c01b75bd";
char ssid[] = "belkin.F04";
char pass[] = "maneesht"; Write to on/off
// This function will be called every time Slider Widget
// in Blynk app writes values to the Virtual Pin V1
BLYNK_WRITE(D0)
{
int pinValue = param.asInt(); // assigning incoming value from pin V1 to a variable
// process received value
}
void setup()
{
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
}
void loop()
{
Blynk.run();
}
• Blynk.virtualWrite(pin, "abc");
• Send data from app to hardware
• BLYNK_WRITE(V1) //Button Widget is writing to pin V1
•{
• int pinData = param.asInt();
•}
• Get data from hardware
• Perform requests by Widget
• BLYNK_READ(V5) // Widget in the app READs Virtal Pin V5 with the
certain frequency
• {
• // This command writes Arduino's uptime in seconds to Virtual Pin V5
• Blynk.virtualWrite(5, millis() / 1000);
•}
• Pushing data from hardware
#include <SPI.h>
#include <Ethernet.h>
#include <BlynkSimpleEthernet.h>
char auth[] = "YourAuthToken"; // Put your token here
BlynkTimer timer; // Create a Timer object called "timer"!
void setup()
{
Serial.begin(9600);
Blynk.begin(auth);
timer.setInterval(1000L, sendUptime);
// Here you set interval (1sec) and which function to call
}
void sendUptime()
{ // This function sends Arduino up time every 1 second to Virtual Pin (V5) //
In the app, Widget's reading frequency should be set to PUSH //
You can send anything with any interval using this construction //
Don't send more that 10 values per second
Blynk.virtualWrite(V5, millis() / 1000);
}
void loop()
{ Blynk.run(); // all the Blynk magic happens here
timer.run(); // BlynkTimer is working...
}
State syncing
For hardware
• If your hardware looses Internet connection or resets, you can restore all the values
from Widgets in the Blynk app.
• BLYNK_CONNECTED()
•{
• Blynk.syncAll();
• } //here handlers for sync command
• BLYNK_WRITE(V0)
• { ....
• }
• For app
• Blynk.virtualWrite
• LED
• WidgetLED led1(V1); //register to virtual pin 1
• led1.off();
• led1.on();

• WidgetLED led2(V2);
• led2.setValue(127); //set brightness of LED to 50%.
• LCD
• lcd.print(x, y, "Your Message");//Where x is a symbol position (0-15), y
is a line number (0 or 1),
• lcd.clear();
GPS Trigger
• BLYNK_WRITE(V1) GPS trigger widget allows easily trigger
• { events when you arrive to or leave from
some destination.
• int state = param.asInt();
This widget will work in
• if (state) background and periodically will check
• { //You enter destination your coordinates. In case your location is
within/out required radius
• }
(selected on widget map) widget
• else will send HIGH/LOW command to hardware.
• {
• //You leave destination
• }
• }
GPS Streaming

• In order to accept data from this widget you need to :


• BLYNK_WRITE(V1)
• { float latitude = param[0].asFloat(); Useful for monitoring smartphone
• float longitude = param[1].asFloat(); location data such as latitude,
longitude, altitude and speed
• float altitude = param[2].asFloat();
(speed could be often 0
• float speed = param[3].asFloat(); in case smartphone
•} doesn’t support it).
or you can use prepared
wrapper GpsParam :

• BLYNK_WRITE(V1)
•{
• GpsParam gps(param); // Print 6 decimal places for Lat
Serial.println(gps.getLat(), 7);
• Serial.println(gps.getLon(), 7);
• Serial.println(gps.getAltitude(), 2);
• Serial.println(gps.getSpeed(), 2);
•}
USING AN APP & FIREBASE TO
CONTROL YOUR DEVICE (WEB
CONECTION)
FIREBASE
SETTINGS
•Visit https://console.firebase.google.com/

and login with your Google account.


•You will see the welcome screen with two buttons
as shown below:
• Click on the Database link on the left.
Click on Publish. This will publish
(associate) the rules with your database
Settings tab

Users and Permissions


Service accounts-1

Database Secrets
Note this Secret Code
Setting App inventor
• Go to App inventor site and sign in using your Google account
• Start a new Project
Create front
Screen using
Button and
Properties
Add Experimental
firebaseDB

Paste the
Firebase token
and FirebaseURL
to firebaseDB
Properties
Blocks Tab

Add Blocks to
store firebase
data when
Buttons are
clicked
Install Required Libraries for Firebase settings.

Arduino Settings
In Examples Select Code Beginners_start_here
Add the Required datas
Change all Int to String
And int to string to
make the match the
data send from app
inventor

Write required program


in loop and Run the
program

You might also like