0% found this document useful (0 votes)
209 views57 pages

Iot Lab Manual - For Mca

MCA

Uploaded by

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

Iot Lab Manual - For Mca

MCA

Uploaded by

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

INTERNET OF THINGS LAB Department of ECE,KHIT

KALLAMHARANADHAREDDYINSTITUTEOFTECHNOLOGY
(AUTONOMOUS )
CHOWDAVARAM, Guntur-522019, ANDHRA PRADESH

INTERNET OF THINGS
LAB MANUAL

(R-23)

MASTER OF COMPUTER APPLICATION


INTERNET OF THINGS LAB Department of ECE,KHIT

LIST OF EXPERIMENTS
Course Objectives:
1. Students will understand the concepts of Internet of Things and can able to build IoT applications

Course Outcomes:
1. Interpret the impact and challenges posed by IoT networks leading to new architectural models.
2. Compare and contrast the deployment of smart objects and the technologies to connect them to network.
3. Appraise the role of IoT protocols for efficient network communication.
4. Elaborate the need for Data Analytics and Security in IoT.
5. Illustrate different sensor technologies for sensing real world entities and identify the applications of
IoT in Industry.

(Any of the 10 experiments are required to be conducted)

List of Experiments:

1. Study the fundamental of IOT softwares and components.


2. Familiarization with Arduino/Raspberry Pi and perform necessary software installation.
3. To interface LED/Buzzer with Arduino/Raspberry Pi and write a program to turn ON LED for 1 sec
after every 2 seconds.
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.
5. To interface DHT11 sensor with Arduino/Raspberry Pi and write a program to print temperature
and humidity readings.
6. To interface motor using relay with Arduino/Raspberry Pi and write a program to turn ON motor
when push button is pressed.
7. To interface OLED with Arduino/Raspberry Pi and write a program to print temperature and
humidity readings on it.
8. To interface Bluetooth with Arduino/Raspberry Pi and write a program to send sensor data to
smartphone using Bluetooth.
9. 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.
10. Write a program on Arduino/Raspberry Pi to upload temperature and humidity data to thingspeak
cloud.
11. Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity data from
thingspeak cloud.
12. Write a program on Arduino/Raspberry Pi to publish temperature data to MQTT broker.

13. Write a program to create TCP server on Arduino/Raspberry Pi and respond with humidity data to
TCP client when requested.
INTERNET OF THINGS LAB Department of ECE,KHIT

EXPERIMENT-1

Fundamentals of IOT
AIM: Study the fundamental of IOT software 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 smart phone 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.
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
INTERNET OF THINGS LAB Department of ECE,KHIT

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 smart phone.
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.

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 smart phones, 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.
INTERNET OF THINGS LAB Department of ECE,KHIT

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.
INTERNET OF THINGS LAB Department of ECE,KHIT

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.

End point 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 theIoT 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.
INTERNET OF THINGS LAB Department of ECE,KHIT

 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.

1. 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 Arcomin 1999 and is designed for
M2Mcommunication. It‘s normally used for far away 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.
INTERNET OF THINGS LAB Department of ECE,KHIT

2. 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: State the connection between the message queue and the change.

3. 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.
INTERNET OF THINGS LAB Department of ECE,KHIT

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.
c. Wearable Electronic Devices

Wearable electronic devices are small devices that can be worn on the head, neck, arms,torso ,and feet.
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.

IoTHardware–IoTSensors
INTERNET OF THINGS LAB Department of ECE,KHIT

Experiment – 02
Familiarization of an Arduino

To program the Arduino we need an Integrated Development Environment (IDE) called


“Arduino”. This is an official and open source IDE introduced by Arduino.cc and it is used for
writing, compiling and uploading the code to an Arduino. In this article I will discuss on the detailed
introduction to Arduino IDE. Where I will uncover all the parts of its interface and how to use it.

 First we have to download and install this IDE.


 Here is the Download link – https://www.arduino.cc/en/main/software.
 Arduino IDE is available for Windows, MAC, Linux, Linux ARM (Raspberry PI).
 After download, install it and you are done. Now let’s explore this IDE.
As mentioned earlier this is an open source IDE which makes the coding very easy that
even a common person with no high technical knowledge can make codes for it. This IDE is
available for Windows, MAC, Linux operating systems and it runs on the JAVA platform. It is
based on “Processing” programming environment and comes with many inbuilt functions and
command which makes the software very easy to use.
INTERNET OF THINGS LAB Department of ECE,KHIT

The code that we write in this IDE is known as sketch. After compiling an sketch it gives a Hex file
which we can upload to the Arduino. The code is written in the C or C++ language. Its user interface has a
navigation menu bar on the top, text editor in which we write the code and a output pane where compilation
logs are shown.

At the top name of the sketch and version of Arduino is displayed. Then we have the Menu bar just
below that. In the menu bar we have five options. Let’s see them one by one.
1. File
In this menu we have these options.

It is used to open a new sketch


New
Open To open existing sketch
Open Recent To open recent sketches
Sketchbook To open the entire sketches
INTERNET OF THINGS LAB Department of ECE,KHIT

Example To open example codes


Close To close the window
Save To save the sketch
Save As To save the same sketch with different
name
Page Setup To setup the page with portrait or landscape
Print To print the text editor
Preferences It is used to set the page preferences, the
sketchbook location, compilation options
etc..
Quit To close all active windows

2. Edit
This section is used for editing the code text such as copy, paste, select all, find, copy as HTML etc.
3. Sketch
This is used for compiling, uploading, exporting the compiled code as binary file, to see the sketch
folder.
4. Tools
This is mainly used to select the Arduino type and port, burning boot loader to the new
microcontroller. There are also some other option are available which are serial monitor and serial
plotter. More of that is explained later.
5. Help
This is help desk of the software.
Short-cut Buttons In Arduino IDE
There are some important shortcut buttons are also available just under the menu bar. Which are
verify (compile), upload, new, open, save and serial monitor.

Verify
Button with right check mark is for verify the code we have just written. If we written the code without
any logical or syntax or any errors, it will compile successfully. Just in case we have written
something wrong, it will give an error message in output pane about what and where the error is.
Shortcut key for verify is “CTRL+R”.
INTERNET OF THINGS LAB Department of ECE,KHIT

Upload
This shortcut button showing right sided arrow is called upload and used to upload the code into the
microcontroller of Arduino. Shortcut key for this is “CTRL+U”.
New
This shortcut button showing dotted paper is used to open a new sketch. Shortcut key to open a new
sketch is “CTRL+N”.
Open
The button with arrow up is used open an existing sketch. Shortcut key to open an existing sketch is
“CTRL+O”.
Save
The button with arrow down is used to save the sketch. Shortcut key to save a sketch is “CTRL+S”.
Serial monitor
As we press this button a separate window will pop up which will show the data that that is being
transmitted and received from an Arduino board. Shortcut key for open serial monitor is
“CTRL+SHIFT+M”
INTERNET OF THINGS LAB Department of ECE,KHIT

To start sending or receiving serial data we have to start serial communication in the code. Let’s see
how we can start serial communication in Arduino.

Here is the code and output serial data. First we have initiated the serial communication by using
Serial.begin command and giving it the baud rate. Baud rate is the rate at which data is
transmitted or received. We can choose other baud rates also which are valid and the other device is
compatible with.
Then we have printed the two string using Serial.println() command and given one second delay
between them. This printing process will run infinitely till Arduino is powered because we have put
the code in “void loop” function.

Serial plotter in Arduino


There is another serial function and we call it “serial plotter”. Basically it is same as serial monitor
but it shows the serial data in the form of graph except string data. Suppose we are working with
some kind of heat sensor which output a data according to heat. So, serial plotter will show us heat
in the graphically. We can open serial plotter window by using shortcut key “CTRL+SHIFT+L”.
INTERNET OF THINGS LAB Department of ECE,KHIT

Here in the code, “i” is declared integer as globally. It means that we can use this everywhere in the
code. Then we started serial communication at 9600baud rate. Using the for loop value of “i” goes
up to 254 from 0. Then we print “i” serially. This basically means that we are printing the value of
“i”. As you can see that we have the graph of integer “i” printed on serial plotter window. Here x-
axis depends on the number and y-axis depends upon the highest value of serial data available.

Selecting the board type and port in Arduino


To upload the code on Arduino or serial communication or serial plotting we need to choose the right
board and port of board. These options will be available under “Tools” option and put the mouse
arrow on “Board”. It will open a window like figure shown below.
INTERNET OF THINGS LAB Department of ECE,KHIT

From here you can choose the board you have connected form computer. And then go to port
option. Here we will be selecting the port of your operating system from which your board is
connected. It will look something like this.

In my case my Arduino UNO is connected to my COM11 port.


After selecting right board and port you can upload code to the board, see and plot the serial data.
During the code is uploading, the RX ant TX led on board should blink.
INTERNET OF THINGS LAB Department of ECE,KHIT

Including the libraries in Arduino code


In programming world libraries are so important. It consists the instruction set and predefined
function that we can run without writing it repeatedly. It adds extra functionality to any sketch that we
are writing by just including it. In Arduino we can include any library by using a
command“#include<library_name.h>” or by going to Sketch>Include Library>Select any Library.

You can include only those libraries which are available in your Ardiuno’s “Library” folder.
If any library is not present in your library folder then you can add it by downloading it from internet.
Or you can do it within your Arduino IDE by going to Tool>Manage Library and search the library
name and click install. Shortcut for library manager is “CTRL+SHIFT+I”.
INTERNET OF THINGS LAB Department of ECE,KHIT

EXPERIMENT-3

a)To Interface an LED/BUZZER with Arduino

Aim: a) Write a program to interface LED with Arduino and to turn ON LED for 1sec after every 2secs.
Apparatus:
Arduino IDE software
Arduino Board
LED
Bread Board
Serial Cable
Jumper wires

Theory:

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

Nowconnectaresistortopositivelegandotherendofresistorto5V.Cathodewillbe connected to Arduino


GPIO, in our case pin 13.

Digital Write(LED,HIGH); will turn the LED ON. Now we need to keep the LED ON for 1 sec.
We do so by keeping the micro controller idle (or we make it to wait) for 1sec.

Delay (1000); is the function we use to keep the microcontroller idle for 1sec.

After1second, we need to turn LED OFF. We do so with instruction

Digital Write(LED,LOW); this will turn LED OFF.

Now we need to keep the LED in its OFF state for 2sec (before it is turned ON again).

Then 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 microcontroller will begin executing from beginning statement inside loop() after waiting
1second to keep LED OFF.

So the LED is ON again after 1 second.


INTERNET OF THINGS LAB Department of ECE,KHIT

CIRCUIT DIAGRAM:

Program:

int led pin = 13; //set pin no of Arduino to which led is connected
void setup() {
Pin Mode(led pin, OUTPUT); //initialize digital pin LED_BUILT IN as an output.

} //the loop f unction runs over and over again


forever void loop() {

Digital Write(led pin, LOW ); //turn the LED off by making the voltage LOW
delay(1000);
digital Write(led pin, HIGH); //turn the LED ON by making the voltage HIGH
delay(2000);
}

Procedure:
1. LED Connections: Connect the LED to the breadboard.
2. The LED has two legs, the longer of which is the anode (positive) and the shorter of which is the
cathode (negative).
3. Resistor Connection: Insert one end of the resistor into the same row of the breadboard as the LED’s
Anode.
4. The resistor’s other end should be connected to the Arduino’s digital output pin.
5. Ground (GND) Connection: Connect a jumper wire from the same row as the LED’s cathode to any
Arduino board GND (Ground) pin.
6. This connects the circuit to the ground of the Arduino.
7. The circuit is now complete.
8. When you upload a simple Arduino program that controls the LED.
9. The microcontroller on the Arduino board executes the program, Then LED will blink .

Result:
INTERNET OF THINGS LAB Department of ECE,KHIT

b)To Interface BUZZER with Arduino

Aim: b)Write a program to interface BUZZER with Arduino

Apparatus:
Arduino IDE software
Arduino Board
Bread Board
Serial Cable
Jumper wires
Buzzer

Theory:

Piezo buzzer is an electronic device commonly used to produce sound.


Piezo buzzer is based on the inverse principle of piezo electricity discovered in 1880 by
Jacques and Pierre Curie. It is the phenomena of generating electricity when mechanical pressure is
applied to certain materials and the vice versa is also true. Such materials are called piezo electric
materials.
Piezo electric materials are either naturally available or manmade. Piezo ceramic is class of
manmade material, which poses piezo electric effect and is widely used to make disc, the heart of
piezo buzzer.
When subjected to an alternating electric field they stretch or compress, in accordance with the
frequency of the signal thereby producing sound.
INTERNET OF THINGS LAB Department of ECE,KHIT

Program:

Const in buzzer=9; //buzzer to arduino pin9


void setup()
{
Pin Mode(buzzer, OUTPUT); //Set buzzer-pin9 as an output
}
Void loop()
{
Tone (buzzer,1000); //Send 1KHz sound signal...
delay(1000); // ...for 1 sec
no Tone(buzzer); //Stop sound
delay(2000); // ...for 1sec
}

Procedure:

1. Connect the Supply wire (RED) of the buzzer to the Digital Pin 9 of the Arduino through a 100 ohm
resistor.
2. Connect the Ground wire (BLACK) of the buzzer to any Ground Pin on the Arduino.
3. The circuit is now complete.
4. When you upload a simple Arduino program that controls the LED.
5. The microcontroller on the Arduino board executes the program, Then LED will blink

Result:
INTERNET OF THINGS LAB Department of ECE,KHIT

EXPERIMENT-4
To Interface Pushbutton with Arduino

Aim: Write a program to turn ON LED when push button is pressed or at sensor detection.

Apparatus:
Arduino IDE software
Arduino Board
Push Button
Serial Cable
Jumper Wires
Bread Board
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 K Ohms) 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 (un pressed) 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.)
INTERNET OF THINGS LAB Department of ECE,KHIT

Procedure:

1. First, make sure to power off your Arduino – remove any USB cable.
2. Plug a black wire between the blue line of the breadboard and a ground (GND) pin on the
Arduino board.
3. Plug this shorter leg to the ground (blue line here) of the circuit.
4. Connect the longer leg of the LED to a digital pin (here pin no 8, you can change it).
5. Add a 220 Ohm resistor in between to limit the current going through the LED.
6. Add the push button to the breadboard, like in the picture.
7. Connect one leg of the button to the ground, and put a 10k Ohm resistor in between..
8. Add a red wire between another leg of the button and VCC (5V).
9. Finally, connect a leg of the button (same side as the pull down resistor) to a digital pin (here 7).

Program:

Const int switch Pin=9; //SwitchConnectedtoPIN4 const


int led Pin = 8; //LED Connected to PIN 8
Int switch State=0; //Variable for reading Switch status
void setup()
{
Pin Mode(led Pin, OUTPUT); //LED PIN is Output

pin Mode(switch Pin, INPUT); //Switch PIN is input with PULLUP


}
Void loop()
{
Switch State=digital Read(switch Pin); //Reads the status of the switch.

if (switch State == LOW) / /If the switch is pressed


{
Digital Write(led Pin, HIGH); //LEDON
delay(500); //0.5 Second
Delay digital Write(led Pin, LOW); //LEDOFF
}
}

Result:
INTERNET OF THINGS LAB Department of ECE,KHIT

b) To Interface Digital LDR sensor with Arduino

Aim: Write a program to Interface Digital LDR sensor with Arduino and to turn ON LED at sensor detection.
Apparatus:
Arduino IDE software
Arduino Board
LDR Sensor
LED
Serial Cable
Jumper Wires

Theory:

LDR sensor module is used to detect the intensity of light. It is associated with both analog output
pin and digital output pin labelled as AO and DO respectively on the board. When there is light, the
resistance of LDR will become low according to the intensity of light. The greater the intensity of light,
the lower the resistance of LDR. The sensor has a potentiometer knob that can be adjusted to change
the sensitivity of LDR towards light.
Specification:
Input Voltage: DC 3.3V to 5V
Output: Analog and Digital
Sensitivity adjustable

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.
INTERNET OF THINGS LAB Department of ECE,KHIT

Program:
const int led Pin = 9;
const int ldr Pin=A0;
void setup()
{
Pin Mode(led Pin, OUTPUT);
pin Mode (ldr Pin, INPUT);
}
void loop()
{
Int ldr Status=analog Read (ldr Pin);

if (ldr Status <= 200)

Digital Write (led Pin, HIGH);


}
else
{
Digital Write (led Pin, LOW);
}
}

Procedure:
1. Connecting the LDR sensor’s VCC pin to the 5V output on the Arduino for power.
2. Connect the GND pin of the LDR to one of the GND pins on the Arduino.
3. The finally connect the Analog Output Pin (A0) to A0 of Arduino
4. Open Arduino IDE software.
5. Now write the program in Sketch area in Arduino.
6. Save the program and click on the verify button.
7. Select the board as Arduino in tools options. Now click on verifybutton wait to complete the
compilation process.
8. Now click on upload button and wait to complete the uploading process.
9. Check the ouput in serial monitor.

Result:
INTERNET OF THINGS LAB Department of ECE,KHIT

C) To Interface Digital IR sensor with Arduino

Aim: Write a program to Interface Digital IR sensor with Arduino and to turn ON LED at IR sensor detection.
Apparatus:
Arduino IDE software
Arduino Board
Relay
Jumper Wires
LED
IR Sensor
Serial Cable

Theory:

IR sensor is an electronic device that senses the IR radiations in its surroundings. The IR sensor used
here is an active IR sensor that emits IR radiation from the transmitter diode and receives the reflected rays
from the target object through a receiver.

A relay module is an electrical switch that can be opened or closed using an electromagnet. It acts as
a circuit breaker and detects the faulty current in the circuit.

The resistor is a passive electronic component that offers resistance to the current flowing through it.
Here it is used to reduce the current flowing through the LED. A 220Ω resistor is used in this project.
INTERNET OF THINGS LAB Department of ECE,KHIT

Program:
int IR Sensor = 2; // connect ir sensor to arduino pin 2
int LED = 13; // conect Led to arduino pin 13
void setup()
{

Pin Mode (IR Sensor, INPUT); // sensor pin INPUT

pin Mode (LED, OUTPUT); // Led pin OUTPUT


}
Void loop()
{
Int status Sensor=digital Read (IRSensor);
If (status Sensor==1)
digital Write(LED,LOW); //LEDLOW
}
else
{ digital Write(LED,HIGH); //LED High
}
}

Procedure:

1. Connect the Vcc pin of the IR sensor to the Vcc of the Arduino via a breadboard.
2. Connect the ground pin of the IR sensor to the ground of the Arduino.
3. Connect the output pin of the IR sensor to D2 of the Arduino.
4. Connect cathode lead of the LED to the ground rail of the breadboard.
5. Connect the anode lead of the LED to one of the arms of the 220Ω resistor.
6. Connect another arm of the resistor to D3 of the Arduino.
7. Connect the signal pin of the relay module to D3 of the Arduino.
8. Connect the common terminal of the relay module to the positive of the external power supply.
9. Connect the cathode of the LED to the negative terminal of the external power supply.
10. Connect the anode of the LED to one of the arms of the resistor. The other arm of the resistor is
connected to the normally open terminal of the relay module.

