Iot Lab Workbook 2023-24
Iot Lab Workbook 2023-24
(UGC AUTONOMOUS)
Cheeryal (V), Keesara (M), Medchal District – 501 301 (T.S)
Internet of Things
LABORATORY WORK BOOK
B.Tech III Year II Semester (CSE)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
(2023-2024)
Geethanjali College of Engineering and Technology
UGC AUTONOMOUS
Cheeryal (V), Keesara (M), Medchal District – 501 301 (T S)
Internet of Things
Laboratory Work Book
Name:
RollNo:
Class: Branch:
CERTIFICATE
This is to certify that Mr./Miss
has satisfactorily completed number of experiments in the Internet of
Things Laboratory.
RollNo: Branch:
Year: Academic Year:
Course Faculty
Coordinator In charge
Course Objectives
Develop ability to
1. Assess the vision and introduction of IoT and understanding how M2M is connected to
internet of things
2. Identify the appropriate Hardware and software components of IoT for communication
3. Gain knowledge on Cloud Storage models, web servers and how to integrate device, data
and cloud management framework for IoT.
4. Learn the concepts of various data analytics and operational technology security with IoT.
5. Understand advanced and emerging concepts fog computing and Edge computing-IoT
Course Outcomes
1
9. Select at least 1 input sensor (not PIR) and 1 output device and make the RPi control the
chosen output device in response to activity by the input device (e.g., a temperature sensor as
input and two or more LEDs indicating the current temperature in binary code).
10. Write a python program for client-server based intruder detection system using mqtt
application layer protocol
11. Write an Arduino sketch to blink an LED Light for a particular interval of time using
wireless communication protocol (LoRa)
Case study:
1. Assume that you are in a college, design and implement a IoT prototype to measure the
amount of usage of water at a given location (take the location from user) on a day to day basis
and send the information to Cloud.
2. Receive the above information from the sensors/ cloud and apply necessary algorithms to
predict the amount of water being wasted at a particular location and also send a notification to
the user
2
S.No Index Page No
1 Vision, Mission, Program Educational Objectives (PEO) 5
2 Program Outcomes, Mapping of Lab course with PEO’s and PO’s 6
3 Performance Indicator 11
LIST OF EXPERIMENTS
4 Week -1:
Getting Started with IoT (Arduino). 13
5 Week-2:
Write an Arduino sketch to blink an LED Light for a particular
interval of time. 30
6 Week-3: 32
Write an Arduino sketch to measure the distance(in cms) of a certain
object.
7 Week-4: 37
Write an Arduino sketch to
i. Blink an LED and a buzzer if the distance measured is less
than a threshold value
ii. Illustrate the working of PIR Sensor with an example.
iii. Illustrate the IR and DHT Sensor
8 Week-5: 48
Write an Program to send the humidity and temperature data to
Cloud (ThingSpeak)
9 Week-6: 56
Write a program to alert the user through SMS and Email
notification if humidity is greater than a threshold value
using IFTTT and Thingspeak cloud.
10 Week-7: 67
Write a Python program that blinks an LED at a rate of 3
second ON, 1 second OFF
3
11 Week- 8: 69
Connect a PIR sensor to the GPIO pins of the Raspberry Pi.
Perform measurements todetermine the range of the sensor, i.e.,
start with a small distance (e.g., a few inches) and see if the motion
sensor responds. Repeat these for increasing distances until the
sensor stopsresponding. Report the measured distance.
12 Week-9: 71
Select at least 1 input sensor (not PIR) and 1 output device and make the
RPi control the chosen output device in response to activity by the
input device (e.g., a temperature sensor as input and two or more LEDs
indicating the current temperature in binary code).
13 Week-10: 74
Write a python program for client-server based intruder
detection system using mqtt application layer protocol.
14 Week-11: 76
Write an Arduino sketch to blink an LED Light for a particular
interval of time using wireless communication protocol (LoRa)
4
VISION OF THE DEPARTMENT – CSE
5
PEO’s, PO’s & PSO’s
PO 2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO 5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
PO 6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
6
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO 8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO 11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO 12: Life-long learning: Recognize the need for and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change..
7
Mapping of Lab Course with Programme Educational Objectives
Mapping of Course Outcomes with Program Outcomes & Program Specific Outcomes- CSE:
Prerequisites:
20CS11L01- Programming for Problem Solving Lab
20CS31L02 - Computer Networks Lab
8
INSTRUCTIONS TO THE STUDENTS:
1. Observation book and lab records submitted for the lab work are to be
checked andsigned before the next lab session.
2. Students should be instructed to switch ON the power supply
after theconnections are checked by the lab assistant / teacher.
3. The promptness of submission should be strictly insisted by awarding the
marks accordingly.
4. Ask viva questions at the end of the experiment.
5. Do not allow students who come late to the lab class.
6. Encourage the students to do the experiments innovatively.
7. Fill continuous Evaluation sheet, on regular basis.
8. Ensure that the students are dressed in formals.
9
Scheme of Lab Exam Evaluation:
10
PERFORMANCE INDICATOR
10
11
13
14
15
16
17
18
19
11
20
21
22
23
24
25
26
27
28
29
30
ADDITIONAL EXPERIMENTS
12
WEEK1
Arduino Installation Date:
Aim: Getting Started with IoT (Arduino) and perform necessary software installation
Arduino:
Arduino is a platform that makes it easy for you to build projects using electronics.
IoT is a way of using electronics - to make electronic modules talk to each other remotely and
wirelessly (often using a Cloud) to solve problems.
Now, Arduino can also help you easily build IoT projects in two ways: Using traditional Arduino
boards and attaching communication breakout modules (like nRF, Bluetooth,WiFi,LoRA,GSM, etc)
to them.
Arduino is a micro controller that can be connected to one or more sensors and help you capture the
data or information and then pass it on to processor. If you know the full stack of IoT then you should
also look at Raspberry.
RaspPi is a microprocessor so the basic difference between Arduino and RasPi is that RaspPi is
controller plus processor and Arduino is just a micro controller.
They suit the need for different use cases. You can easily read online about this both.
13
INSTALLING THE ARDUINO IDE ONWindows PCs
1. Visit http://www.arduino.cc/en/main/software to download the latest Arduino IDE version for your
computer’s operating system. There are versions for Windows, Mac, and Linux systems. At the download
page, click on the “Windows Installer” option for the easiest installation.
2. Save the .exe file to your hard drive.
3. Open the .exe file.
4. Click the button to agree to the licensing agreement:
14
6. Select which folder to install the program to, then click “Install”:
7. Wait for the program to finish installing, and then click “Close”:
8. Now find the Arduino shortcut on your Desktop and click on it. The IDE will open up and you’ll seethe
code editor:
15
CONFIGURING THE ARDUINO IDE
The next thing to do is to make sure the software is set up for your particular Arduino board. Go to the
“Tools” drop-down menu, and find “Board”. Another menu will appear where you can select from a list of
Arduino models. I have the Arduino Uno R3, so I chose “Arduino Uno”.
Selecting arduino board
16
Selecting arduino port
17
Running the Arduino IDE Software
This is a display of the Arduino IDE Software. The application is ready to be used to create amazing projects.
Get the latest version from the download page. You can choose between the 32, 64 and ARM versions. It is
very important that you choose the right version for your Linux distro. Clicking on the chosen version brings
you to the donation page and then you can either open or save the file. Please save it on your computer.
18
Extract the package
The file is compressed and you have to extract it in a suitable folder, remembering that it will be executed
from there.
Open the arduino-1.6.x folder just created by the extraction process and spot the install.sh file. Right click
on it and choose Run in Terminal from the contextual menu. The installation process will quickly end and
you should find a new icon on your desktop.
If you don't find the option to run the script from the contextual menu, you have to open a Terminal window
and move into the arduino-1.6.x folder. Type the command ./install.sh and wait for the process to finish.
You should find a new icon on your desktop.
19
Proceed with board-specific instructions
When the Arduino Software (IDE) is properly installed you can go back to the Getting Started Home and
choose your board from the list on the right of the page.
Please Read...
It might happen that when you upload a sketch - after you have selected your board and the serial port -, you
get an error Error opening serial port ... If you get this error, you need to set serial port permission.
ls -l /dev/ttyACM*
The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we
need is "dialout" (is the group owner of the file).
sudousermod -a -G dialout<username>
20
where <username> is your Linux user name. You will need to log out and log in again for this change to
take effect.
This is the procedure to access the serial port from the Arduino Software (IDE) if you get an error
After this procedure, you should be able to proceed normally and upload the sketch to your board or use the
Serial Monitor.
Step 1 − First you must have your Arduino board (you can choose your favorite board) and a USB cable. In
case you use Arduino UNO, Arduino Duemilanove, Nano, Arduino Mega 2560, or Diecimila, you will need
a standard USB cable (A plug to B plug), the kind you would connect to a USB printer as shown in the
following image.
In case you use Arduino Nano, you will need an A to Mini-B cable instead as shown in the following image.
21
You can get different versions of Arduino IDE from the Download page on the Arduino Official website.
You must select your software, which is compatible with your operating system (Windows, IOS, or Linux).
After your file download is complete, unzip the file.
22
Step 5 − Open your first project.
Once the software starts, you have two options −
23
To open an existing project example, select File → Example → Basics → Blink.
Here, we are selecting just one of the examples with the name Blink. It turns the LED on and off with some
time delay. You can select any other example from the list.
Step 6 − Select your Arduino board.
To avoid any error while uploading your program to the board, you must select the correct Arduino board
name, which matches with the board connected to your computer.
Go to Tools → Board and select your board.
24
Here, we have selected Arduino Uno board according to our tutorial, but you must select the name matching
the board that you are using.
Step 7 − Select your serial port.
Select the serial device of the Arduino board. Go to Tools → Serial Port menu. This is likely to be COM3 or
higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect
your Arduino board and re-open the menu, the entry that disappears should be of the Arduino board.
Reconnect the board and select that serial port.
25
Step 8 − Upload the program to your board.
Before explaining how we can upload our program to the board, we must demonstrate the function of each
symbol appearing in the Arduino IDE toolbar.
26
1.Power USB
Arduino board can be powered by using the USB cable from your computer. All you need to do is connect
the USB cable to the USB connection (1).
3. Voltage Regulator
The function of the voltage regulator is to control the voltage given to the Arduino board and stabilize the DC
voltages used by the processor and other elements.
4. Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. How does Arduino calculate time? The
answer is, by using the crystal oscillator. The number printed on top of the Arduino crystal is 16.000H9H. It
tells us that the frequency is 16,000,000 Hertz or 16 MHz.
11.Main microcontroller
Each Arduino board has its own microcontroller (11). You can assume it as the brain of your board. The
main IC (integrated circuit) on the Arduino is slightly different from board to board. The microcontrollersare
usually of the ATMEL Company. You must know what IC your board has before loading up a new program
from the Arduino IDE. This information is available on the top of the IC. For more details about the IC
construction and functions, you can refer to the data sheet.
12. ICSP pin
Mostly, ICSP (12) is an AVR, a tiny programming header for the Arduino consisting of MOSI, MISO, SCK,
RESET, VCC, and GND. It is often referred to as an SPI (Serial Peripheral Interface), which could be
considered as an "expansion" of the output. Actually, you are slaving the output device to the master of the
SPI bus.
27
13. Power LED indicator
This LED should light up when you plug your Arduino into a power source to indicate that your board is
powered up correctly. If this light does not turn on, then there is something wrong with the connection.
16. AREF
AREF stands for Analog Reference. It is sometimes, used to set an external reference voltage (between 0
and 5 Volts) as the upper limit for the analog input pins.
Sketch − The first new terminology is the Arduino program called “sketch”.
Structure
Arduino programs can be divided in three main parts: Structure, Values (variables and constants),
and Functions. In this tutorial, we will learn about the Arduino software program, step by step, and how we
can write the program without any syntax or compilation error.
Let us start with the Structure. Software structure consists of two main functions −
Setup( ) function
Loop( ) function
Void setup ( ) {
}
PURPOSE − The setup() function is called when a sketch starts. Use it to initialize the variables, pin
modes, start using libraries, etc. The setup function will only run once, after each power up or reset
of the Arduino board.
INPUT − -
OUTPUT − -
RETURN − -
Void Loop ( ) {
}
28
PURPOSE − After creating a setup() function, which initializes and sets the initial values,
the loop() function does precisely what its name suggests, and loops consecutively, allowing your
program to change and respond. Use it to actively control the Arduino board.
INPUT − -
OUTPUT − -
RETURN − -
Viva Questions:
1. What is the name of program written with the Arduino IDE?
4. How many digital pins are there in the Arduino Uno board?
29
WEEK-2 Date:
AIM: To interface LED/Buzzer with Arduino/Raspberry Pi and write a program to turn ON LED for 1 sec
after every 2 seconds.
Hardware Requirements:
1. 1x Breadboard
2. 1x Arduino Uno R3
3. 1x RGB LED
x Jumper Wires
Procedure:
1. Connect the Arduino board to your computer using the USB cable.
2. Set the pin-mode as LED output
3. Set the pin-mode as Buzzer output.
4. Set the delay time for output
5. Set the digital pin-mode on.
6. Set the digital pin-mode off.
Source Code:
int led=13;
int buzzer=11;
void setup() {
pinMode(13, OUTPUT);
pinMode(11, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(13, LOW);
digitalWrite(11, LOW);
delay(2000);
}
30
OUTPUT:
Viva Questions
4. How many times does the setup() function run on every startup of the Arduino System?
5. How many times does the loop() function run on every startup of the Arduino System?
31
WEEK-3: Date:
AIM: Write an Arduino sketch to measure the distance (in cm’s) of a certainobject.
Ultrasonic Sensor:
The HC-SR04 ultrasonic sensor uses SONAR to determine the distance of an object just like the bats do. It
offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use
package from 2 cm to 400 cm or 1” to 13 feet.
The operation is not affected by sunlight or black material, although acoustically, soft materials like cloth
can be difficult to detect. It comes complete with ultrasonic transmitter and receiver module.
Ultrasonic Sensor
Hardware Requirements:
32
Procedure:
Follow the circuit diagram and make the connections as shown in the image given below.
The Ultrasonic sensor has four terminals - +5V, Trigger, Echo, and GND connected as follows −
33
Source code:
void setup() {
void loop() {
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
pinMode(echoPin, INPUT);
inches =microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100); }
34
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;
return microseconds / 29 / 2;
1. Upload code.
2. Open serial monitor under tools menu.
3. Output will be shown.
OUTPUT:
To see output:
35
Viva Questions:
4. What mode should we put the Arduino pin to , in order for object detection to work withthe
Ultrasonic Sensor?
36
WEEK-4: Date:
i. AIM :Write an Arduino sketch to blink an LED and a buzzer if the distance measured is less than
a threshold value.
Hardware Requirements:
1. 1x Breadboard
2. 1x Arduino Uno R3
3. 1x Buzzer
4. 6x Jumper Wires
5. 1 x ULTRASONIC Sensor (HC-SR04)
Pin diagram:
Procedure:
37
Source Code:
const int TRIG_PIN = 6; // Arduino pin connected to Ultrasonic Sensor's TRIG pin
const int ECHO_PIN = 7; // Arduino pin connected to Ultrasonic Sensor's ECHO pin
const int BUZZER_PIN = 3; // Arduino pin connected to Piezo Buzzer's pin
const int DISTANCE_THRESHOLD = 50; // centimeters
const int LED_PIN = 13;
void setup() {
Serial.begin (9600); // initialize serial port
pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode
pinMode(ECHO_PIN, INPUT); // set arduino pin to input mode
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
// set arduino pin to output mode
}
void loop() {
// generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
if(distance_cm< DISTANCE_THRESHOLD){
digitalWrite(BUZZER_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
// turn on Piezo Buzzer
}
else{
digitalWrite(BUZZER_PIN, LOW); // turn off Piezo Buzzer
digitalWrite(LED_PIN, LOW);
}
// print the value to Serial Monitor
Serial.print("distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
delay(500);
}
38
OUTPUT:
To see output:
ii. AIM :Write an Arduino sketch to Illustrate the working of PIR Sensor with an example.
Hardware Requirements:
1. 1x Arduino Uno R3
2. 3x Jumper Wires
3. 1 x PIR Sensor
PIR Sensor:
39
Pin Diagram:
Procedure:
Source Code:
#definepirPin 2
int calibrationTime = 30;
long unsigned int lowIn;
long unsigned int pause = 5000;
booleanlockLow = true;
booleantakeLowTime;
int PIRValue = 0;
void setup() {
Serial.begin(9600);
pinMode(pirPin, INPUT);
}
void loop() {
PIRSensor();
}
40
void PIRSensor() {
if(digitalRead(pirPin) == HIGH) {
if(lockLow) {
PIRValue = 1;
lockLow = false;
Serial.println("Motion detected.");
delay(1);
}
takeLowTime = true;
}
if(digitalRead(pirPin) == LOW) {
if(takeLowTime){
lowIn = millis();takeLowTime = false;
}
if(!lockLow&&millis() - lowIn> pause) {
PIRValue = 0;
lockLow = true;
Serial.println("Motion ended.");
delay(1);
}
}
}
OUTPUT:
To see output:
41
iii. AIM : Write an Arduino sketch to Illustrate the IR and DHT Sensor
IR Sensor:
Hardware Requirements:
1. 1x Arduino Uno R3
2. 3x Jumper Wires
3. 1 x IR Sensor
4. 1 x LED
Procedure:
Pin diagram
42
Source Code:
void setup() {
pinMode(7,INPUT);
Serial.begin(9600);
pinMode(13,OUTPUT);
}
void loop() {
Serial.print("IRSensorip ");
Serial.println(digitalRead(7));
if(digitalRead(7)==0)
{
digitalWrite(13,HIGH);
}
else{
digitalWrite(13,LOW);
}
OUTPUT:
DHT Sensor
Hardware Requirements:
1. 1x Arduino Uno R3
2. 3x Jumper Wires
3. 1 x DHT Sensor
43
Procedure:
1. Arduino GND to DHT sensor GND.
2. Vcc of IR to +5V of Arduino.
3. DATA of IR to pin 2 of Arduino.
Installing Libraries:
1. Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries.
2. The Library Manager should open.
3. Search for “DHT” on the Search box and install the DHT library from Adafruit
4. After installing the DHT library from Adafruit, type “Adafruit Unified Sensor” in the search box.
Scroll all the way down to find the library and install it.
44
Pin Diagram:
Procedure:
45
Source Code:
#include "DHT.h"
#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}
void loop() {
// Wait a few seconds betweenmeasurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();
// Read temperature as Fahrenheit
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index
// Must send in temp in Fahrenheit!
float hi = dht.computeHeatIndex(f, h);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hi);
Serial.println(" *F");
}
46
OUTPUT:
To see output:
Viva Questions:
47
WEEK-5 Date:
AIM: Write an Program to send the humidity and temperature data to Cloud (ThingSpeak).
Hardware Requirements:
Procedure:
Step1: Go to https://thingspeak.com/ and create account using official college mail I’d.
48
Step2: Create a new channel and add two fields namely “Temperature” and “Humidity”.
49
Step4: Make a note of Channel number and API Key.
Step2:Open file->Preferences.
Step3:In the Additional Board Managers URL field enter the below link
http://arduino.esp8266.com/stable/package_esp8266com_index.json
50
Click Ok .
Step4:
Search the word ESP8266 in Boards>boards manager from Tools menu. Then install ESP8266 boards.
After complete installation, you will see the INSTALLED label on ESP8266 boards.
51
Step5: Go to tools and Select the board and we can see ESP8266 and select NodeMCU 0.9 from the list.
Write the code in Arduino IDE and Verify and upload the code.
The output graphs can be seen in the channel created on ThingSpeak Cloud.
Pin Diagram:
52
Source Code:
String apiKey = "AZLPGOM7VG3H0BFE"; // Enter your Write API key from ThingSpeak
const char *ssid= "wifi network name "; // replace with your wifissid and wpa2 key
const char *pass = "password of wifi network";
const char* server = "api.thingspeak.com";
WiFiClient client;
void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
void loop()
{
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
53
if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com
{
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop();
Serial.println("Waiting...");
// thingspeak needs minimum 15 sec delay between updates, i've set it to 30 seconds
delay(10000);
}
54
OUTPUT:
Viva Questions:
55
Week-6: Date:
Aim: Write a program to alert the user through SMS and Email notification if humidity is
greater than a threshold value using IFTTT and Thingspeak cloud.
Hardware Requirements:
1. 3 x jumping wires(female to female)
2. 1 xNodeMCU
3. 1 x DHT11 Sensor
Steps:
1. Cresting account on IFTTT and setting up applet
Step1: Open ifttt.com
Step2: Click on create
56
Step 5: Choose Receive Web Request
57
Step 8: Choose add of “Then That”
Step 9: Search for email and choose Email and select send me Email
58
58
Step 11: Click Continue
59
Step 15: Replace event with the name of event given for the applet
2. Thingspeak
Step 1: Open Thingspeak and create a channel for temperature and humidity readings
60
Step 3: Select New ThingHTTP
61
Step 5: Click on Save ThingHTTP
62
Step 8: Fill the details mentioned below
63
Pin Diagram:
Code:
#include <DHT.h> // Including library for
dht #include <ESP8266WiFi.h>
String apiKey = "GEHPJR80CJV2HXJ1"; // Enter your Write API key from
ThingSpeak const char *ssid = " ";// replace with your wifi ssid and wpa2 key
const char *pass = " ";
const char* server = "api.thingspeak.com";
#define DHTPIN 0 //pin where the dht11 is connected
DHT dht(DHTPIN, DHT11);
WiFiClient client;
void setup()
{
Serial.begin(9600);
delay(10);
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
64
void loop()
{
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com
{
String postStr = apiKey;
postStr +="&field1=";
postStr += String(t);
postStr +="&field2=";
postStr += String(h);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop(); Serial.println("Waiting...");
// thingspeak needs minimum 15 sec delay between updates, i've set it to 30 seconds
delay(10000);
}
65
Output:
An Email is triggered when the humidity exceeds threshold value
Viva Questions:
1. Abbrevate IFTTT?
66
Week-7 Date:
Aim: Write a Python program that blinks an LED at a rate of 3 second ON, 1 second OFF
Hardware Requirements:
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW)
while True:
GPIO.output(8,GPIO.HIGH)
sleep(3)
GPIO.output(8,GPIO.LOW)
sleep(1)
67
Output:
The Led will blink at the rate of 3 seconds ON and 1 second OFF.
Viva Questions:
68
Week 8: Date:
Aim: Connect a PIR sensor to the GPIO pins of the Raspberry Pi. Perform measurements to determine
the range of the sensor, i.e., start with a small distance (e.g., a few inches) and see if the motion sensor
responds. Repeat these for increasing distances until the sensor stops responding. Report the measured
distance.
Hardware Requirements:
69
Code:
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOAR
D) GPIO.setup(11,GPIO.IN)
GPIO.setup(3,GPIO.OUT)
GPIO.output(3,GPIO.LOW)
while True:
if(GPIO.input(11)):
GPIO.output(3,GPIO.HIGH)
print("Intruder Detected!!")
else:
GPIO.output(3,GPIO.LOW)
print("NO Intruder")
Output:
The Led will blink when an intruder is detected
Viva Questions:
70
Week 9: Date:
Aim: Select at least 1 input sensor (not PIR) and 1 output device and make the RPi control thechosen
output device in response to activity by the input device (e.g., a temperature sensor asinput and two or
more LEDs indicating the current temperature in binary code)
Hardware Requirements:
Pin Diagram:
71
Code:
import sys
import Adafruit_DHT
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.OUT)
GPIO.setup(10,GPIO.OUT)
GPIO.setup(12,GPIO.OUT)
GPIO.output(8,GPIO.LOW)
GPIO.output(10,GPIO.LOW)
GPIO.output(12,GPIO.LOW)
while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
#4 means pin number 7 in raspberry pi
print('Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature, humidity))
temp_int = int(temperature)
if temp_int<20:
GPIO.output(8,GPIO.HIGH)
GPIO.output(10,GPIO.LOW)
GPIO.output(12,GPIO.LOW)
Output:
72
Viva Questions:
73
Week-10 Date:
Aim: Write a python program for client-server based intruder detection system using mqtt
application layer protocol.
Hardware Requirements:
Client.py
# Import socket module
import socket
import RPi.GPIO as GPIO
from time import sleep
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.OUT)
GPIO.output(8,GPIO.LOW)
74
GPIO.output(8,GPIO.HIGH)
sleep(10)
else:
GPIO.output(8,GPIO.LOW)
print('intruder not detected')
# close the connection
s.close()
Server.py
import socket
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.IN)
# next create a socket object
s = socket.socket()
print ("Socket successfully created")
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 8787
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
s.bind(('', port))
print ("socket binded to %s" %(port))
# put the socket into listening mode
s.listen(5)
print ("socket is listening")
# a forever loop until we interrupt it or
# an error occurs
74
while True:
# Establish connection with client.
c, addr = s.accept()
print ('Got connection from', addr )
# send a thank you message to the client. encoding to send byte type.
c.send('Thank you for connecting'.encode())
while True:
if GPIO.input(7):
c.send("1".encode())
print("INtruder DEtected")
else:
c.send("0".encode())
print("No INtruder")
Output:
If the intruder is detected on server side then led will blink on the client side.
Viva Questions:
1. What is the abbreviation of MQTT Protocol?
75
Week-11 Date:
Aim: Write an Arduino sketch to blink an LED Light for a particular interval of time using wireless
communication protocol (LoRa)
Hardware Requirements:
1. 2 x Arduino Uno boards
2. 2 x LoRa Modules
3. Connecting wires
4. 1 x push button
5. 1 x LED
Pin Diagram:
Transmitter:
Receiver:
76
Transmitter Code:
#include <SPI.h>
#include <LoRa.h>
int pot = A0;
void setup() {
Serial.begin(9600);
pinMode(pot,INPUT);
while (!Serial);
Serial.println("LoRa Sender");
if (!LoRa.begin(433E6)) { // or 915E6, the MHz speed of yout module
Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {
int val = map(analogRead(pot),0,1024,0,255);
LoRa.beginPacket();
LoRa.print(val);
LoRa.endPacket();
delay(50);
77
Receiver Code:
#include <SPI.h>
#include <LoRa.h>
int LED = 3;
String inString = ""; // string to hold input
int val = 0;
void setup() {
Serial.begin(9600);
pinMode(LED,OUTPUT);
while (!Serial);
Serial.println("LoRa Receiver");
if (!LoRa.begin(433E6)) { // or 915E6
Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {
// try to parse packet
int packetSize = LoRa.parsePacket();
if (packetSize) {
// read packet
while (LoRa.available())
{
int inChar = LoRa.read();
inString += (char)inChar;
val = inString.toInt();
}
inString = "";
LoRa.packetRssi();
}
Serial.println(val);
analogWrite(LED, val);
}
Output:
If the button is pressed on the transmitter side then led will blink on the receiver side.
78
Viva Questions:
1. What is LoRa?
79
Case Study/ Mini Project:
Basics of Arduino:
Basics of Raspberry Pi
Python commands:
Notes: