IOT Lab Manual - Merged - 2
IOT Lab Manual - Merged - 2
IOT Lab Manual - Merged - 2
Jaipur
Name:
Sem/Section:
Presentation/Neatness (2)
Date of Evaluation
Faculty Signature
S.No. Name of Experiment
Execution (4)
Total (10)
1
10
11
12
IOT Lab
LIST OF EXPERIMENTS
Exp:12 To install MySQL database on Raspberry Pi and perform basic SQL queries.
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.
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.
EXPERIMENT NO.1
OBJECTIVE: Study the fundamental of IOT softwares and components.
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.
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.
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
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.
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.
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
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.
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.
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
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.
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.
Wearable electronic devices are small devices that can be worn on the head, neck, arms,
torso, and feet.
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.
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
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.
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.
EXPERIMENT NO.2
OBJECTIVE: Familiarization with Arduino/Raspberry Pi and perform necessary software
installation
Choose the installation directory (we suggest to keep the default one)
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.
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++.
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
Observations: We have interfaced the led with Arduino Uno and observe the simulation
result.
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.
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:
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.
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:
{
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:
OBSERVATIONS: We have interfaced the led with Arduino Uno and observe the
simulation result.
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.
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.
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:
} else {
digitalWrite(ledPin, LOW);
}
}
CIRCUIT DIAGRAM:
OBSERVATIONS: We have interfaced the led with Arduino Uno and observe the
simulation result.
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.
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.
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.
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);
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.
We have performed the experiment of led interfacing with Arduino and to turn ON for 1 sec
after every 2 seconds.
Experiment No- 5
OBJECTIVE: To Interface DHT11 sensor with Arduino /Raspberry Pi and write a program
to print temperature and humidity readings.
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
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:
Circuit Diagram:
Observations: We have interfaced the led with Arduino Uno and observe the simulation
result.
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.
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.
THEORY:
ARDUINO CODE:
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
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.
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:
OBSERVATIONS:
When pushbutton is pressed, then the motor rotates due to amount of current provided
required to turn on relay by the pushbutton.
Experiment No- 7
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.
5V--------------------VCC
GND-----------------GND
SDA/A4--------------SDA
SCL/A5---------------SCL
Adafruit_GFX.h https://github.com/adafruit/Adafruit-GFX-Library
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.
Open manage library from sketch -> include library -> manage libraries
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();
}
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);
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);
}
OBSERVATIONS:
Experiment 8
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:
Code:
#include <SoftwareSerial.h>
#include "DHT.h"
#define DHTPIN 2
SoftwareSerial BTSerial(4,5);
void setup() {
Serial.begin(9600);
BTSerial.begin(38400);
delay(500);
while (BTSerial.available()) {
Serial.write(BTSerial.read());
delay(500);
while (BTSerial.available()) {
Serial.write(BTSerial.read());
dht.begin();
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)) {
return;
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(hic);
Serial.print(" *C ");
The Bluetooth device and DHT 11 sensor have been interfaced with Arduino Uno
successfully and sent sensor data to smart phone.
Experiment 9
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:
Code:
void setup()
Serial.begin(9600); //Sets the data rate in bits per second (baud) for serial data
transmission
void loop()
data = Serial.read(); //Read the incoming data and store it into variable data
} }
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.
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:
Procedure:
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.
Click on Sing up if you don‘t have account and if you already have account click on sign in.
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.
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.
Code:
#include <stdlib.h>
#include <DHT.h>
String msg = "GET /update?key=Your API Key"; //change it with your key...
float temp;
int hum;
String tempC;
int error;
void setup()
Serial.println("AT");
delay(5000);
if(Serial.find("OK")){
connectWiFi();
void loop(){
start:
error=0;
temp = dht.readTemperature();
hum = dht.readHumidity();
char buffer[10];
updateTemp();
if (error==1){
goto start;
delay(5000);
void updateTemp(){
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(">")){
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);
if(Serial.find("OK")){
return true;
}else{
return false;
Result:
Account has created on thingspeak cloud and got API Key successfully. Temperature and
humidity data have been uploaded on thingspeak successfully.
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:
Procedure:
Follow steps mentioned in experiment 10 to create account and upload data on thingspeak
cloud.
#include "ThingSpeak.h"
#include <ESP8266WiFi.h>
WiFiClient client;
//---------Channel Details---------//
//-------------------------------//
void setup()
Serial.begin(115200);
Department of ECE Page 82
IOT Lab
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
void loop()
if (WiFi.status() != WL_CONNECTED)
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println(" ....");
WiFi.begin(ssid, pass);
delay(5000);
statusCode = ThingSpeak.getLastReadStatus();
if (statusCode == 200)
Serial.print("Temperature: ");
Serial.println(temp);
else
delay(100);
statusCode = ThingSpeak.getLastReadStatus();
if (statusCode == 200)
Serial.print("Humidity: ");
Serial.println(humidity);
else
delay(100);
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)
1. Before we get started with installing MySQL to our Raspberry Pi, we must first update our
package list and all installed packages.
Terminal$
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$
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.
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.
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.
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$
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 >
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
―exampleuser‖ and giving it the password ―pimylifeup―. When creating your own, make sure
you replace both of these.
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.
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.
FLUSH PRIVILEGES;
Insecure Method
If you have direct access to the remote server and aren't worried about security
Secure Method
If you can SSH into the remote server you can use this
You will then be promoted for the SSH password of the remote server