RESULT:
INTERNET OF THINGS LAB Department of ECE,KHIT

EXPERIMENT-5
To interface DHT11 sensor with Arduino

Aim: To interface DHT11 sensor with Arduino and to print temperature and humidity readings.

Apparatus:
Arduino IDE software
Arduino Board
DHT11 Sensor
Serial Cable
Jumper Wires

Theory:
The DHT11 detects water vapor by measuring the electrical resistance between two electrodes.
The humidity sensing component is a moisture holding substrate with electrodes applied to the surface.
When water vapor is absorbed by the substrate, ions are released by the substrate which increases the
conductivity between the electrodes.
The change in resistance between the two electrodes is proportional to the relative humidity. Higher
relative humidity decreases the resistance between the electrodes, while lower relative humidity increases the
resistance between the electrodes.

 DHT11 sensor measures and provides humidity and temperature values serially over a single wire.
 It can measure relative humidity in percentage (20 to 90% RH)
 Temperature in degree Celsius in the range of 0 to 50°C.
 It has 4 pins; one of which is used for data communication in serial form.
 Pulses of different T-ON and T-OFF are decoded as logic 1 or logic 0 or start pulse or end of a frame.
INTERNET OF THINGS LAB Department of ECE,KHIT

Program:
#include "DHT.h" //including the dht11 library
#define DHT PIN8 //Declaring pin8 of arduino for the dht11
#define DHT TYPE DHT11 //Definingwhichtypeofdht22weareusing(DHT22orDHT11)
DHT dht(DHT PIN,DHT TYPE); //Declaring a variable name ddht
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 dht11
}voidloop()
{ //Data written in it will run again and again
Float hum =dht.read Humidity(); //Reading the humidity and storing in hum
Float temp=dht.read Temperature(); //Reading the temperature as Celsius and storing in temp

float fah = dht.read Temperature(true);


if (isnan(hum) || isnan(temp) || isnan(fah))
{
Serial.println("Failed to read from DHT sensor!"); return;
}
Float heat_index=dht.compute Heat Index(fah,hum);

float heat_indexC = dht.convert FtoC(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 ");
delay(2000); //Giving a delay of 2seconds
}
INTERNET OF THINGS LAB Department of ECE,KHIT

Procedure:

1. VCC pin of the DHT11 goes into +3v of the Arduino.


2. DATA pin of the DHT11 goes into Analog Pin A0 of the UNO.
3. GND Pin of the DHT11 goes into Ground Pin (GND) of the UNO.
4. Connect the DHT11 Data pin to Arduino Digital Pin 2.
5. Open Arduino IDE software.
6. Now click on upload button and wait to complete the uploading process.

Output:

Result:
INTERNET OF THINGS LAB Department of ECE,KHIT

Experiment - 06
To interface motor using Relay with Arduino
Aim: write a program to interface motor using relay with Arduino and to turn ON
motor when push button is pressed

Apparatus:
Arduino IDE software
Arduino Uno Board
28BYJ-48 Stepper Motor
5V Unipolar
ULN2003 stepper motor driver board
Relay
Serial Cable
Theory:

We can control high voltage electronic devices using relays. A Relay is actually as witch 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 free wheeling 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.
INTERNET OF THINGS LAB Department of ECE,KHIT

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.
INTERNET OF THINGS LAB Department of ECE,KHIT

Program:

const int button Pin = 12;


const int transistor Pin=7;
int button State = 0;
void setup()
{

Pin Mode (button Pin,INPUT_PULLUP);

Pin Mode transistor Pin, OUTPUT);


}
Void loop()
{

Button State=digital Read(button Pin);

if (button State == LOW)


{
Digital Write(transistor Pin,HIGH);
}
else
{
Digital Write(transistor Pin, LOW);
}
}

Procedure:

1. Connect the VCC pin of Relay module to 5v pin of Arduino Board


2. Connect the GND pin of Relay module to GND pin of Arduino Board
3. Connect the IN1of Relay module to 7th pin of Arduino Board
4. Connect the IN2 of Relay module to 8th pin of Arduino Board
5. Then power the relay switch module itself, using the Arduino.
6. We can connect the wires and send signals to activate the relay switches.
7. You should end up with a motor that spins clockwise for 1sec and counter-clockwise for 1sec.

Result:
INTERNET OF THINGS LAB Department of ECE,KHIT

Experiment - 07
To interface OLED with Arduino

Aim: Write a program to interface OLED with Arduino and to print temperature and humidity readings.

Apparatus:
Arduino IDE software
Arduino Uno Board
DHT11 Sensor
Bread Board
Serial Cable

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.

OLED SCREEN

An OLED stands for “Organic LED”. One of its elements is an organic compound for
displaying light. With this, you can write text or graphics in pixel form and display them on your
screen.

The OLED in use in this tutorial uses the SSD1306 driver IC. It’s a dedicated chip for
displaying and driving the OLED’s monochromatic output through a programmable interface.
 The interface of the OLED in this tutorial uses I2C while its pixel characteristic is 128×64.
 It also has a display dimension of 0.96 inches.
INTERNET OF THINGS LAB Department of ECE,KHIT

Procedure:
1. The OLED’s I2C SDA and SCL lines connect to the UNO’s own SDA and SCL lines
2. (which also connect to the A4 and A5 pins).
3. You won’t external need pull-ups as the UNO enables them internally through the library.
4. The DHT11 used here is contained in the KY-015 Temp and Humidity module.
5. However you can wire up the sensor yourself, but you should include an external pull-up resistor on
the output line.
6. Once finished, you can continue writing firmware on the Arduino IDE.

Creating Firmware:

 When you get a new sensor, you should download and include a library.
 Go to the Library Manager by going to Tools -> Manage Libraries…
 Search for DHT11 and install the DHT sensor library.

 Next, download and install the Adafruit SSD1306 library


INTERNET OF THINGS LAB Department of ECE,KHIT

 You should also be getting the Adafruit GFX library automatically upon installing the SSD1306.

 After installing the libraries, you can now include them in your new sketch by going to Sketch ->
Include Library. You should see the DHT Sensor Library and the Adafruit SSD1306 library.
INTERNET OF THINGS LAB Department of ECE,KHIT

 Before going further, you may want to take a look at the example sketches for the DHT11 sensor and
SSD1306 display module.

Go to File -> Examples -> DHT11 sensor library – > DHTester

 For the SSD1306, find the Adafruit SSD1306 example through the SSD1306_128x64_i2c sketch.
INTERNET OF THINGS LAB Department of ECE,KHIT

Program:
#include "DHT.h"
#define DHT11 Pin 2
#define DHT Type DHT11
//OLED
#include<Wire.h>
#include <Adafruit_GFX.h>
#include<Adafruit_SSD1306.h>

DHTHT (DHT11Pin, DHTType);


float humi;
float temp C;
float temp F;

//OLEDdefine
#define SCREEN_WIDTH128 //OLED display width, in pixels
#define SCREEN_HEIGHT64 //OLED display height, in pixels
Adafruit_SSD1306 display (SCREEN_WIDTH, SCREEN_HEIGHT,&Wire,-1);

void setup() {
Serial.begin(9600);
INTERNET OF THINGS LAB Department of ECE,KHIT

//ForDHT11
HT.begin();
//ForOLED I2C
If (!display. begin(SSD1306_SWITCHCAPVCC,0x3C)){
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.display(); //Display logo
delay(1000);
display. Clear Display();
}
void loop() {
delay(1000);
humi = HT.read Humidity();
tempC=HT.read Temperature();
tempF= HT.read Temperature(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.clear Display();
oled Display Header();
oled Display(3,5,28,humi,"%");
oled Display(2,70,16,tempC,"C");
oled Display(2,70,44,tempF,"F");
display.display();
}
void oled Display Header(){

display.set Text Size(1);

display.setTextColor(WHITE);

display.setCursor(0, 0);

display.print("Humidity");

display.setCursor(60, 0);
display.print("Temperature");
INTERNET OF THINGS LAB Department of ECE,KHIT

}
Void oled Display (int size, int x ,int y, float value, String unit)

int charLen=12;
int xo=x+charLen*3.2;
int x unit=x+charLen*3.6;
int x val = x;
display.set Text Size(size);
display.set TextColor(WHITE);

if (unit=="%"){
display.set Cursor(x,y);
display.print(value,0);
display.print(unit);
}
Else
{
if(value>99)

X val=x;
}
else
{
X val=x+char Len;
}

display.set Cursor(x val, y);

display.print(value,0);
display.draw Circle(xo,y+2,2,WHITE);
//print degree
Symbols ()
display.set Cursor(x unit, y);
display.print(unit);
}
}
INTERNET OF THINGS LAB Department of ECE,KHIT

Output:

Result:
INTERNET OF THINGS LAB Department of ECE,KHIT

Pi OSct the mroSD c Experiment – 09

To Interface Bluetooth with Arduino and send sensor data to Smartphone

AIM: write a program to interface Bluetooth with Arduino and to send sensor data to smartphone using
Bluetooth.
Apparatus:
Arduino Board
Arduino IDE Software
Android Studio
Serial Cable
HC-05 Bluetooth Module
Android Phone has Bluetooth
DHT11 Sensor
Jumper wires

Procedure:

1.Connection with Bluetooth Module

To use the HC-05 Bluetooth module,


 Connect the VCC to the 5V output on the Arduino,
 GND to Ground,
 RX to TX pin of the Arduino, and TX to RX pin of the Arduino.
If the module is being used for the first time, you’ll want to change the name, passcode etc.
To do this the module should be set to command mode.
Connect the Key pin to any pin on the Arduino and set it to high
to allow the module to be programme
INTERNET OF THINGS LAB Department of ECE,KHIT

2. Connection with DHT11 Sensor

 To use the DHT-11, the DHT library by Adafruit is used.


 Go here to download the library.
 When the letter “t” is received,
 the temperature, humidity, and heat index will be transmitted back via Bluetooth.

Program:

#include<Software Serial.h>
#include "DHT.h"
#defineDHTPIN2
#define DHTTYPE DHT11DHT
Dht (DHT PIN,DHT TYPE);
Software Serial BT Serial(4,5);
Void setup()
{
String set Name=String("AT+NAME=MyBTBee\r\n"); //Setting name as'MyBTBee'
Serial.begin(9600);
BT Serial.begin(38400);
BT Serial.print("AT\r\n"); //Check Status
delay(500);
While (BTSerial.available())
{
Serial.write (BTSerial.read());
}
BT Serial.print(setName); //Send Command to change the name
delay(500);
while(BT Serial.available())
{
Serial.write(BTSerial.read());
}
INTERNET OF THINGS LAB Department of ECE,KHIT

dht.begin();
}
void loop()
{
char c;
if (Serial.available())
{
c=Serial.read();
if (c=='t')
Read Sensor();
}
}
Void read Sensor()
{
float h = dht.read Humidity();
float t=dht.read Temperature();
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
Float hic=dht.compute Heat Index(t,h,false);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("%\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print("Heatindex:");
Serial.print (hic);

Result:
INTERNET OF THINGS LAB Department of ECE,KHIT

Experiment – 10

To Interface Bluetooth with Arduino and turn LED ON/OFF


Aim: Write a program to interface Bluetooth with Arduino and turn LED ON/OFF when ‘1’/’0’ is
received from smart phone using Bluetooth.
Apparatus:
Arduino Board
Arduino IDE Software
Android Studio
Serial Cable
HC-05 Bluetooth Module
Android Phone has Bluetooth
LED and Resistor
Jumper wires

Theory:

There are three main parts to this project. An Android smart phone, a Bluetooth transceiver, and an
Arduino. HC 05/06 works on serial communication. The Android app is designed to send serial data to the
Arduino Bluetooth module when a button is pressed on the app.

The Arduino Bluetooth module at the other end receives the data and sends it to the Arduino
through the TX pin of the Bluetooth module (connected to RX pin of Arduino). The code uploaded to the
Arduino checks the received data and compares it. If the received data is 1, the LED turns ON. The LED
turns OFF when the received data is 0. You can open the serial monitor and watch the received data while
connecting.
INTERNET OF THINGS LAB Department of ECE,KHIT

Program:
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); //Setsdigital pin13asoutput 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
digital Write(13, HIGH); //If value is 1 then LED turns ON
else
if(data == '0') //Checks whether value of data is equal to 0
digital Write(13, LOW); //If value is 0 then LED turns OFF
}
}

Procedure:
Installing the Android Application

 Download the application from Amazon AppStore or Github.


 Pair your device with the HC-05/06 Bluetooth module:
• Turn ON the HC-05/06 Bluetooth module by powering theArduino.
• 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.
INTERNET OF THINGS LAB Department of ECE,KHIT

3. Press "paired devices".


 Select your Bluetooth module from the list (HC-05/06)
 After connecting successfully, press the ON button to turn the LED on
 The OFF button to turn the LED off.
 Disconnect the button to disconnect the Bluetooth module.
 Connect an LED positive to pin 13 of the Arduino through a resistance .
 Connect its negative to GND.

RESULT:
INTERNET OF THINGS LAB Department of ECE,KHIT

Experiment – 11
To upload temperature and humidity data to thingspeak cloud

Aim: Write a program on Arduino to upload temperature and humidity data to thingspeak cloud
Apparatus:
Arduino Uno
ESP8266 WIFI Module
DHT-11Sensor
Bread board
Jumper wire

Circuit Diagram:

Procedure:

Step1: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.
INTERNET OF THINGS LAB Department of ECE,KHIT

Step2: 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
 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
 Enter the name and description of your data.
 After this click on save channel button to save your details.

Step3: API Key

 To send data to Thingspeak, we need a unique APIkey,


 which we will use later in our code to upload our sensor data to Thingspeak Website.
 Clickon―APIKeys ‖button
 To get your unique API key for uploading your sensor data.

Program:

#include<stdlib.h>
#include <DHT.h>
#define DHTPIN 5 //DHT data pin connected to Arduino pin5
#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.comip
String msg="GET/update? key=YourAPIKey"; //changeitwithyourkey...
float temp;
int hum;
String tempC;
int error;
void setup()
{
Serial.begin(115200); //use default 115200.
Serial.println("AT");
delay(5000);
if(Serial.find("OK"))
{
Connect WiFi ();
INTERNET OF THINGS LAB Department of ECE,KHIT
}
}

