IOT Lab Manual - Merged - 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 83

Jaipur Engineering College & Research Centre,

Jaipur

Academic Session 2023-24

COURSE NAME - IOT LAB

COURSE CODE - 8EC4-21

Name:

RTU Roll No:

Sem/Section:

DEPARTMENT OF ELECTRONICS & COMMUNICATION ENGINEERING


IOT LAB Syllabus
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
Department of Electronics and Communication Engineering
VIII Semester Session 2023-24

Name of the Lab:


Name of the Student:
RTU Roll No.:
Continuous Evaluation

Presentation/Neatness (2)

On time submission (2)


Experiment Setup (2)
Date of Performance

Date of Evaluation

Faculty Signature
S.No. Name of Experiment

Execution (4)

Total (10)
1

10

11

12
IOT Lab

LIST OF EXPERIMENTS

Exp. NO. List of Experiments

Exp:1 Study the fundamental of IOT softwares and components.

Exp:2 Familiarization with Arduino/Raspberry Pi and perform necessary software

To interface LED/Buzzer with Arduino/Raspberry Pi and write a program to


Exp:3
turn ON LED for 1 sec after every 2 seconds.
Exp:4 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.
To interface DHT11 sensor with Arduino/Raspberry Pi and write a program to
Exp:5
print temperature and humidity readings.
To interface motor using relay with Arduino/Raspberry Pi and write a program
Exp:6
to turn ON motor when push button is pressed.
Exp:7 To interface OLED with Arduino/Raspberry Pi and write a program to print
temperature and humidity readings on it.
To interface Bluetooth with Arduino/Raspberry Pi and write a program to send
Exp:8
sensor data to smartphone using Bluetooth.
To interface Bluetooth with Arduino/Raspberry Pi and write a program to turn
Exp:9 LED ON/OFF when ‗1‘/‘0‘ is received from smartphone using Bluetooth

Write a program on Arduino/Raspberry Pi to upload temperature and humidity


Exp:10
data to thingspeak cloud.
Write a program on Arduino/Raspberry Pi to retrieve temperature and
Exp:11
humidity data from thingspeak cloud.

Exp:12 To install MySQL database on Raspberry Pi and perform basic SQL queries.

Department of ECE Page 11


IOT Lab

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


Exp:13 with humidity data to UDP client when requested.

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


Exp:14 with humidity data to TCP client when requested.

Department of ECE Page 12


IOT Lab

INSTRUCTIONS OF LAB

DO’S

1. Student should get the record of previous experiment checked before starting the new
experiment.
2. Read the manual carefully before starting the experiment.
3. Before starting the experiment, system checked by the teacher.
4. Get your readings checked by the teacher.
5. Apparatus must be handled carefully.
6. Maintain strict discipline.
7. Keep your mobile phone switched off or in vibration mode.
8. Students should get the experiment allotted for next turn, before leaving the lab.

DON’TS

1. Do not touch or attempt to touch the mains power supply wire with bare hands.
2. Do not overcrowd the tables.
3. Do not tamper with equipments.
4. Do not leave the lab without permission from the teacher.

Department of ECE Page 13


IOT Lab

SAFETY MEASURES
1. Antivirus software is installed for protection against viruses and malwares.
2. External storage devices are not allowed to use in lab.
3. At all the times the right procedures while starting and shutting down the computer
therefore abrupt switching on and off the computer should be avoided since this can
lead to damaging the computer.
4. Any repairs to the computer should be done by someone who has knowledge
regarding computer repairs.

Department of ECE Page 14


IOT Lab

EXPERIMENT NO.1
OBJECTIVE: Study the fundamental of IOT softwares and components.

RESOURCE REQUIRED: Proteus and Arduino IDE


THEORY: Internet of Things (IoT) is a network of physical objects or people called "things"
that are embedded with software, electronics, network, and sensors that allows these objects
to collect and exchange data.
The thing in IoT can also be a person with a diabetes monitor implant, an animal with
tracking devices, etc.
Components of IOT:
1) Sensors/Devices: Sensors or devices are a key component that helps you to collect
live data from the surrounding environment. A device may have various types of
sensors which performs multiple tasks apart from sensing. Example, A mobile phone
is a device which has multiple sensors like GPS, camera but your smartphone is not
able to sense these things.
2) Connectivity: All the collected data is sent to a cloud infrastructure. The sensors
should be connected to the cloud using various mediums of communications. These
communication mediums include mobile or satellite networks, Bluetooth, WI-FI,
WAN, etc.
3) Data Processing: Once that data is collected, and it gets to the cloud, the software
performs processing on the gathered data. This process can be just checking the
temperature, reading on devices like AC or heaters. However, it can sometimes also
be very complex like identifying objects, using computer vision on video.
4) User Interface: The information needs to be available to the end-user in some way
which can be achieved by triggering alarms on their phones or sending them
notification through email or text message. The user sometimes might need an
interface which actively checks their IoT system. For example, the user has a camera
installed in his home. He wants to access video recording and all the feeds with the
help of a web server.
Department of ECE Page 15
IOT Lab

5) Depending on the IoT application and complexity of the system, the user may also be
able to perform an action which may create cascading effects.
6) For example, if a user detects any changes in the temperature of the refrigerator, with
the help of IoT technology the user should able to adjust the temperature with the help
of their mobile phone.
Application type Description

Smart Thermostats Helps you to save resource on heating bills by knowing your
usage patterns.
Connected Cars IoT helps automobile companies handle billing, parking,
insurance, and other related stuff automatically.
Activity Trackers Helps you to capture heart rate pattern, calorie expenditure,
activity levels, and skin temperature on your wrist.
Smart Outlets Remotely turn any device on or off. It also allows you to track a
device's energy level and get custom notifications directly into
your smartphone.
Parking Sensors IoT technology helps users to identify the real-time availability of
parking spaces on their phone.
Connect Health The concept of a connected health care system facilitates real-time
health monitoring and patient care. It helps in improved medical
decision-making based on patient data.
Smart City Smart city offers all types of use cases which include traffic
management to water distribution, waste management, etc.
Smart home Smart home encapsulates the connectivity inside your homes. It
includes smoke detectors, home appliances, light bulbs, windows,
door locks, etc.
Smart supply chain Helps you in real time tracking of goods while they are on the
road, or getting suppliers to exchange inventory information.

Department of ECE Page 16


IOT Lab

Department of ECE Page 17


IOT Lab

How does Internet of Thing (IoT) Work?

The working of IoT is different for different IoT echo system (architecture). However, the
key concept of there working are similar. The entire working process of IoT starts with the
device themselves, such as smartphones, digital watches, electronic appliances, which
securely communicate with the IoT platform. The platforms collect and analyze the data from
all multiple devices and platforms and transfer the most valuable data with applications to
devices.

Features of IOT

The most important features of IoT on which it works are connectivity, analyzing,
integrating, active engagement, and many more. Some of them are listed below:

Connectivity: Connectivity refers to establish a proper connection between all the things of
IoT to IoT platform it may be server or cloud. After connecting the IoT devices, it needs a
high speed messaging between the devices and cloud to enable reliable, secure and bi-
directional communication.

Analyzing: After connecting all the relevant things, it comes to real-time analyzing the data
collected and use them to build effective business intelligence. If we have a good insight into
data gathered from all these things, then we call our system has a smart system.

Integrating: IoT integrating the various models to improve the user experience as well.

Artificial Intelligence: IoT makes things smart and enhances life through the use of data. For
example, if we have a coffee machine whose beans have going to end, then the coffee
machine itself order the coffee beans of your choice from the retailer.

Sensing: The sensor devices used in IoT technologies detect and measure any change in the
environment and report on their status. IoT technology brings passive networks to active
networks. Without sensors, there could not hold an effective or true IoT environment.

Department of ECE Page 18


IOT Lab

Active Engagement: IoT makes the connected technology, product, or services to active
engagement between each other.

Endpoint Management: It is important to be the endpoint management of all the IoT system
otherwise, it makes the complete failure of the system. For example, if a coffee machine itself
order the coffee beans when it goes to end but what happens when it orders the beans from a
retailer and we are not present at home for a few days, it leads to the failure of the IoT
system. So, there must be a need for endpoint management.

IoT Protocols

1. Constrained Application Protocol (CoAP)

CoAP is an internet utility protocol for constrained gadgets. It is designed to enable simple,
constrained devices to join IoT through constrained networks having low bandwidth
availability. This protocol is primarily used for machine-to-machine (M2M) communication
and is particularly designed for IoT systems that are based on HTTP protocols.

Department of ECE Page 19


IOT Lab

CoAP makes use of the UDP protocol for lightweight implementation. It also uses restful
architecture, which is just like the HTTP protocol. It makes use of dtls for the cozy switch of
statistics within the slipping layer.

2. Message Queue Telemetry Transport Protocol (MQTT)

MQTT (Message Queue Telemetry Transport) is a messaging protocol developed with the aid
of Andy Stanford-Clark of IBM and Arlen Nipper of Arcom in 1999 and is designed for

Department of ECE Page 20


IOT Lab

M2M communication. It‘s normally used for faraway tracking in IoT. Its primary challenge is
to gather statistics from many gadgets and delivery of its infrastructure. MQTT connects
gadgets and networks with packages and middleware. All the devices hook up with facts
concentrator servers like IBM‘s new message sight appliance. MQTT protocols paintings on
top of TCP to offer easy and dependable streams of information.
These IoT protocols include 3 foremost additives: subscriber, publisher, and dealer. The
writer generates the information and transmits the facts to subscribers through the dealer. The
dealer guarantees safety by means of move-checking the authorization of publishers and
subscribers.
3. Advanced Message Queuing Protocol (AMQP)

This was evolved by John O‘Hara at JP Morgan Chase in London. AMQP is a software layer
protocol for message-oriented middleware environment. It supports reliable verbal exchange
through message transport warranty primitives like at-most-once, at least once and exactly as
soon as shipping.
The AMQP – IoT protocols consist of hard and fast components that route and save messages
within a broker carrier, with a set of policies for wiring the components together. The AMQP
protocol enables patron programs to talk to the dealer and engage with the AMQP model.
This version has the following three additives, which might link into processing chains in the
server to create the favored capabilities.
 Exchange: Receives messages from publisher primarily based programs and routes them
to ‗message queues‘.
 Message Queue: Stores messages until they may thoroughly process via the eating client
software.
 Binding: States the connection between the message queue and the change.

Department of ECE Page 21


IOT Lab

4. Data Distribution Service (DDS)

It enables a scalable, real-time, reliable, excessive-overall performance and interoperable


statistics change via the submit-subscribe technique. DDS makes use of multicasting to
convey high-quality QoS to applications.

DDS is deployed in platforms ranging from low-footprint devices to the cloud and supports
green bandwidth usage in addition to the agile orchestration of system additives.
The DDS – IoT protocols have fundamental layers: facts centric submit-subscribe (dcps) and
statistics-local reconstruction layer (dlrl).

Dcps plays the task of handing over the facts to subscribers, and the dlrl layer presents an
interface to dcps functionalities, permitting the sharing of distributed data amongst IoT
enabled objects.

Department of ECE Page 22


IOT Lab

Building Blocks of IoT Hardware

IoT Hardware – Building Blocks

i. Thing

―Thing‖ in IOT is the asset that you want to control or monitor or measure, that is, observe
closely. In many IoT products, the ―thing‖ gets fully incorporated into a smart device. For

Department of ECE Page 23


IOT Lab

example, think of products like a smart refrigerator or an automatic vehicle. These products
control and monitor themselves.
There are sometimes many other applications where the thing stands as an alone device, and a
separate product is connected to ensure it possesses smart capabilities.

ii. Data Acquisition Module


The data acquisition module focuses on acquiring physical signals from the thing which is
being observed or monitored and converting them into digital signals that can be manipulated
or interpreted by a computer.
This is the hardware component of an IOT system that contains all the sensors that help in
acquiring real-world signals such as temperature, pressure, density, motion, light, vibration,
etc. The type and number of sensors you need depend on your application.
This module also includes the necessary hardware to convert the incoming sensor signal into
digital information for the computer to use it. This includes conditioning of incoming signal,
removing noise, analog-to-digital conversion, interpretation, and scaling.

iii. Data Processing Module


The third building block of the IoT device is the data processing module. This is the actual
―computer‖ and the main unit that processes the data performs operations such as local
analytics, stores data locally, and performs some other computing operations.

iv. Communication Module


The last building block of IOT hardware is the communications module. This is the part that
enables communications with your Cloud Platform, and with 3rd party systems either locally
or in the Cloud.

Department of ECE Page 24


IOT Lab

b. IoT Sensors

The most important IoT hardware might be its sensors. These devices consist of a variety of
modules such as energy modules, RF modules, power management modules, and sensing
modules.

IoT Hardware – IoT Sensors

c. Wearable Electronic Devices

Wearable electronic devices are small devices that can be worn on the head, neck, arms,
torso, and feet.

Department of ECE Page 25


IOT Lab

IoT Hardware – Wearable Electronic Devices

Current smart wearable devices include −


 Head − Helmets, glasses,
 Neck − Jewelry, collars
 Arm − Wristwatches, wristbands, rings
 Torso – Clothing pieces, backpacks
 Feet − Shoes, Socks

d. Basic Devices

The day to day devices that we use such as desktop, cellphones and tablets remain integral
parts of IoT system.
 The desktop provides the user with a very high level of control over the system and its
settings.
 The tablet acts as a remote and provides access to the key features of the system.
 Cellphone allows remote functionality and some essential settings modification
Other key connected devices include standard network devices like routers and switches.

Department of ECE Page 26


IOT Lab

IoT Software

Embedded systems have less storage and processing power, their language needs are
different. The most commonly used operating systems for such embedded systems are Linux
or UNIX-like OSs like Ubuntu Core or Android.
IoT software encompasses a wide range of software and programming languages from
general-purpose languages like C++ and Java to embedded-specific choices like Google‘s Go
language or Parasail.
Few IoT Softwares are-
 C & C++: The C programming language has its roots in embedded systems—it even got
its start for programming telephone switches. It‘s pretty ubiquitous, that is, it can be used
almost everywhere and many programmers already know it. C++ is the object-oriented
version of C, which is a language popular for both the Linux OS and Arduino embedded
IoT software systems. These languages were basically written for the hardware systems
which makes them so easy to use.
 Java: While C and C++ are hardware specific, the code in JAVA is more portable. It is
more like a write once and read anywhere language, where you install libraries, invests
time in writing codes once and you are good to go.
 Python: There has been a recent surge in the number of python users and has now
become one of the ―go-to‖ languages in Web development. Its use is slowly spreading to
the embedded control and IoT world—specially the Raspberry Pi processor. Python is an

Department of ECE Page 27


IOT Lab

interpreted language, which is, easy toread, quick to learn and quick to write. Also, it‘s a
powerhouse for serving data-heavy applications.
 Unlike most of the languages mentioned so far, it was specifically designed for
embedded systems, it‘s small and compact and has less memory size.
 Data Collection: It is used for data filtering, data security, sensing, and measurement.
The protocols aid in decision making by sensing form real-time objects. It can work both
ways by collecting data from devices or distributing data to devices. All the data
transmits to a central server.
 Device Integration: This software ensures that devices bind and connect to networks
facilitating information sharing. A stable cooperation and communication ensure
between multiple devices.
 Real-Time Analytics: In this, the input from users serves as potential data for carrying
out real-time analysis, making insights, suggesting recommendations to solve
organizations problems and improve its approach. This, as a result, allows automation
and increased productivity.
 Application and Process Extension: These applications extend the reach of existing
systems and software to allow a wider, more effective system. They integrate predefined
devices for specific purposes such as allowing certain mobile devices or engineering
instruments access. It supports improved productivity and more accurate data collection.

IoT Hardware | IoT Software


Department of ECE Page 28
IOT Lab

RESULT AND CONCLUSION:

We have studied the fundamentals of IOT softwares and components. Internet of Things can
create information about the connected objects, analyze it, and make decisions. All IoT
applications are using sensors to detect and collect data that are used to give a proper decision
that maintains a high level of security of the installations.

Department of ECE Page 29


IOT Lab

EXPERIMENT NO.2
OBJECTIVE: Familiarization with Arduino/Raspberry Pi and perform necessary software
installation

RESOURCE REQUIRED: Arduino IDE


THEORY: Arduino is a prototype platform (open-source) based on an easy-to-use hardware
and software. It consists of a circuit board, which can be programed (referred to as a
microcontroller) and a ready-made software called Arduino IDE (Integrated Development
Environment), which is used to write and upload the computer code to the physical board.
Arduino provides a standard form factor that breaks the functions of the microcontroller into
a more accessible package. Arduino is a prototype platform (open-source) based on an easy-
to-use hardware and software. It consists of a circuit board, which can be programed (referred
to as a microcontroller) and ready-made software called Arduino IDE (Integrated
Development Environment), which is used to write and upload the computer code to the
physical board.
The key features are −
sensors and
turn it into an output such as activating a motor, turning LED on/off, connect to the cloud and
many other actions.

microcontroller on the board via Arduino IDE (referred to as uploading software).


extra piece
of hardware (called a programmer) in order to load a new code on to the board. You can
simply use a USB cable.
rsion of C++, making it easier to learn
to program.
micro-
controller into a more accessible package.

Department of ECE Page 30


IOT Lab

Download the Arduino Software (IDE)


arduino.cc web site. 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.
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)

Department of ECE Page 31


IOT Lab

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 Different
Arduino Boards:
1. Arduino Uno: This is the latest revision of the basic Arduino USB board. It connects to the
computer with a standard USB cable and contains everything else you need to program and
use the board.
2. Arduino NG: REV-C Revision C of the Arduino NG does not have a built-in LED on pin
13 - instead you'll see two small unused solder pads near the labels "GND" and "13".
3. Arduino Bluetooth: The Arduino BT is a microcontroller board originally was based on the
ATmega168, but now is supplied with the 328, and the Bluegiga WT11 bluetooth module. It
supports wireless serial communication over bluetooth.
4. Arduino Mega: The original Arduino Mega has an ATmega1280 and an FTDI USB-to
serial chip.
5. Arduino NANO: The Arduino Nano 3.0 has an ATmega328 and a two-layer PCB. The
power LED moved to the top of the board.
Advantages of using Arduino:
It offers some advantage for teachers, students, and interested amateurs over other systems:
 Inexpensive - Arduino boards are relatively inexpensive compared to other
Department of ECE Page 32
IOT Lab

microcontroller platforms. The least expensive version of the Arduino module can be
assembled by hand, and even the pre-assembled Arduino modules cost less than $50
 Cross-platform - The Arduino Software (IDE) runs on Windows, Macintosh OSX,
and Linux operating systems. Most microcontroller systems are limited to Windows.
 Simple, clear programming environment - The Arduino Software (IDE) is easy-to-use
for beginners, yet flexible enough for advanced users to take advantage of as well. For
teachers, it's conveniently based on the Processing programming environment, so
students learning to program in that environment will be familiar with how the
Arduino IDE works.
 Open source and extensible software - The Arduino software is published as open
source tools, available for extension by experienced programmers. The language can
be expanded through C++ libraries, and people wanting to understand the technical
details can make the leap from Arduino to the AVR C programming language on
which it's based. Similarly, you can add AVR-C code directly into your Arduino
programs if you want to.
 Open source and extensible hardware - The plans of the Arduino boards are published
under a Creative Commons license, so experienced circuit designers can make their
own version of the module, extending it and improving it. Even relatively
inexperienced users can build the breadboard version of the module in order to
understand how it works and save money.

RESULT AND CONCLUSION:

In this experiment, we have discussed about the Arduino fundamentals and its necessary
software installation. Thus, Arduino simplifies the process of working with microcontrollers,
Arduino is an open source micro-controller which can be used as a development board for
hundreds and thousands of project. we can program the Arduino board with the help of
Arduino IDE and the programming is based on C/C++.

Department of ECE Page 33


IOT Lab

Experiment No- 3(a)


OBJECTIVE: To Interface LED /BUZZER with Arduino /Raspberry Pi and write a program
to turn ON LED for 1 Sec after every 2 seconds.

RESOURCE REQUIRED: Arduino IDE, Proteus 8 Professional.

THEORY:-

Firstly identify anode(+ve) & cathode (-ve) leg of LED. Following diagram gives a clear
idea of LED

Now connect a resistor to positive leg and other end of resistor to 5V. Cathode will be
connected to Arduino GPIO, in our case pin 13.

