[go: up one dir, main page]

0% found this document useful (0 votes)
486 views63 pages

IOE - Lab Manual

This document describes an experiment using an Arduino board to interface an LED, push button, and light dependent resistor (LDR) sensor. The circuit diagrams and code are provided to turn on an LED when the push button is pressed or when the LDR sensor detects light. An LDR sensor's resistance changes with light intensity, allowing it to be used for light sensing applications. The experiment aims to familiarize students with basic input and output components like buttons, sensors and LEDs on the Arduino platform.

Uploaded by

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

IOE - Lab Manual

This document describes an experiment using an Arduino board to interface an LED, push button, and light dependent resistor (LDR) sensor. The circuit diagrams and code are provided to turn on an LED when the push button is pressed or when the LDR sensor detects light. An LDR sensor's resistance changes with light intensity, allowing it to be used for light sensing applications. The experiment aims to familiarize students with basic input and output components like buttons, sensors and LEDs on the Arduino platform.

Uploaded by

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

FACULTY OF ENGINEERING AND TECHNOLOGY

BACHELOR OF TECHNOLOGY

COMPUTER SCIENCE AND ENGINEERING

INTERNET OF EVERYTHING LABORATORY


203105306

5TH SEMESTER

Laboratory Manual
CERTIFICATE

This is to certify that

Mr./Ms Sai Harsha Vardhan Ghantasala

with enrolment no 190303105391 has

successfully completed his/her laboratory experiments in the

INTERNET OF EVERYTHING
LABORATORY
(203105306) from the department

Of Computer science & Engineering

during the academic year 2021-2022

Date of Submission: ......................... Staff In charge: ...........................

Head of Department: ...........................................


Practical - 1

Familiarization with Arduino and perform necessary software


installation.

Theory :
What is Arduino?

 Arduino is an open-source electronics platform based on easy-to-use


hardware and software. Arduino boards are able to read inputs - light on
a sensor, a finger on a button, or a Twitter message - and turn it into an
output - activating a motor, turning on an LED, publishing something
online.
Why we are use Arduino?

 The Arduino Uno R3 is a microcontroller board based on a removable,


dual-inline-package (DIP) ATmega328 AVR microcontroller. It has 20
digital input/output pins (of which 6 can be used as PWM outputs and 6
can be used as analog inputs). Programs can be loaded on to it from the
easy-to-use Arduino computer program.

190303105391 1|Page
Specification of Arduino :

Microcontroller ATmega328P – 8 bit AVR family


microcontroller

Operating Voltage 5V

Recommended Input 7-12V


Voltage

Input Voltage Limits 6-20V

Analog Input Pins 6 (A0 – A5)

Digital I/O Pins 14 (Out of which 6 provide PWM output)

DC Current on I/O Pins 40 mA

DC Current on 3.3V Pin 50 mA

Flash Memory 32 KB (0.5 KB is used for Bootloader)

SRAM 2 KB

EEPROM 1 KB

Frequency (Clock Speed) 16 MHz

Application of Arduino :

 Prototyping of Electronics Products and Systems


 Multiple DIY Projects.
 Easy to use for beginner level DIYers and makers.
 Projects requiring Multiple I/O interfaces and communications.

190303105391 2|Page
Pin description :

Pin Category Pin Name Details


Vin: Input voltage to Arduino when using an
external power source.
5V: Regulated power supply used to power
microcontroller and other components on
Power Vin, 3.3V, 5V, GND the board.
3.3V: 3.3V supply generated by on-board
voltage regulator. Maximum current draw is
50mA.
GND: ground pins.
Reset Reset Resets the microcontroller.
Used to provide analog input in the range of
Analog Pins A0 – A5
0-5V
Input/Output
Digital Pins 0 – 13 Can be used as input or output pins.
Pins
Serial 0(Rx), 1(Tx) Used to receive and transmit TTL serial data.
External
2, 3 To trigger an interrupt.
Interrupts
PWM 3, 5, 6, 9, 11 Provides 8-bit PWM output.
10 (SS), 11 (MOSI),
SPI 12 (MISO) and 13 Used for SPI communication.
(SCK)
Inbuilt LED 13 To turn on the inbuilt LED.
TWI A4 (SDA), A5 (SCA) Used for TWI communication.
To provide reference voltage for input
AREF AREF
voltage.

190303105391 3|Page
Programming Arduino
Once arduino IDE is installed on the computer, connect the board with
computer using USB cable. Now open the arduino IDE and choose the correct
board by selecting Tools>Boards>Arduino/Genuino Uno, and choose the
correct Port by selecting Tools>Port. Arduino Uno is programmed using
Arduino programming language based on Wiring. To get it started with Arduino
Uno board and blink the built-in LED, load the example code by selecting
Files>Examples>Basics>Blink. Once the example code (also shown below) is
loaded into your IDE, click on the ‘upload’ button given on the top bar. Once
the upload is finished, you should see the Arduino’s built-in LED blinking. 
Below is the example code for blinking:

// the setup function runs once when you press reset or power the board
void setup()
{
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever


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

Download the Arduino Software (IDE)


Get the latest version from the download page. You can choose between the
Installer (.exe) and the Zip packages. We suggest you use the first one that
installs directly everything you need to use the Arduino Software (IDE),
including the drivers. With the Zip package you need to install the drivers
manually. The Zip file is also useful if you want to create a portable installation.

190303105391 4|Page
When the download finishes, proceed with the installation and please allow
the driver installation process when you get a warning from the operating
system.

Choose the components to install

Choose the installation directory (we suggest to keep the default one)

190303105391 5|Page
The process will extract and install all the required files to execute properly the
Arduino Software (IDE)

Proceed with board specific instructions


When the Arduino Software (IDE) is properly installed you can go back to
the Getting Started Home and choose your board from the list on the right of
the page.

Practical - 2

190303105391 6|Page
To interface LED/Burzer with Arduino/Raspberry Pi and write a
program to turn “ON LED” for 1sec after every 2 seconds.

Component :
An Arduino board and a LED.

Theory :
I am selected the Arduino Uno board for this practical after selecting the board
I have selected a normal LED and placed it on the board. Anode at pin no. 13
and cathode at GND. After completion of circuit write some code in code
section for output. And Connect the board with USB.

Circuit Diagram :

Code :
void setup()
{
pinMode(10, OUTPUT);
}
void loop()
{
digitalWrite(10, HIGH);
delay(1000); // Wait for 1000 millisecond(s)

190303105391 7|Page
digitalWrite(10, LOW);
delay(2000); // Wait for 1000 millisecond(s)
}

Output :

Conclusion :

LED in Circuit diagram turn on for 1 sec and turn off for 2 sec.

Practical - 3

To interface Push button/Digital sensor (IR/LDR) with Arduino /


Raspberry Pi and write a program to turn ON LED when push button
is pressed or at sensor detection.
Description :

Material Used :

190303105391 8|Page
 Arduino Uno Rev3
 Breadboard
 LED
 Resistors
 Pushbutton/LDR Sensor

What is an LDR Sensor ?


An LDR Sensor Module has a (variable) resistance that changes with the light
intensity that falls upon it. This allows them to be used in light sensing circuits.
It’s provide analog reading/ value to IOT Device. It can directly upload reading
to icloud using nutty Engineer’s IOT device.

Light dependent resistors, LDRs or photoresistors fall into one of two types or
categories:

 Intrinsic photoresistors :  


Intrinsic photoresistors use undoped semiconductor materials including
silicon or germanium. Photons fall on the LDR excite electrons moving them
from the valence band to the conduction band. As a result, these electrons
are free to conduct electricity. The more light that falls on the device, the
more electrons are liberated and the greater the level of conductivity, and
this results in a lower level of resistance.

 Extrinsic photoresistors :  


Extrinsic photoresistors are manufactured from semiconductor of materials
doped with impurities. These impurities or dopants create a new energy
band above the existing valence band. As a
result, electrons need less energy to transfer to the conduction band
because of the smaller energy gap.

 Push-button :
The push button is a digital button that can easily be used with
microcontrollers like ESP8266, Arduino, etc. The button sends digital signals
to the microcontroller, and it sends the value '0' whenever it is pressed.

 Resistor :
190303105391 9|Page
A resistor is a passive two terminal electrical component that
implements electrical resistance as a circuit element. In electronic circuits,
resistors are used to reduce current flow, adjust signal levels, to divide
voltages, bias active elements, and terminate transmission lines, among
other uses.

 Arduino Uno Board :


The Arduino Uno is an open-source microcontroller board based on
the Microchip ATmega328P microcontroller and developed
by Arduino.cc. The board is equipped with sets of digital and
analog input/output (I/O) pins that may be interfaced to various expansion
boards (shields) and other circuits. The board has 14 digital I/O pins (six
capable of PWM output), 6 analog I/O pins, and is programmable with
the Arduino IDE (Integrated Development Environment), via a type B USB
cable. It can be powered by the USB cable or by an external 9-volt battery,
though it accepts voltages between 7 and 20 volts. 

 Breadboard :
A breadboard is a solderless device for temporary prototype with
electronics and test circuit designs. Most electronic components in
electronic circuits can be interconnected by inserting their leads or
terminals into the holes and then making connections through wires where
appropriate.

 LED :
A light-emitting diode (LED) is a semiconductor light source that emits light
when current flows through it. Electrons in the semiconductor recombine
with electron holes, releasing energy in the form of photons. The color of
the light (corresponding to the energy of the photons) is determined by the
energy required for electrons to cross the band gap of the
semiconductor. White light is obtained by using multiple semiconductors or
a layer of light-emitting phosphor on the semiconductor device.
Circuit Diagram :

190303105391 10 | P a g e
Pushbutton: Unpressed

PIR : No Motion in range

Program :

(A) PushButton :

Code :
int buttonState=0;
void setup()
{
pinMode(2,INPUT);
pinMode(13,OUTPUT);

190303105391 11 | P a g e
}
void loop()
{
buttonState = digitalRead(2); //if button is pressed then LED should bilnk
if(buttonState == HIGH) // LED IS ON
digitalWrite(13,HIGH);
else // LED IS OFF
digitalWrite(13,LOW);
}

Output :

Pushbutton pressed
(B) PIR Sensor :

Code :
int state=LOW; //State of LED
int val=0; //State of Sensor
void setup()
{
pinMode(13,OUTPUT);
pinMode(2,INPUT);
Serial.begin(9600);
}
void loop()
{
val=digitalRead(2);

190303105391 12 | P a g e
if(val==HIGH)
{
digitalWrite(13,HIGH);
if(state==LOW)
{
Serial.print("Motion Detected");
state=HIGH;
}
}
else
{
digitalWrite(13,LOW);
if(state==HIGH)
{
Serial.print("Motion Stopped");
state=LOW;
}
}
}

Output :

Motion in range

190303105391 13 | P a g e
Conclusion :

LED get turned “ON” when Pushbutton is pressed in circuit A whereas in circuit
when there will be any motion in the sensor range only.

LED get turned “OFF” when Pushbutton is not pressed in circuit A whereas in
circuit when there will be no motion in the sensor range only.

Practical - 4
To interface DHT11 sensor with Arduino/Raspberry Pi and write a program to
print temperature and humidity readings.

Description :

Material Used :
 Arduino Uno Rev3
 Temperature Sensor

Arduino Uno Board :


The Arduino Uno is an open-source microcontroller board based on
the Microchip ATmega328P microcontroller and developed by Arduino.cc. The

190303105391 14 | P a g e
board is equipped with sets of digital and analog input/output (I/O) pins that
may be interfaced to various expansion boards (shields) and other circuits. The
board has 14 digital I/O pins (six capable of PWM output), 6 analog I/O pins,
and is programmable with the Arduino IDE (Integrated Development
Environment), via a type B USB cable. It can be powered by the USB cable or by
an external 9-volt battery, though it accepts voltages between 7 and 20 volts. 

Temperature Sensor :
The DHT22 is a low voltage, precision centigrade temperature sensor. It
provides a voltage output that is linearly proportional to the Celsius
temperature. It also doesn't require any external calibration to provide typical
accuracies of ±24°C at humidity 40% temperature range. 

Circuit Diagram :

Program :

#include<DHT.h>
#define DHTPIN 7
#define DHTTYPE DHT22
DHT dht(DHTPIN,DHTTYPE);
float hum,temp;//Variable

190303105391 15 | P a g e
void setup() 
{
  Serial.begin(9600);
  dht.begin();
}
void loop()
{
  float hum=dht.readHumidity();
  float temp=dht.readTemperature();
  Serial.println("\nTemperature : ");
  Serial.print(temp);
  Serial.print("°C ");
  Serial.print("\nHumidity : ");
  Serial.print(hum);
  delay(3000);
}

Output :

Conclusion :
Hence, we have completed the experiment for printing temperature and
humidity readings using the temperature sensor.

190303105391 16 | P a g e
Practical - 5

To interface motor using relay with Arduino and write a program to


turn on motor when push button is pressed.

Description :

Component Used :
 Arduino Uno Rev3
 Breadboard
 DC motor
 Push Button
 2 x Battery (9 Volt)
 2 x NPN Transistor
 2 x Realy

Theory :
For this practical I have selected an Arduino with push button, DC motor,
2 NPN transistor, 2 batteries of 9V and 2 relay SPDT. I have arranged NPN
transistor and relay accordingly on the breadboard. The negative terminal
of DC motor is connected with both relays at terminal 7 respectively.

190303105391 17 | P a g e
Terminal 5 of both relays is connected to positive terminal of breadboard.
The positive terminal of breadboard is further connected with Arduino
and given 5V of power. The GND terminal of Arduino is connected to
negative terminal of breadboard. The collector terminal of both transistor
is connected to negative terminal of breadboard. The base terminal of
both transistor is connected to digital pins of Arduino at -11 and 8
respectively. The emitter of each the transistor is connected to terminal 8
of each relay. The positive terminal of battery(a) is connected to positive
terminal of DC motor and the negative terminal is connected to terminal
12 of one relay. The positive terminal of battery(b) is connected to
terminal 12 of another relay. Terminal 5 of both the relays is connected
with positive terminal of breadboard.
Circuit Diagram :

Program :
#define CW 8
#define CCW 11
int buttonState = 0;
void setup()
{
pinMode(2, INPUT);
pinMode(CW, OUTPUT);
pinMode(CCW, OUTPUT);
}

190303105391 18 | P a g e
void loop()
{
buttonState = digitalRead(2); // read the state of the pushbutton value
/* check if pushbutton is pressed. If it is, the buttonState is HIGH motor turns
on */
if (buttonState == HIGH)
{
digitalWrite(CW, HIGH); // motor runs clockwise
delay(2000);
digitalWrite(CCW, HIGH); // motor runs counter clockwise
delay(2000);
}
else // motor turns off
{
digitalWrite(CW, LOW);
digitalWrite(CCW, LOW);
}
}

Output :

190303105391 19 | P a g e
Conclusion :

For the given circuit diagram the DC motor will rotate when the push button is
pressed.

Practical - 6

To interface OLED with Arduino/Raspberry Pi and write a program


to print temperature and humidity readings on it.
Component Used :
1. DHT22 : DHT22 output calibrated digital signal. It utilizes exclusive
digital-signal-collecting-technique and humidity sensing technology,
assuring its reliability and stability. Its sensing elements is connected
with 8-bit single-chip computer. Every sensor of this model is
temperature compensated and calibrated in accurate calibration
chamber and the calibration-coefficient is saved in type of programme in
OTP memory, when the sensor is detecting, it will cite coefficient from
memory. Small size & low consumption & long transmission
distance(20m) enable DHT22 to be suited in all kinds of harsh application
occasions.

2. Arduino: Arduino is an open-source hardware and software company,


project and user community that designs and manufactures single-board
microcontrollers and microcontroller kits for building digital devices.

Circuit Diagram :

190303105391 20 | P a g e
Program :
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#define DHTPIN 7
#define DHTTYPE DHT22
DHT dht(DHTPIN,DHTTYPE);
Adafruit_SSD1306 display(4);
void setup()
{
Serial.begin(9600);
dht.begin();
display.begin(SSD1306_SWITCHCAPVCC,0X3C);
display.clearDisplay();
display.display();
}
void loop()
{
float hum,temp;
hum=dht.readHumidity();
temp=dht.readTemperature();
display.clearDisplay();
display.setTextColor(WHITE);
display.setCursor(20,0);
display.print("todays weather");
display.setCursor(0,15);
display.print("temprature=");
display.print(temp);
display.setCursor(5,25);
display.print("humidity=");
display.print(hum);
display.display();
}

190303105391 21 | P a g e
Output :

Conclusion :

For the given circuit diagram in the project display temperature and humidity
is changing when its changes.

190303105391 22 | P a g e
Practical - 7

To interface Bluetooth with Arduino/Raspberry Pi and write a


program to send sensor data to smartphone using Bluetooth
reading on it.
Component Used :
3. DHT22 : DHT22 output calibrated digital signal. It utilizes exclusive
digital-signal-collecting-technique and humidity sensing technology,
assuring its reliability and stability. Its sensing elements is connected
with 8-bit single-chip computer. Every sensor of this model is
temperature compensated and calibrated in accurate calibration
chamber and the calibration-coefficient is saved in type of programme in
OTP memory, when the sensor is detecting, it will cite coefficient from
memory. Small size & low consumption & long transmission
distance(20m) enable DHT22 to be suited in all kinds of harsh application
occasions. Single-row packaged with four pins, making the connection
very convenient.
4. Arduino: Arduino is an open-source hardware and software company,
project and user community that designs and manufactures single-board
microcontrollers and microcontroller kits for building digital devices.
5. Bluetooth HC-05 : The HC-05 is a very cool module which can add two-
way (full-duplex) wireless functionality to your projects. You can use this
module to communicate between two microcontrollers like Arduino or
communicate with any device with Bluetooth functionality like a Phone
or Laptop. There are many android applications that are already
available which makes this process a lot easier.
6. DHT11 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). Its fairly simple to use,
but requires careful timing to grab data.

190303105391 23 | P a g e
Circuit Diagram :

Program :
#include <DHT.h>
#include <DHT_U.h>
#include <SoftwareSerial.h>
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
SoftwareSerial BTSerial(4,5);
void setup()
{
String setName = String("AT+NAME=MyBTBee\r\n"); //Setting name as
'MyBTBee'
Serial.begin(9600);
dht.begin();
BTSerial.begin(38400);
BTSerial.print("AT\r\n"); //Check Status
delay(500);
while (BTSerial.available())
{
Serial.write(BTSerial.read());
}
BTSerial.print(setName); //Send Command to change the name

190303105391 24 | P a g e
delay(500);
while (BTSerial.available())
{
Serial.write(BTSerial.read());
}
}
void loop()
{
char c;
if(Serial.available())
{
c = Serial.read();
if(c=='t')
readSensor();
}
}
void readSensor()
{
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("\n Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
}

Output :

190303105391 25 | P a g e
Conclusion :

For the given circuit diagram the we change the temperature and it reflect in
phone using Bluetooth.

190303105391 26 | P a g e
Practical - 8

To interface Bluetooth with Arduino Uno and write a program to


turn LED ON/OFF when ‘1’/’0’ is received from smartphone using
Bluetooth.
Component Used :
1. DHT22 : DHT22 output calibrated digital signal. It utilizes exclusive
digital-signal-collecting-technique and humidity sensing technology,
assuring its reliability and stability. Its sensing elements is connected
with 8-bit single-chip computer. Every sensor of this model is
temperature compensated and calibrated in accurate calibration
chamber and the calibration-coefficient is saved in type of programme in
OTP memory, when the sensor is detecting, it will cite coefficient from
memory. Small size & low consumption & long transmission
distance(20m) enable DHT22 to be suited in all kinds of harsh application
occasions. Single-row packaged with four pins, making the connection
very convenient.

2. Arduino: Arduino is an open-source hardware and software company,


project and user community that designs and manufactures single-board
microcontrollers and microcontroller kits for building digital devices.

3. Bluetooth HC-05 : The HC-05 is a very cool module which can add two-
way (full-duplex) wireless functionality to your projects. You can use this
module to communicate between two microcontrollers like Arduino or
communicate with any device with Bluetooth functionality like a Phone
or Laptop. There are many android applications that are already
available which makes this process a lot easier.

4. LED-RED : In the simplest terms, a light-emitting diode (LED) is a


semiconductor device that emits light when an electric current is passed
through it. Light is produced when the particles that carry the current
(known as electrons and holes) combine together within the
semiconductor material.

190303105391 27 | P a g e
Program :
String voice;
void setup()
{
pinMode(13,OUTPUT);
Serial.begin(9600);
}
void loop()
{
while (Serial.available())
{
delay(10);
char c=Serial.read();
voice += c;
}
if (voice.length() > 0)
{
Serial.println(voice);
if(voice=="on")
{
digitalWrite(13,HIGH);
}
if(voice=="off")
{
digitalWrite(13,LOW);
}
voice="";
}
}

Circuit Diagram :

190303105391 28 | P a g e
Output :

Conclusion :
For the given circuit diagram the led gets turned ON/OFF using Bluetooth.

Practical - 9

Write a program on Arduino Uno to upload temperature data to


things peak cloud.

190303105391 29 | P a g e
Component Used :

1. Arduino :
Arduino is an open-source hardware and software company, project and
user community that designs and manufactures single-board
microcontrollers and microcontroller kits for building digital devices.

2. Resistor :
A passive electrical component with two terminals that are used for
either limiting or regulating the flow of electric current in electrical
circuits.The main purpose of resistor is to reduce the current flow and to
lower the voltage in any particular portion of the circuit. It is made of
copper wires which is coiled around a ceramic rod and the outer part of
the resistor is coated with an insulating paint.

3. Temperature Sensor (TMP36) :


The TMP36 is a low voltage, precision centigrade temperature sensor. It
provides a voltage output that is linearly proportional to the Celsius
temperature. It also doesn't require any external calibration to provide
typical accuracies of ±1°C at +25°C and ±2°C over the −40°C to +125°C
temperature range.

4. Wifi Module (ESP8266) :


The ESP8266 WiFi Module is a self contained SOC with integrated TCP/IP
protocol stack that can give any microcontroller access to your WiFi
network. The ESP8266 is capable of either hosting an application or
offloading all WiFi networking functions from another application
processor.
Circuit Diagram :

190303105391 30 | P a g e
Program :
String ssid = "Simulator Wifi"; // SSID to connect to
String password = ""; // Our virtual wifi has no password
String host = "api.thingspeak.com"; // Open Weather Map API
const int httpPort = 80;
String url= "/update?api_key=ICJL7U715L11M5TO&field1=";
int setupESP8266(void)
{
// Start our ESP8266 Serial Communication
Serial.begin(115200); // Serial connection over USB to computer
Serial.println("AT"); // Serial connection on Tx / Rx port to ESP8266
delay(10); // Wait a little for the ESP to respond
if (!Serial.find("OK")) return 1; // Connect to 123D Circuits Simulator Wifi
Serial.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");
delay(10); // Wait a little for the ESP to respond
if (!Serial.find("OK")) return 2; // Open TCP connection to the host:
Serial.println("AT+CIPSTART=\"TCP\",\"" + host + "\"," + httpPort);
delay(50); // Wait a little for the ESP to respond
if (!Serial.find("OK")) return 3;
return 0;
}
void anydata(void)
{
int temp = map(analogRead(A0),20,358,-40,125); // Construct our HTTP call
String httpPacket = "GET " + url + String(temp) + " HTTP/1.1\r\nHost: " + host
+ "\r\n\r\n";
int length = httpPacket.length(); // Send our message length
Serial.print("AT+CIPSEND=");

190303105391 31 | P a g e
Serial.println(length);
delay(10); // Wait a little for the ESP to respond
if (!Serial.find(">")) return -1; // Send our http request
Serial.print(httpPacket);
delay(10); // Wait a little for the ESP to respond
if (!Serial.find("SEND OK\r\n")) return;
}
void setup()
{
setupESP8266();
}
void loop()
{
anydata();
delay(100);
}

Output :

190303105391 32 | P a g e
Conclusion :
For the given circuit diagram the temperature vs time graph will show changes
in the temperature and time in peak cloud.

Practical - 10

Write a program on Arduino/Raspberry Pi to retrieve temperature


and humidity data from thingspeak cloud.
Theory :
ThingSpeak is an open source platform to store and retrieve a data for Internet
of Things application. To use this, you need to register in ThingSpeak cloud and
then login to your account. After create a new channel with temperature in
one field and humidity in another field as shown in Fig: 1.2. Once you created a
new channel, it will generate a two API keys, they are READ API keys and
WRITE API keys. First, copy the WRITE API keys from ThingsSpeak and paste it
into the line (String apiKey = "OX9T8Y9OL9HD0UBP";) of the program. Next,
replace the Host_Name and Password with your WiFi name and WiFi password
in the two lines given below in the program. (String Host_Name = "Pantech"
and String Password = "pantech123").

Circuit Diagram :

190303105391 33 | P a g e
Program :
% Template MATLAB code for reading data from a private channel, analyzing
% the data and storing the analyzed data in another channel.
% Prior to running this MATLAB code template, assign the channel variables.
% Set 'readChannelID' to the channel ID of the channel to read from. Since
% this is a private channel, also assign the read API Key to the 'readAPIKey'
% variable. You can find the read API Key on the right side pane of this page.
% To store the analyzed data, you will need to write it to a channel other
% than the one you are reading data from. Assign this channel ID to the
% 'writeChannelID' variable. Also assign the write API Key to the
% 'writeAPIKey' variable below. You can find the write API Key in the right
% side pane of this page.
% TODO - Replace the [] with channel ID to read data from:
readChannelID = 1*****9;
% TODO - Enter the Read API Key between the '' below:
readAPIKey = 'M************D';
% TODO - Replace the [] with channel ID to write data to:
writeChannelID = 1******0;
% TODO - Enter the Write API Key between the '' below:
writeAPIKey = 'V*************Z';
%% Read Data %%
data = thingSpeakRead(readChannelID, 'ReadKey', readAPIKey,'Fields',
[1],'NumDays',50,'OutputFormat','TimeTable')
%% Analyze Data %%
% Add code in this section to analyze data and store the result in the
% 'analyzedData' variable.
analyzedData = data;
%% Write Data %%
thingSpeakWrite(writeChannelID, analyzedData, 'WriteKey', writeAPIKey);

190303105391 34 | P a g e
Output :
data = 98×1 timetable

Timestamps Temperature
16-Jul-2021 09:39:29 24
16-Jul-2021 09:39:49 24
16-Jul-2021 09:40:21 -2
16-Jul-2021 09:42:55 -2
16-Jul-2021 09:43:33 75
16-Jul-2021 09:44:17 75
16-Jul-2021 09:44:39 75
16-Jul-2021 09:45:47 75
16-Jul-2021 09:48:50 75
16-Jul-2021 09:56:29 75
. .
. .

190303105391 35 | P a g e
From Channel - 1

Conclusion :

For the given circuit diagram the temperature vs time graph will show changes
in the temperature and time in peak cloud.

Practical - 11

To install MySQL database on Raspberry Pi and perform basic SQL


queries.

How to install MYSQL database on raspberry pi


Please follow the following steps to know how to install MYSQL server on
raspberry pi or to know how to install MariaDB server on raspberry pi.

1) Please open the raspberry pi terminal.

2)Execute the following command to update the existing packages.

sudo apt-get update

3)Now execute the following to install MySQL server which is shown below.
While installing if it is asking do you want to continue then please enter y and
hit enter

190303105391 36 | P a g e
sudo apt-get install mysql-server

4)Now please execute the following command for secure installation which is
shown below.

sudo mysql_secure_installation

5)Please hit Enter for current root password.

190303105391 37 | P a g e
6)Now please Enter y and hit Enter for setting a new password which is shown
below

7)Now Please enter New password which is shown below

8)Now please enter y to remove anonymous user and hit Enter.

190303105391 38 | P a g e
9)Now please enter y to disallow remote login which is shown below

10)Please enter y to remove test databases which is shown below

11)Please enter y to reload privileges tables which is shown below

1
2)Now please execute the following command to login into the database and
Enter the password which you have entered in step 7.

sudo mysql -u root -p

1
3)Please execute the following command to see databases present in the
mysql database.

190303105391 39 | P a g e
show databases;

14)Execute the following to create Demo database in mysql server which is


shown below.

CREATE DATABASE Demo;

1
5)Now please execute the following to go in Demo database

USE Demo;

16)Please execute the following command to create database user

CREATE USER ‘admin’@’localhost’ IDENTIFIED BY ‘admin’;

17)Execute the following command to grant all previleges

GRANT ALL PRIVILEGES ON Demo.* TO ‘admin’@’localhost’;

190303105391 40 | P a g e
18)Now execute the following command save all the changes

FLUSH PRIVILEGES;

19)Now please execute the following command to come out of database.

quit

20)E
xecute the following command to restart the MYSQL server

sudo service mysql restart

How
to insert and fetch data from MySQL database

Please follow the following steps to insert and fetch from the MySQL database.
1)Open the raspberry pi terminal

2)Execute the following command to login to the database and enter the
password which is shown below.

sudo mysql -u root -p

190303105391 41 | P a g e
3)Execute the following command to use Demo database which is shown
above.

USE Demo;

4)Execute the following command to create login table which has two coloums
i.e is username and password which is shown above.

create table login(username varchar(25), password varchar(25));

5)Execute the following command to insert data into login table which is
shown below.

insert into login values(‘admin’,’admin123′);

6)
To see the inserted values please execute the following command which is
shown bel

select * from login;

190303105391 42 | P a g e
Practical - 12
Write a program on Arduino/Raspberry Pi to publish temperature
data to MQTT broker.

Circuit configuration :

Code :
#include <SimpleDHT.h> // Data ---> D3 VCC ---> 3V3 GND ---> GND

#include <ESP8266WiFi.h>

#include "Adafruit_MQTT.h"

#include "Adafruit_MQTT_Client.h"

// WiFi parameters

190303105391 43 | P a g e
#define WLAN_SSID "Samsung M51"

#define WLAN_PASS "12345678"

// Adafruit IO

#define AIO_SERVER "io.adafruit.com"

#define AIO_SERVERPORT 1883

#define AIO_USERNAME "iggggviffdsshgsvekk"

#define AIO_KEY "frghjklkjkghjghtrtyjkljkhjghfgfdh"

WiFiClient client;

Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT,


AIO_USERNAME, AIO_KEY);

Adafruit_MQTT_Publish Temperature = Adafruit_MQTT_Publish(&mqtt,


AIO_USERNAME "/feeds/Temperature");

int pinDHT11 = 0;

SimpleDHT11 dht11(pinDHT11);

byte hum = 0; //Stores humidity value

byte temp = 0; //Stores temperature value

void setup() {

Serial.begin(115200);

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

// Connect to WiFi access point.

Serial.println(); Serial.println();

190303105391 44 | P a g e
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();

// 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;

190303105391 45 | P a g e
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;

// Setup MQTT subscription for onoff & slider feed.

mqtt.subscribe(&slider);

if(ret >= 0)

mqtt.disconnect();

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

delay(10000);

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

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

dht11.read(&temp, &hum, NULL);


190303105391 46 | P a g e
Serial.print((int)temp); Serial.print(" *C, ");

Serial.print((int)hum); Serial.println(" H");

delay(5000);

if (! Temperature.publish(temp)) { //Publish to Adafruit

Serial.println(F("Failed"));

if (! Humidity.publish(hum)) { //Publish to Adafruit

Serial.println(F("Failed"));

else {

Serial.println(F("Sent!"));

Adafruit_MQTT_Subscribe *subscription;

while ((subscription = mqtt.readSubscription(5000))) {

// check if its the slider feed

if (subscription == &slider) {

Serial.print(F("Slider: "));

Serial.println((char *)slider.lastread);

uint16_t sliderval = atoi((char *)slider.lastread); // convert to a number

//analogWrite(PWMOUT, sliderval);

190303105391 47 | P a g e
Output :

190303105391 48 | P a g e
Practical - 13

Write a program on Arduino/Raspberry Pi to subscribe to MQTT


broker for temperature data and print it.

Circuit configuration:

Code :

#include <SimpleDHT.h>                   // Data ---> D3 VCC ---> 3V3 GND ---> GND
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
// WiFi parameters
#define WLAN_SSID       "realme 7"
#define WLAN_PASS       "12345678"
// Adafruit IO
#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883
#define AIO_USERNAME    "iggggviffdsshgsvekk"

190303105391 49 | P a g e
#define AIO_KEY         "frghjklkjkghjghtrtyjkljkhjghfgfdh" 
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT,
AIO_USERNAME, AIO_KEY);
Adafruit_MQTT_Publish Temperature = Adafruit_MQTT_Publish(&mqtt,
AIO_USERNAME "/feeds/Temperature");
int pinDHT11 = 0;
SimpleDHT11 dht11(pinDHT11);
byte hum = 0;  //Stores humidity value
byte temp = 0; //Stores temperature value
void setup() {
  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();
}
// 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;

190303105391 50 | P a g e
      case 5: Serial.println(F("Not authed")); break;
      case 6: Serial.println(F("Failed to subscribe")); break;
      default: Serial.println(F("Connection failed")); break;
    }
// Setup MQTT subscription for onoff & slider feed.
    mqtt.subscribe(&slider);
      if(ret >= 0)
      mqtt.disconnect();
    Serial.println(F("Retrying connection..."));
    delay(10000);
  }
  Serial.println(F("Adafruit IO Connected!"));
}
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();   
  }
  dht11.read(&temp, &hum, NULL);
  Serial.print((int)temp); Serial.print(" *C, "); 
  Serial.print((int)hum); Serial.println(" H");
  delay(5000);
  
     if (! Temperature.publish(temp)) {                     //Publish to Adafruit
      Serial.println(F("Failed"));
    } 
       if (! Humidity.publish(hum)) {                     //Publish to Adafruit
      Serial.println(F("Failed"));
    }
    else {
      Serial.println(F("Sent!"));
    }
Adafruit_MQTT_Subscribe *subscription;
 while ((subscription = mqtt.readSubscription(5000))) {
     // check if its the slider feed
    if (subscription == &slider) {
      Serial.print(F("Slider: "));
      Serial.println((char *)slider.lastread);

190303105391 51 | P a g e
      uint16_t sliderval = atoi((char *)slider.lastread);  // convert to a number
      //analogWrite(PWMOUT, sliderval);
    }    
}
}

Output :

Practical - 14

190303105391 52 | P a g e
Write a program to create TCP server on Arduino/Raspberry Pi and
respond with humidity data to TCP client when requested.

Circuit configuration :

Code :

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

#define DHTTYPE DHT11

const char* ssid = "realme 7";


const char* password = "12345678";

WiFiServer server(80);

190303105391 53 | P a g e
const int DHTPin = 0;

DHT dht(DHTPin, DHTTYPE);


static char celsiusTemp[7];
static char fahrenheitTemp[7];
static char humidityTemp[7];
void setup() 
{
  Serial.begin(115200);
  delay(10);
  dht.begin();
  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");
  server.begin();
  Serial.println("Web server running. Waiting for the ESP IP...");
  delay(10000);
  Serial.println(WiFi.localIP());
}

void loop() 
{
  WiFiClient client = server.available();

  if (client) 
  {
    Serial.println("New client");

190303105391 54 | P a g e
    boolean blank_line = true;
    while (client.connected()) 
    {
      if (client.available()) 
      {
        char c = client.read();
        if (c == '\n' && blank_line) 
        {
          float h = dht.readHumidity();
          float t = dht.readTemperature();
          float f = dht.readTemperature(true);
          if (isnan(h) || isnan(t) || isnan(f)) 
          {
            Serial.println("Failed to read from DHT sensor!");
            strcpy(celsiusTemp,"Failed");
            strcpy(fahrenheitTemp, "Failed");
            strcpy(humidityTemp, "Failed");
          }
          else
          {
            float hic = dht.computeHeatIndex(t, h, false);
            dtostrf(hic, 6, 2, celsiusTemp);
            float hif = dht.computeHeatIndex(f, h);
            dtostrf(hif, 6, 2, fahrenheitTemp);
            dtostrf(h, 6, 2, humidityTemp);
          }
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();

          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          client.println("<head></head><body><h1>ESP8266 - Temperature and
Humidity</h1><h3>Temperature in Celsius: ");
          Serial.println(celsiusTemp);
          client.println(celsiusTemp);
          client.println("*C</h3><h3>Temperature in Fahrenheit: ");
          client.println(fahrenheitTemp);
          client.println("*F</h3><h3>Humidity: ");

190303105391 55 | P a g e
          client.println(humidityTemp);
          client.println("%</h3><h3>");
          client.println("</body></html>");
          break;
        }
        if (c == '\n') 
        {
          blank_line = true;
        }
        else if (c != '\r') 
        {
          blank_line = false;
        }
      }
    }
    delay(1);
    client.stop();
    Serial.println("Client disconnected.");
  }
}

Output :

190303105391 56 | P a g e
Practical - 15

Write a program to create UDP server on Arduino/Raspberry Pi and


respond with humidity data to UDP client when requested.

Circuit configuration :

Code :

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DHT.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#define DHTPin 2 
#define DHTTYPE DHT22   
DHT dht(DHTPin, DHTTYPE);                

190303105391 57 | P a g e
WiFiUDP ntpUDP;
const long utcOffsetInSeconds = 28800;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);
unsigned long epochTime = timeClient.getEpochTime();
struct tm *ptm = gmtime ((time_t *)&epochTime);

const char* ssid = "realme 7";  


const char* password = "12345678"; 

ESP8266WebServer server(80);

String SendHTML(float TemperatureWeb,float HumidityWeb, String TimeWeb,


String DateWeb);
void handle_OnConnect();
void handle_NotFound();

float Temperature;
float Humidity;
String formattedTime;
String Date;
int Day;
int Month;
int Year;

void setup() {
  Serial.begin(115200);
  pinMode(DHTPin, INPUT);           

  Serial.println("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

190303105391 58 | P a g e
  delay(1000);
  Serial.print(".");
  } 
  Serial.println("");
  Serial.println("Connected to WiFi");
  Serial.print("IP: ");  Serial.println(WiFi.localIP());

  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);
  server.begin();
  dht.begin();
  timeClient.begin();
}
void loop() {
  
  server.handleClient(); 
}
void handle_OnConnect() {
  timeClient.update();
 
  unsigned long epochTime = timeClient.getEpochTime(); 
  String formattedTime = timeClient.getFormattedTime();
  
  struct tm *ptm = gmtime ((time_t *)&epochTime); 

  int monthDay = ptm->tm_mday;


  int currentMonth = ptm->tm_mon+1;
  int currentYear = ptm->tm_year+1900;
 
  formattedTime = timeClient.getFormattedTime(); 
  Date = String(currentYear) + "-" + String(currentMonth) + "-" +
String(monthDay);
  Temperature = dht.readTemperature(); 
  Humidity = dht.readHumidity(); 
  server.send(200, "text/html",
SendHTML(Temperature,Humidity,formattedTime,Date)); 
}

190303105391 59 | P a g e
void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

String SendHTML(float TemperatureWeb,float HumidityWeb, String


TimeWeb,String DateWeb){
  String ptr = "<!DOCTYPE html> <html>\n";
  ptr +="<head><meta name=\"viewport\" content=\"width=device-width,
initial-scale=1.0, user-scalable=no\">\n";
  ptr +="<title>ESP8266 Global Server</title>\n";

  ptr +="</head>\n";
  ptr +="<body>\n";
  ptr +="<div id=\"webpage\">\n";
  ptr +="<h1>ESP8266 Global Server</h1>\n";

  ptr +="<p>Date: ";


  ptr +=(String)DateWeb;
  ptr +="</p>";
  ptr +="<p>Time: ";
  ptr +=(String)TimeWeb;
  ptr +="</p>";
  ptr +="<p>Temperature: ";
  ptr +=(int)TemperatureWeb;
  ptr +="C</p>";
  ptr +="<p>Humidity: ";
  ptr +=(int)HumidityWeb;
  ptr +="%</p>";
  
  ptr +="</div>\n";
  ptr +="</body>\n";
  ptr +="</html>\n";
  return ptr;
}

Output :

190303105391 60 | P a g e
190303105391 61 | P a g e

You might also like