voidloop(){
start:
error=0;
temp=dht.read Temperature();
hum = dht.read Humidity();
char buffer[10];
temp C=dtostrf(temp,4,1,buffer);
update Temp();
if(error==1)
{
Go to start;
}
delay(5000);
}
Void update Temp()
{
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(">"))
{
Serial.print(cmd);
}
Else
{
Serial.println ("AT+CIPCLOSE"); //Resend...
error=1;
}
}
INTERNET OF THINGS LAB Department of ECE,KHIT

Boolean connect WiFi()


{
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;
}
}

Output:

Result:
INTERNET OF THINGS LAB Department of ECE,KHIT

Experiment – 12

To Retrieve temperature and humidity data from thingspeak cloud

Aim: Write a program on Arduino to retrieve temperature and humidity data from thingspeak cloud.
Apparatus:

Arduino Uno
ESP8266WiFiModule
DHT11Sensor
Breadboard
Jumper Wires

 Circuit Diagram:


Procedure:

 Follow steps mentioned in experiment 10 to create account and upload data on thingspeak
cloud.
INTERNET OF THINGS LAB Department of ECE,KHIT

Program:
#include "ThingSpeak.h"
#include<ESP8266WiFi.h>
Const char ssid[]="xxxxxxxxx"; //your network SSID(name)
const char pass[] = "xxxxxxxx"; // your network password WiFi Clien client;
unsigned long counter Channel Number=12345; //Channel ID
const char*my Counter Read API Key="xxxxxxxxxxxxxxxx"; //Read API Key
const int FieldNumber1 = 1; // The field you wish to read
const int Field Number2=2; //The field you wish to read
void setup()
{
Serial.begin(115200);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}
void loop()
{
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.");
}
Long temp=ThingSpeak.read Long Field(counter Channel Number, Field Number1, myCounter
Read APIKey);

Status Code=ThingSpeak.get Last Read Status();

if (status Code == 200)


{
Serial.print("Temperature: "); Serial.println(temp);
}
else
{
Serial.println("Unable to read channel/No internet connection");
}
delay(100);
}
// End of Channel 1 //
INTERNET OF THINGS LAB Department of ECE,KHIT

// Channel 2 //

Long humidity = ThingSpeak.read Long Field (counter Channel Number, FieldNumber2,


myCounte rRead APIKey);
Status Code=ThingSpeak.get Last Read Status();
if (status Code == 200)
{

Serial.print("Humidity:");
Serial.println(humidity);
}
else
{
Serial.println("Unable to read channel/No internet connection");
}
delay(100);
}

// End of Channel 2 //

RESULT:
INTERNET OF THINGS LAB Department of ECE,KHIT

Experiment – 12
To Install MySQL database on Raspberry Pi

Aim: Write a program to install MySQL database on Raspberry Pi and perform basic SQL queries.

Apparatus:

Raspberry Pi
Ethernet cord or WiFi dongle
Micro SD card
Power Supply
Jumper Wires

Procedure and commands:

A. Installing MySQL to RaspberryPi:

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.


Terminals

 Sudoapt update
 Sudoapt upgrade

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

• Sudoapt install mariadb-server

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.

• sudomysql_secure_installation

a. Just follow the prompts to set a password for the root user and to secure your MySQL
installation.
INTERNET OF THINGS LAB Department of ECE,KHIT

 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 Word
Pressor PHP My Admin.

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.

• sudomysql-uroot-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

7. . Through this interface, you can also create or delete users and assign them the rights to manage
any database.
8. 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 ou tof the MYSQL command line is to press CTRL+D.

9. At this point, you will now have successfully setup MySQL on your Raspberry Pi.

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 login to the MySQL command line.

 You will be prompted to enter the password for the ―root‖account that you set up earlier.

Terminals

• sudomysql-uroot-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 example db;


INTERNET OF THINGS LAB Department of ECE,KHIT

3. Next, we will create a MySQL user that we will assign to our new database.
4. We can create this user by running the following command.
 For this example, we will be calling the user
Example user ‖and giving it the password―pi my life up―.
When creating your own, make sure you replace both of these.

• CREATE USER'example user'@'local host'IDENTIFIEDBY'pi my life up';

5. With the user created, we can now go ahead and grant all privileges to the user so that it can
interact with the database.
6. This command will grant all permissions to our
―example user‖for all tables with in our―example db‖database.

• GRANT ALL PRIVILEGE SON example db.*TO'example user'@'local host';

7. 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.

8.We can do this by running the following command.


• FLUSH PRIVILEGES;
9.Cop y Database To/From A Remote Server

Insecure Method:
If you have direct access to the remote server and aren't worried about security
• Mysql dumb-h[server]-u[user]-p[password][database name]|mysql-h[server]-u[user]-
p[password][database name]

Secure Method:
If you can SSH into the remote server you can use this
• Mysqldump-h[server]-
u[user]p[password][databasename]ssh[ssh_username]@remote_domain.commysql-
u[user]-p[password][databasename]

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

RESULT:

You might also like