digitalWrite(LED,HIGH); will turn the LED ON. Now we need to keep the LED ON
for 1 second. We do so by keeping the micro controller idle (or we make it to wait) for 1
second. delay(1000); is the function we use to keep the micro controller idle for 1
second. After 1 second, we need to turn LED OFF. We do so with
instruction digitalWrite(LED,LOW); this will turn LED OFF. Now we need to keep the
LED in its OFF state for 2 second (before it is turned ON again). To do so we write
a delay(2000); instruction once again just below the instruction to turn LED OFF. Since
this is the last statement inside loop() function of our program; the micro controller will
begin executing from beginning statement inside loop() after waiting 1 second to keep
LED OFF. So the LED is ON again after 1 second.
Department of ECE Page 34
IOT Lab

CIRCUIT DIAGRAM:

ARDUINO CODE

int ledpin = 13; //set pin no of Arduino to which led is connected


void setup()
{ pinMode(ledpin, OUTPUT); // initialize digital pin LED_BUILTIN as an output.
} // the loop function runs over and over again forever
void loop() {
digitalWrite(ledpin, LOW ); // turn the LED off by making the voltage LOW
delay(1000);
digitalWrite(ledpin, HIGH); // turn the LED ON by making the voltage HIGH
delay(2000);
}

Department of ECE Page 35


IOT Lab

Observations: We have interfaced the led with Arduino Uno and observe the simulation
result.

RESULT AND CONCLUSION:

LED is interfaced with Arduino uno with ON time delay of 1 second and OFF time delay of
2 seconds. Thus, we have performed the experiment of led interfacing with Arduino and to
turn ON for 1 sec after every 2 seconds.

Department of ECE Page 36


IOT Lab

Experiment No- 3(b)


OBJECTIVE: To Interface BUZZER with Arduino /Raspberry Pi and write a program to
turn ON LED for 1 Sec after every 2 seconds.

RESOURCE REQUIRED: Arduino IDE, Proteus 8 Professional.

THEORY:-

Led blinking is the most beginner & easy step to start your experiment with arduino.
Lets get started :-

Firstly identify anode(+ve) & cathode (-ve) leg of LED. Following diagram gives a clear
idea of LED

Now connect a resistor to positive leg and other end of resistor to 5V.Cathode will be
connected to Arduino GPIO, in our case pin 13.

ARDUINO CODE:

const int buzzer = 9; //buzzer to arduino pin 9


void setup(){
pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
}
void loop(){
tone(buzzer, 1000); // Send 1KHz sound signal...
delay(1000); // ...for 1 sec

Department of ECE Page 37


IOT Lab

noTone(buzzer); // Stop sound...


delay(2000); // ...for 1sec
}

CIRCUIT DIAGRAM:

Observations: We have interfaced the led with Arduino Uno and observe the simulation
result.

RESULT AND CONCLUSION: A buzzer is interfaced with Arduino uno and buzzer sound
is verified after running the simulation.

Department of ECE Page 38


IOT Lab

Experiment No- 4(a)


OBJECTIVE: To Interface Pushbutton with Arduino /Raspberry Pi and write a program to
turn ON LED for 1 Sec after every 2 seconds.

RESOURCE REQUIRED: Arduino IDE, Proteus 8 Professional.

THEORY: The pushbutton is a component that connects two points in a circuit when you
press it. The example turns on an LED when you press the button.

We connect three wires to the Arduino board. The first goes from one leg of the pushbutton
through a pull-up resistor (here 2.2 KOhms) to the 5 volt supply. The second goes from the
corresponding leg of the pushbutton to ground. The third connects to a digital i/o pin (here
pin 7) which reads the button's state.

When the pushbutton is open (unpressed) there is no connection between the two legs of the
pushbutton, so the pin is connected to 5 volts (through the pull-up resistor) and we read a
HIGH. When the button is closed (pressed), it makes a connection between its two legs,
connecting the pin to ground, so that we read a LOW. (The pin is still connected to 5 volts,
but the resistor in-between them means that the pin is "closer" to ground.)

ARDUINO CODE:

const int switchPin = 9; //Switch Connected to PIN 4


const int ledPin = 8; //LED Connected to PIN 8
int switchState = 0; // Variable for reading Switch status
void setup()
{
pinMode(ledPin, OUTPUT); //LED PIN is Output
pinMode(switchPin, INPUT);//Switch PIN is input with PULLUP
}
void loop()

Department of ECE Page 39


IOT Lab

{
switchState = digitalRead(switchPin); //Reads the status of the switch.
if (switchState == LOW) //If the switch is pressed
{
digitalWrite(ledPin, HIGH); //LED ON
delay(500); //0.5 Second Delay
digitalWrite(ledPin, LOW); //LED OFF
}
}

CIRCUIT DIAGRAM:

Department of ECE Page 40


IOT Lab

OBSERVATIONS: We have interfaced the led with Arduino Uno and observe the
simulation result.

RESULT AND CONCLUSION:

We have verified that LED is glowing when pushbutton interfaced with Arduino is pressed.
Pushbutton interfacing with Arduino is done and diode is turning ON when it is pressed.

Department of ECE Page 41


IOT Lab

Experiment No- 4(b)


OBJECTIVE: To Interface Digital LDR sensor with Arduino /Raspberry Pi and write a
program toturn ON LED at sensor detection.

RESOURCE REQUIRED: Arduino IDE, Proteus 8 Professional.

THEORY:

We have made a voltage divider circuit using LDR and 100k resistor. The voltage divider
output is feed to the analog pin of the Arduino. The analog Pin senses the voltage and gives
some analog value to Arduino. The analog value changes according to the resistance of LDR.
So, as the light falls on the LDR the resistance of it gets decreased and hence the voltage
value increase.

Intensity of light ↓ - Resistance↑ - Voltage at analog pin↓ - Light turns ON

As per the Arduino code, if the analog value falls below 200 we consider it as dark and the
light turns ON. If the value comes above 200 we consider it as bright and the light turns OFF.

ARDUINO CODE:

const int ledPin = 9;


const int ldrPin = A0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
}
void loop() {
int ldrStatus = analogRead(ldrPin);
if (ldrStatus <= 200) {
digitalWrite(ledPin, HIGH);

Department of ECE Page 42


IOT Lab

} else {
digitalWrite(ledPin, LOW);
}
}

CIRCUIT DIAGRAM:

OBSERVATIONS: We have interfaced the led with Arduino Uno and observe the
simulation result.

Department of ECE Page 43


IOT Lab

RESULT AND CONCLUSION:

It is verified that when analog value falls below 200, ambient is considered dark and the light
turns ON. If the value comes above 200, ambient is considered bright and the light turns
OFF. LDR interfacing with Arduino is done and to turn ON LED on darkness and vice-versa.

Department of ECE Page 44


IOT Lab

Experiment No- 4(c)


OBJECTIVE: To Interface Digital IR sensor with Arduino/Raspberry Pi and write a
program to turn ON LED at sensor detection.

RESOURCE REQUIRED: Arduino IDE, Proteus 8 Professional.

THEORY:

An infrared sensor is an electronic device, that emits in order to sense some aspects of the
surroundings. An IR sensor can measure the heat of an object as well as detects the motion.
These types of sensors measures only infrared radiation, rather than emitting it that is called
as a passive IR sensor.
The Passive Infrared (PIR) sensor is used to detect the presence of human.... The Grid-EYE
sensor detects the human using the infrared radiation radiated by the human body. Every
human radiates the infrared energy of specific wavelength range.
IR Sensor has four pins:
1. VCC +5V
2. GND
3. D connects with any digital pin of Arduino when IR pair use as Digital Sensor.
4. A connects with analog input pin of Arduino when IR pair use as Analog Sensor.

The wavelengths of these regions and their applications are shown below.

 Near infrared region — 700 nm to 1400 nm — IR sensors, fiber optic


 Mid infrared region — 1400 nm to 3000 nm — Heat sensing
 Far infrared region — 3000 nm to 1 mm — Thermal imaging

The frequency range of infrared is higher than microwave and lesser than visible light.

For optical sensing and optical communication, photo optics technologies are used in the near
infrared region as the light is less complex than RF when implemented as a source of signal.

Department of ECE Page 45


IOT Lab

Optical wireless communication is done with IR data transmission for short range
applications.

An infrared sensor emits and/or detects infrared radiation to sense its surroundings.

The working of any Infrared sensor is governed by three laws: Planck‘s Radiation law,
Stephen – Boltzmann law and Wien‘s Displacement law.

Planck‘s law states that ―every object emits radiation at a temperature not equal to 00K‖.
Stephen – Boltzmann law states that ―at all wavelengths, the total energy emitted by a black
body is proportional to the fourth power of the absolute temperature‖. According to Wien‘s
Displacement law, ―the radiation curve of a black body for different temperatures will reach
its peak at a wavelength inversely proportional to the temperature‖.

The basic concept of an Infrared Sensor which is used as Obstacle detector is to transmit an
infrared signal, this infrared signal bounces from the surface of an object and the signal is
received at the infrared receiver.

ARDUINO CODE:
int IRSensor = 2; // connect ir sensor to arduino pin 2
int LED = 13; // conect Led to arduino pin 13
void setup()
{ pinMode (IRSensor, INPUT); // sensor pin INPUT
pinMode (LED, OUTPUT); // Led pin OUTPUT
}
void loop()
{ int statusSensor = digitalRead (IRSensor);

Department of ECE Page 46


IOT Lab

if (statusSensor == 1)
digitalWrite(LED, LOW); // LED LOW
}
else
{ digitalWrite(LED, HIGH); // LED High
}
}

CIRCUIT DIAGRAM:

OBSERVATIONS: We have interfaced the led with Arduino Uno and observe the
simulation result.

Department of ECE Page 47


IOT Lab

RESULT AND CONCLUSION:

We have performed the experiment of led interfacing with Arduino and to turn ON for 1 sec
after every 2 seconds.

Department of ECE Page 48


IOT Lab

Experiment No- 5
OBJECTIVE: To Interface DHT11 sensor with Arduino /Raspberry Pi and write a program
to print temperature and humidity readings.

RESOURCE REQUIRED: Arduino IDE, Proteus 8 Professional.

THEORY: DHT11 sensor is used to measure the temperature and humidity. It has a resistive
humidity sensing component and a negative temperature coefficient (NTC). An 8 bit MCU is
also connected in it which is responsible for its fast response. It is very inexpensive but it
gives values of both temperature and humidity at a time.

First of all connect the ground and the VCC of the DHT11 temperature and humidity sensor
to the ground and 5v of the Arduino. Then connect the data pin of the DHT11 sensor to the
pin 2 of the Arduino. To run the following code in Arduino IDE you will first have to install
the DHT library in you Arduino directory.

Download the zip file and place it in your Arduino library folder. The path to Arduino library
folder for my computer is

Documents/ Arduino/ Libraries

Unzip the downloaded file and place it in this folder.

After copying the files, the Arduino library folder should have a new folder named DHT
containing the dht.h and dht.cpp. After that copy the following code in the Arduino IDE and
upload the code.

ARDUINO CODE:

#include "DHT.h" //including the dht22 library


#define DHTPIN 8 //Declaring pin 9 of arduino for the dht22
#define DHTTYPE DHT22 //Defining which type of dht22 we are using (DHT22 or DHT11)

Department of ECE Page 49


IOT Lab

DHT dht(DHTPIN, DHTTYPE); //Declaring a variable named dht


void setup() { //Data written in it will only run once
Serial.begin(9600); //setting the baud rate at 9600
dht.begin(); //This command will start to receive the values from dht22
}
void loop() { //Data written in it will run again and again
float hum = dht.readHumidity(); //Reading the humidity and storing in hum
float temp = dht.readTemperature(); //Reading the temperature as Celsius and storing in temp
float fah = dht.readTemperature(true);
if (isnan(hum) || isnan(temp) || isnan(fah)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
float heat_index = dht.computeHeatIndex(fah, hum);
float heat_indexC = dht.convertFtoC(heat_index);
Serial.print("Humidity: "); //Writing the humidity on the serial monitor
Serial.print(hum); //Writing the humidity value stored in hum on the Serial monitor
Serial.print(" %\t");
Serial.print("Temperature: "); //Writing the temperature on the serial monitor
Serial.print(temp); //Writing the value of temperature on the serial monitor
Serial.print(" *C ");
Serial.print(fah);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(heat_indexC);
Serial.print(" *C ");
Serial.print(heat_index);
Serial.println(" *F ");

Department of ECE Page 50


IOT Lab

delay(2000); //Giving a delay of 2 seconds


}

Circuit Diagram:

Observations: We have interfaced the led with Arduino Uno and observe the simulation
result.

Department of ECE Page 51


IOT Lab

RESULT AND CONCLUSION:

We have performed the experiment of led interfacing with Arduino and to turn ON for 1 sec
after every 2 seconds. It will display the ambient temperature and humidity readings on serial
monitor of Arduino IDE.

Department of ECE Page 52


IOT Lab

Experiment No- 6
AIM: To Interface motor using relay with Arduino /Raspberry Pi and write a program to turn
ON motor when PUSH button is pressed.

RESOURCE REQUIRED: Arduino IDE, Proteus 8 Professional.

THEORY:

ARDUINO CODE:

const int buttonPin = 12;


const int transistorPin = 7;
int buttonState = 0;
void setup()
{ pinMode(buttonPin, INPUT_PULLUP);
pinMode transistorPin, OUTPUT);
}
void loop()
{ buttonState = digitalRead(buttonPin);
if (buttonState == LOW)
{ digitalWrite (transistorPin, HIGH);
}
else
{
digitalWrite (transistorPin, LOW);
}
}

We can control high voltage electronic devices using relays. A Relay is actually a switch
which is electrically operated by an electromagnet. The electromagnet is activated with a low

Department of ECE Page 53


IOT Lab

voltage, for example 5 volts from a microcontroller and it pulls a contact to make or break a
high voltage circuit.

The base terminal of the 2N2222 transistor is connected to any of the digital I/O pin of the
Arduino through a 1KΩ current limiting diode (in this project, base is connected to Pin 7 of
Arduino). The emitter terminal of the transistor is connected to ground.

One coil terminal of the relay is connected to the collector terminal of the transistor while the
other terminal is connected to supply voltage. The supply voltage to coil terminal of the relay
is dependent on the voltage ratings of the relay. Some are rated 5V and other are rated 12V.
In this project, it is connected to 5V.

A freewheeling diode is connected across the coil terminals of the relay. When coming to the
contact terminals of the relay, a 12V motor along with a 12V power supply are connected in
series between the Normally Open (NO) terminal and Common (COMM) terminal as shown
in the circuit.

In order to decide when to turn on the relay and when to turn it off, a button is connected
between the Pin 12 of Arduino and ground.

Department of ECE Page 54


IOT Lab

Working Principle of the Project

The intention behind the project is to explain how a microcontroller (in this case, an Arduino)
can be used to control a high voltage and high current devices using a relay.

When the system is powered on, the Arduino waits for the button to be pressed (as per the
code written). The button terminal is pulled up internally. Hence, when the button is pushed,
the Arduino detects Logic 0 (LOW).

This will send a Logic 1 (HIGH) signal to Pin 7, which is connected to the base of the
transistor. As a result, the transistor is switched ON. As one of the coil terminals of the relay
is connected to the collector of the transistor (which is switched ON), a conduction path
between the supply, coil and collector – emitter terminals of transistor is formed.

Because of this, the coil in the relay gets energized and acts as an electromagnet. As a result,
the moving contact of the coil, which was initially in the Normally Closed (NC) position, will
be attracted towards the electromagnet and moves to the Normally Open (NO) position. This
action will complete the motor circuit and hence, the motor starts rotating.

The motor keeps on rotating as long as the button is pushed. Once the button is released, the
transistor is switched OFF and the coil in the relay is de energized. Hence, the contact goes
back to the Normally Closed position and the motor is turned OFF.

CIRCUIT DIAGRAM:

Department of ECE Page 55


IOT Lab

OBSERVATIONS:
When pushbutton is pressed, then the motor rotates due to amount of current provided
required to turn on relay by the pushbutton.

RESULT AND CONCLUSION:


Continuous motor operation with a momentary ―start‖ switch is possible if a normally-open
―seal-in‖ contact from the contactor is connected in parallel with the start switch so that once
the contactor is energized it maintains power to itself and keeps itself ―latched‖ on. Time
delay relays are commonly used in large motor control circuits to prevent the motor from
being started (or reversed) until a certain amount of time has elapsed from an event.

Department of ECE Page 56


IOT Lab

Experiment No- 7

OBJECTIVE: To Interface OLED with Arduino/Raspberry Pi and write a program to print


temperature and humidity readings.

RESOURCE REQUIRED: Arduino IDE Arduino Uno Board, OLED display, DHT11
sensor

Theory:

The DHT11 sensor has a humidity measurement component and an NTC temperature
measurement component. Humidity measurement component consists of two electrodes and a
substrate in between them. Whenever the humidity or moisture changes the conductivity of
the substrate changes, hence the resistance between electrodes changes. The resistance of the
NTC thermistor decreases as the temperature increases.

Change in resistance is measured and processed by the internal microcontroller and send out
through the data line.In this experiment, we are going to learn interfacing of Arduino UNO
with OLED 128x64 I2C monochrome display.

Connect the pins of OLED with the following pins of Arduino UNO, as shown below.

Arduino UNO OLED

5V--------------------VCC

GND-----------------GND

SDA/A4--------------SDA

SCL/A5---------------SCL

Install Required Libraries

 Adafruit_GFX.h https://github.com/adafruit/Adafruit-GFX-Library

Department of ECE Page 57


IOT Lab

 Adafruit_SSD1306.h https://www.github.com/adafruit/Adafruit_SSD1306
 Wire.h this library will be installed by default

Either you can download the libraries from Github and add the ZIP file in Arduino IDE using
add.zip library option.

Or we can install the libraries directly from Arduino IDE from Manage Libraries.

Follow the below steps to install.

Open manage library from sketch -> include library -> manage libraries

Department of ECE Page 58


IOT Lab

Then Search for AdafruitSSD1306 and click on the install button.

Then search for the AdafruitGFX and click the install button. Now we have successfully
installed the required libraries for this project.
Department of ECE Page 59
IOT Lab

Using a display to view the temperature and humidity of your environment can be
possible using the DHT11 sensor with the easy to use Arduino. For this project, we will
be using the Oled I2C SSD1306 display module to display the temperature and humidity
readings gathered from the environment using the DHT11 temperature and humidity
sensor.

Circuit Diagram:

ARDUINO CODE:

#include "DHT.h"
#define DHT11Pin 2
#define DHTType DHT11
//OLED
#include <Wire.h>
Department of ECE Page 60
IOT Lab

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

DHT HT(DHT11Pin,DHTType);
float humi;
float tempC;
float tempF;

//OLED define
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

void setup() {
Serial.begin(9600);
//For DHT11
HT.begin();
//For OLED I2C
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.display(); //Display logo
delay(1000);
display.clearDisplay();
}

Department of ECE Page 61


IOT Lab

void loop() {
delay(1000);
humi = HT.readHumidity();
tempC = HT.readTemperature();
tempF = HT.readTemperature(true);

Serial.print("Humidity:");
Serial.print(humi,0);
Serial.print("%");
Serial.print(" Temperature:");
Serial.print(tempC,1);
Serial.print("C ~ ");
Serial.print(tempF,1);
Serial.println("F");

display.clearDisplay();
oledDisplayHeader();
oledDisplay(3,5,28,humi,"%");
oledDisplay(2,70,16,tempC,"C");
oledDisplay(2,70,44,tempF,"F");
display.display();
}
void oledDisplayHeader(){
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.print("Humidity");
display.setCursor(60, 0);

Department of ECE Page 62


IOT Lab

display.print("Temperature");
}
void oledDisplay(int size, int x,int y, float value, String unit){
int charLen=12;
int xo=x+charLen*3.2;
int xunit=x+charLen*3.6;
int xval = x;
display.setTextSize(size);
display.setTextColor(WHITE);

if (unit=="%"){
display.setCursor(x, y);
display.print(value,0);
display.print(unit);
} else {
if (value>99){
xval=x;
} else {
xval=x+charLen;
}
display.setCursor(xval, y);
display.print(value,0);
display.drawCircle(xo, y+2, 2, WHITE); // print degree symbols ( )
display.setCursor(xunit, y);
display.print(unit);
}

Department of ECE Page 63


IOT Lab

OBSERVATIONS:

RESULT AND CONCLUSION:


We have understood the working of DHT11 temperature and humidity sensor and how to
integrate it with Arduino Uno. Its about integrating SSD1306 OLED display with Arduino
Uno.

Department of ECE Page 64


IOT Lab

Experiment 8

Objective: To interface Bluetooth with Arduino/Raspberry Pi and write a program to send


sensor data to smartphone using Bluetooth.

Resource Required:

 An Arduino. Any model can be used, but all code and schematics in this manual will
be for the Uno.
 An Android Smartphone that has Bluetooth.
 HC-05 Bluetooth Module
 Android Studio (To develop the required Android app)
 USB cable for programming and powering the Arduino
 DHT-11 temperature and humidity sensor

Circuit:

1. Connection with Bluetooth

Department of ECE Page 65


IOT Lab

2. Connection with DHT11

Code:

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

BTSerial.begin(38400);

Department of ECE Page 66


IOT Lab

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

delay(500);

while (BTSerial.available()) {

Serial.write(BTSerial.read());

dht.begin();

void loop()

{ char c;

if(Serial.available())

c = Serial.read();

if(c=='t')

Department of ECE Page 67


IOT Lab

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

Serial.print(h);

Serial.print(" %\t");

Serial.print("Temperature: ");

Serial.print(t);

Serial.print(" *C ");

Serial.print("Heat index: ");

Serial.print(hic);

Department of ECE Page 68


IOT Lab

Serial.print(" *C ");

RESULT AND CONCLUSION:

The Bluetooth device and DHT 11 sensor have been interfaced with Arduino Uno
successfully and sent sensor data to smart phone.

Department of ECE Page 69


IOT Lab

Experiment 9

Objective: To interface Bluetooth with Arduino/Raspberry Pi and write a program to turn


LED ON/OFF when ‗1‘/‘0‘ is received from smartphone using Bluetooth.

Resource Required:

 An Arduino. Any model can be used, but all code and schematics in this manual will
be for the Uno.
 An Android Smartphone that has Bluetooth.
 HC-05 Bluetooth Module
 Android Studio (To develop the required Android app)
 USB cable for programming and powering the Arduino
 LED and resistor

Circuit:

Department of ECE Page 70


IOT Lab

Code:

char data = 0; //Variable for storing received data

void setup()

Serial.begin(9600); //Sets the data rate in bits per second (baud) for serial data
transmission

pinMode(13, OUTPUT); //Sets digital pin 13 as output pin

void loop()

if(Serial.available() > 0) // Send data only when you receive data:

data = Serial.read(); //Read the incoming data and store it into variable data

Serial.print(data); //Print Value inside data in Serial monitor

Serial.print("\n"); //New line

if(data == '1') //Checks whether value of data is equal to 1

digitalWrite(13, HIGH); //If value is 1 then LED turns ON

else if(data == '0') //Checks whether value of data is equal to 0

digitalWrite(13, LOW); //If value is 0 then LED turns OFF


Department of ECE Page 71
IOT Lab

} }

Installing the Android Application

Download the application from Amazon App Store or Github.

 Pair your device with the HC 05/06 Bluetooth module:


 Turn ON the HC 05/06 Bluetooth module by powering the Arduino.
 Scan your smartphone for available devices.3. Pair your smartphone to the HC 05/06
by entering default password 1234 OR 0000.
 Install the LED application on your Android device.
 Open the application.

 Press "paired devices".


 Select your Bluetooth module from the list (HC-05/06)

Department of ECE Page 72


IOT Lab

 After connecting successfully, press the ON button to turn the LED on and the OFF
button to turn the LED off.
 Disconnect the button to disconnect the Bluetooth module.

RESULT AND CONCLUSION:


The Bluetooth device and LED have been interfaced with Arduino Uno and LED has been
operated using smart phone.

Department of ECE Page 73


IOT Lab

Experiment 10
Objective: Write a program on Arduino/Raspberry Pi to upload temperature and humidity
data to thingspeak cloud.

Resource required:

 Arduino Uno
 ESP8266 WiFi Module
 DHT11 Sensor
 Breadboard
 Jumper Wires

Circuit Diagram:

Department of ECE Page 74


IOT Lab

Procedure:

Step 1: ThingSpeak Setup for Temperature and Humidity Monitoring

For creating your channel on Thingspeak you first need to Sign up on Thingspeak. In case if
you already have account on Thingspeak just sign in using your id and password.

For creating your account go to www.thinspeak.com

Click on Sing up if you don‘t have account and if you already have account click on sign in.

After clicking on signup fill your details.

After this verify your E-mail id and click on continue.

Step 2: Create a Channel for Your Data

Once you Sign in after your account verification, create a new channel by clicking ―New
Channel‖ button. After clicking on ―New Channel‖, enter the Name and Description of the
data you want to upload on this channel. For example I am sending my DHT11 sensor data,
so I named it as DHT11 data.

Enter the name of your data ‗Temperature‘ in Field1 and ‗Humidity‘ in Field2. If you want to
use more Fields you can check the box next to Field option and enter the name and
description of your data.

After this click on save channel button to save your details.

Step 3: API Key

To send data to Thingspeak, we need a unique API key, which we will use later in our code
to upload our sensor data to Thingspeak Website.

Click on ―API Keys‖ button to get your unique API key for uploading your sensor data.

Department of ECE Page 75


IOT Lab

Code:

#include <stdlib.h>

#include <DHT.h>

#define DHTPIN 5 // DHT data pin connected to Arduino pin 5

#define DHTTYPE DHT11 // DHT11 (DHT Sensor Type )

DHT dht(DHTPIN, DHTTYPE); // Initialize the DHT sensor

#define SSID "WiFi Name" // "WiFi Name"

#define PASS "WiFi Password" // "Password"

#define IP "184.106.153.149"// thingspeak.com ip

String msg = "GET /update?key=Your API Key"; //change it with your key...

float temp;

int hum;

String tempC;

int error;

void setup()

Serial.begin(115200); // use default 115200.

Serial.println("AT");

Department of ECE Page 76


IOT Lab

delay(5000);

if(Serial.find("OK")){

connectWiFi();

void loop(){

start:

error=0;

temp = dht.readTemperature();

hum = dht.readHumidity();

char buffer[10];

tempC = dtostrf(temp, 4, 1, buffer);

updateTemp();

if (error==1){

goto start;

delay(5000);

Department of ECE Page 77


IOT Lab

void updateTemp(){

String cmd = "AT+CIPSTART=\"TCP\",\"";

cmd += IP;

cmd += "\",80";

Serial.println(cmd);

delay(2000);

if(Serial.find("Error")){

return;

cmd = msg ;

cmd += "&field1=";

cmd += tempC;

cmd += "&field2=";

cmd += String(hum);

cmd += "\r\n";

Serial.print("AT+CIPSEND=");

Serial.println(cmd.length());

if(Serial.find(">")){

Department of ECE Page 78


IOT Lab

Serial.print(cmd);

else{

Serial.println("AT+CIPCLOSE");

//Resend...

error=1;

boolean connectWiFi(){

Serial.println("AT+CWMODE=1");

delay(2000);

String cmd="AT+CWJAP=\"";

cmd+=SSID;

cmd+="\",\"";

cmd+=PASS;

cmd+="\"";

Serial.println(cmd);

delay(5000);

Department of ECE Page 79


IOT Lab

if(Serial.find("OK")){

return true;

}else{

return false;

Result:

RESULT AND CONCLUSION:

Account has created on thingspeak cloud and got API Key successfully. Temperature and
humidity data have been uploaded on thingspeak successfully.

Department of ECE Page 80


IOT Lab

Experiment 11
Objective: Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity
data from thingspeak cloud.

Resource required:

 Arduino Uno
 ESP8266 WiFi Module
 DHT11 Sensor
 Breadboard
 Jumper Wires

Circuit Diagram:

Department of ECE Page 81


IOT Lab

Procedure:

Follow steps mentioned in experiment 10 to create account and upload data on thingspeak
cloud.

Code for retrieve data from thingspeak cloud:

#include "ThingSpeak.h"

#include <ESP8266WiFi.h>

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

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

WiFiClient client;

//---------Channel Details---------//

unsigned long counterChannelNumber = 12345; // Channel ID

const char * myCounterReadAPIKey = "xxxxxxxxxxxxxxxx"; // Read API Key

const int FieldNumber1 = 1; // The field you wish to read

const int FieldNumber2 = 2; // The field you wish to read

//-------------------------------//

void setup()

Serial.begin(115200);
Department of ECE Page 82
IOT Lab

WiFi.mode(WIFI_STA);

ThingSpeak.begin(client);

void loop()

//----------------- Network -----------------//

if (WiFi.status() != WL_CONNECTED)

Serial.print("Connecting to ");

Serial.print(ssid);

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

while (WiFi.status() != WL_CONNECTED)

WiFi.begin(ssid, pass);

delay(5000);

Serial.println("Connected to Wi-Fi Succesfully.");

Department of ECE Page 83


IOT Lab

//--------- End of Network connection--------//

//---------------- Channel 1 ----------------//

long temp = ThingSpeak.readLongField(counterChannelNumber, FieldNumber1,


myCounterReadAPIKey);

statusCode = ThingSpeak.getLastReadStatus();

if (statusCode == 200)

Serial.print("Temperature: ");

Serial.println(temp);

else

Serial.println("Unable to read channel / No internet connection");

delay(100);

//-------------- End of Channel 1 -------------//

//---------------- Channel 2 ----------------//

long humidity = ThingSpeak.readLongField(counterChannelNumber, FieldNumber2,


myCounterReadAPIKey);

Department of ECE Page 84


IOT Lab

statusCode = ThingSpeak.getLastReadStatus();

if (statusCode == 200)

Serial.print("Humidity: ");

Serial.println(humidity);

else

Serial.println("Unable to read channel / No internet connection");

delay(100);

//-------------- End of Channel 2 -------------//

RESULT AND CONCLUSION:

Data retrieved from thingspeak cloud successfully.

Department of ECE Page 85


IOT Lab

Experiment 12
Objective: To install MySQL database on Raspberry Pi and perform basic SQL queries.

Resource required:

 Raspberry Pi
 Micro SD Card
 Power Supply
 Ethernet Cord or WiFi dongle (The Pi 3 has WiFi inbuilt)

Procedure and commands:

A. Installing MySQL to Raspberry Pi:

1. Before we get started with installing MySQL to our Raspberry Pi, we must first update our
package list and all installed packages.

We can do this by running the following two commands.

Terminal$

 sudo apt update


 sudo apt upgrade

2.The next step is to install the MySQL server software to your Raspberry Pi.

Installing MySQL to the Raspberry Pi is a simple process and can be done with the following
command.

Terminal$

 sudo apt install mariadb-server

Department of ECE Page 86


IOT Lab

3. With the MySQL server software installed to the Raspberry Pi, we will now need to secure
it by setting a password for the ―root‖ user.

By default, MySQL is installed without any password set up meaning you can access the
MySQL server without any authentication.

Run the following command to begin the MySQL securing process.

 sudo mysql_secure_installation

Just follow the prompts to set a password for the root user and to secure your MySQL
installation. For a more secure installation, you should answer ―Y‖ to all prompts when asked
to answer ―Y‖ or ―N―. These prompts will remove features that allows someone to gain
access to the server easier.

Make sure you write down the password you set during this process as we will need to use it
to access the MySQL server and create databases and users for software such as WordPress
or PHPMyAdmin.

4. Now if you want to access your Raspberry Pi‘s MySQL server and start making changes to
your databases, you can enter the following command.

 sudo mysql -u root -p

5. You will be prompted to enter the password that we just created in step 3 for MySQL‘s
root user.

6. You can now enter MYSQL commands to create, alter, and delete databases. Through this
interface, you can also create or delete users and assign them the rights to manage any
database.

Department of ECE Page 87


IOT Lab

7. There are two different ways you can quit out of the MYSQL command line, the first of
those is to type ―quit;‖ into the MySQL interface.

The other way of quitting out of the MYSQL command line is to press CTRL + D.

8. At this point, you will now have successfully setup MySQL on your Raspberry Pi. Our
next few sections will go into making better use of this database.

B. Performing Queries:

1. Before we proceed to create a MySQL user and database on our Raspberry Pi, we must
first log back into the MySQL command-line tool.

Run the following command to log in to the MySQL command line. You will be prompted to
enter the password for the ―root‖ account that you set up earlier.

Terminal$

 sudo mysql -u root -p

2. Let‘s start by creating a MySQL database using the following command.

This command is super simple and is just ―CREATE DATABASE‖ followed by the name
that you want to give the database. In our example, we will be calling this database
―exampledb―.

mysql >

 CREATE DATABASE exampledb;

3. Next, we will create a MySQL user that we will assign to our new database. We can create
this user by running the following command. For this example, we will be calling the user

Department of ECE Page 88


IOT Lab

―exampleuser‖ and giving it the password ―pimylifeup―. When creating your own, make sure
you replace both of these.

 CREATE USER 'exampleuser'@'localhost' IDENTIFIED BY 'pimylifeup';

4. With the user created, we can now go ahead and grant all privileges to the user so that it
can interact with the database. This command will grant all permissions to our ―exampleuser‖
for all tables within our ―exampledb‖ database.

 GRANT ALL PRIVILEGES ON exampledb.* TO 'exampleuser'@'localhost';

5. The final thing we need to do for both our MySQL database and user to be finalized is to
flush the privilege table. Without flushing the privilege table, the new user won‘t be able to
access the database.

We can do this by running the following command.

 FLUSH PRIVILEGES;

6. Copy Database To/ From A Remote Server

Insecure Method
If you have direct access to the remote server and aren't worried about security

 Mysqldumb -h[server] -u[user] -p[password] [data base name] | mysql -h


[server] -u [user] -p[password] [databasename]

Secure Method

If you can SSH into the remote server you can use this

Department of ECE Page 89


IOT Lab

mysqldump -h [server] -u [user] -p[password] [databasename] | ssh


[ssh_username]@remote_domain.com mysql -u [user] -p[password] [databasename]

You will then be promoted for the SSH password of the remote server

RESULT AND CONCLUSION:

MySQL database has been installed successfully and performed queries.

Department of ECE Page 90

You might also like