KEMBAR78
IoT Lab Manual-01 | PDF | Light Emitting Diode | Microcontroller
0% found this document useful (0 votes)
41 views60 pages

IoT Lab Manual-01

The Control Systems Lab Manual for the 4th semester in Electronics and Communication Engineering provides an overview of the Internet of Things (IoT) course, focusing on practical knowledge and skills related to Arduino and Raspberry Pi. The manual outlines objectives, learning outcomes, prerequisites, and a detailed list of experiments involving various sensors and IoT applications. Additionally, it includes evaluation schemes for Continuous Internal Evaluation (CIE) and Semester End Examination (SEE), emphasizing the importance of proper lab conduct and preparation.

Uploaded by

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

IoT Lab Manual-01

The Control Systems Lab Manual for the 4th semester in Electronics and Communication Engineering provides an overview of the Internet of Things (IoT) course, focusing on practical knowledge and skills related to Arduino and Raspberry Pi. The manual outlines objectives, learning outcomes, prerequisites, and a detailed list of experiments involving various sensors and IoT applications. Additionally, it includes evaluation schemes for Continuous Internal Evaluation (CIE) and Semester End Examination (SEE), emphasizing the importance of proper lab conduct and preparation.

Uploaded by

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

Control systems Lab Manual / Semester – 4th

Electronics and Communication Engineering Department,

Overview

Year / 3rdYear /6thSemester Prepared 2024


Semester Year -
2024-25 2025
Laborator Internet of Things Lab Laborato BEC657C
y Title ry Code
BEC403
Total 30 Duration -----
Hours of SEE
------
IA Marks 50 SEE 50
Marks
------
Lab Prof..D.M.Kumbhar Sign - Academi 2024-
Manual cYear 25
Author 2024-25
Checked Dr.S.S.Ittannavar Sign -
By

Objectives
This course will enable students to:
1. Preparation: To prepare fundamental knowledge of Internet of Things.
2. Core Competence: To equip students with basic foundation of Internet of Things by basics
of Arduino, Raspberry pi and interfacing with different sensors.
Description
1.0 Learning Objectives

1. To impart necessary and practical knowledge of components of the Internet of Things


2. To develop skills required to build real-life IoT-based projects.
2.0 Learning Outcomes

At the end of the course the student will be able to:


1. Explain the Internet of Things and its hardware and software components.
2. Interface I/O devices, sensors & communication modules.
3. Remotely monitor data and control devices.
4. Develop real-life IoT-based projects

Prerequisites
1. C programming language.
2. Basic operation such as creating file, delete, copy, rename etc. should be known.
3. Arduino/Raspberry operation should be understood.
P a g e 1 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

4. Knowledge of various sensors.


Base Course

1. C programming.

Resources Required
1. Arduino IDE.

General Instructions
1. Do not handle any equipment without reading the instructions /Instruction manuals.
2. Observe type of sockets of equipment power to avoid mechanical damage.
3. Do not insert connectors forcefully in the Sockets.
4. Strictly observe the instructions given by the Teacher/ Lab Instructor.

5. It is mandatory to come to lab in a formal dress (Shirts, Trousers, ID card, and Shoes for boys).
Strictly no Jeans for both Girls and Boys.

6. It is mandatory to come with observation book and lab record in which previous experiment
should be written in Record and the present lab‘s experiment in Observation book.

7. Observation book of the present lab experiment should be got corrected on the same day .
8. Record should be corrected on the next scheduled lab session.
9. Mobile Phones should be Switched OFF in the lab session.
10. Students have to come to lab in-time. Late comers are not allowed to enter the lab.

11. Prepare for the viva questions. At the end of the experiment, the lab faculty will ask the viva
12. Questions and marks are allotted accordingly.

13. Bring all the required stationery like graph sheets, pencil & eraser, different color pens etc. for
the lab class.

Introduction

Introduction to Arduino UNO

P a g e 2 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

The Arduino UNO is a standard board of Arduino. Here UNO means 'one' in Italian. It was named as
UNO to label the first release of Arduino Software. It was also the first USB board released by
Arduino. It is considered as the powerful board used in various projects. Arduino.cc developed the
Arduino UNO board.
Arduino UNO is based on an ATmega328P microcontroller. It is easy to use compared to other boards,
such as the Arduino Mega board, etc. The board consists of digital and analog Input/output pins (I/O),
shields, and other circuits.
The Arduino UNO includes 6 analog pin inputs, 14 digital pins, a USB connector, a power jack, and an
ICSP (In-Circuit Serial Programming) header. It is programmed based on IDE, which stands for
Integrated Development Environment. It can run on both online and offline platforms.
The IDE is common to all available boards of Arduino.
Let's discuss each component in detail.

 ATmega328 Microcontroller- It is a single chip Microcontroller of the ATmel family. The


processor code inside it is of 8-bit. It combines Memory (SRAM, EEPROM, and Flash),
Analog to Digital Converter, SPI serial ports, I/O lines, registers, timer, external and
internal interrupts, and oscillator.
 ICSP pin - The In-Circuit Serial Programming pin allows the user to program using the
firmware of the Arduino board.

P a g e 3 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

 Power LED Indicator- The ON status of LED shows the power is activated. When the
power is OFF, the LED will not light up.
 Digital I/O pins- The digital pins have the value HIGH or LOW. The pins numbered from
D0 to D13 are digital pins.
 TX and RX LED's- The successful flow of data is represented by the lighting of these
LED's.
 AREF- The Analog Reference (AREF) pin is used to feed a reference voltage to the
Arduino UNO board from the external power supply.
 Reset button- It is used to add a Reset button to the connection.
 USB- It allows the board to connect to the computer. It is essential for the programming of
the Arduino UNO board.
 Crystal Oscillator- The Crystal oscillator has a frequency of 16MHz, which makes the
Arduino UNO a powerful board.
 Voltage Regulator- The voltage regulator converts the input voltage to 5V.
 GND- Ground pins. The ground pin acts as a pin with zero voltage.
 Vin- It is the input voltage.
 Analog Pins- The pins numbered from A0 to A5 are analog pins. The function of Analog
pins is to read the analog sensor used in the connection. It can also act as GPIO (General
Purpose Input Output) pins.

Introduction to Node MCU ESP8266 module


The NodeMCU (Node Micro-Controller Unit) is an open-source software and hardware development
environment built around an inexpensive System-on-a-Chip (SoC) called the ESP8266. The ESP8266,
designed and manufactured by Espress if Systems, contains the crucial elements of a computer: CPU,
RAM, networking (WiFi), and even a modern operating system and SDK. That makes it an excellent
choice for Internet of Things (IoT) projects of all kinds.

NodeMCU ESP8266 Specifications & Features and Pinout


 Microcontroller: Tensilica 32-bit RISC CPU Xtensa LX106
 Operating Voltage: 3.3V
 Input Voltage: 7-12V
 Digital I/O Pins (DIO): 16
 Analog Input Pins (ADC): 1
 UARTs: 1
 SPIs: 1

P a g e 4 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

 I2Cs: 1
 Flash Memory: 4 MB
 SRAM: 64 KB
 Clock Speed: 80 MHz
 USB-TTL based on CP2102 is included onboard, Enabling Plug n Play
 PCB Antenna
 Small Sized module to fit smartly inside your IoT projects

PIN CODE
A0 A0
GPIO 16 D0
GPIO 5 D1
GPIO 4 D2
GPIO 0 D3
GPIO 2 D4
GPIO14 D5
GPIO 12 D6
GPIO 13 D7
GPIO 15 D8
GPIO 9 SD2
GPIO10 SD3
GPIO3 Rx
GPIO1 Tx

P a g e 5 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

Steps to install Node MCU


1. Download and install Arduino IDE
2. Open the IDE and follow this path. File -> preferences -> Additional board manager
URL.
3. Now paste the URL in the dialog box :
http://arduino.esp8266.com/stable/package_esp8266com_index.json
4. Then, click the “OK” button.
5. Now follow this path. Tools -> Board -> Boards Manager
6. Search for ESP8266 and install the “ESP8266 by ESP8266 Community“
7. After this, restart your Arduino IDE.
8. Then, go to Tools > Board and check that you have ESP8266 boards available.
9. First, make sure you have an ESP8266 selected in Tools > Board. If you’re using the
ESP8266-12E NodeMCU Kit as shown in previous pictures, select the NodeMCU 1.0
(ESP-12E Module) option.

CONTENTS
Expt.
Name of experiment
No.
To interface LED/Buzzer with Arduino /Raspberry Pi and write a program to ‘turn ON’
1.a
LED for 1 sec after every 2 seconds.

1.b To interface the Push button/Digital sensor (IR/LDR) with Arduino /Raspberry Pi and
write a program to ‘turn ON’ LED when a push button is pressed or at sensor detection
To interface the DHT11 sensor with Arduino /Raspberry Pi and write a program to
2.a
print temperature and humidity readings.
To interface OLED with Arduino /Raspberry Pi and write a program to print its
2.b temperature
and humidity readings.
3 To interface the motor using a relay with Arduino /Raspberry Pi and write a program to
‘turn ON’ the motor when a push button is pressed.
4.a Write an Arduino/Raspberry Pi program to interface the Soil Moisture Sensor.
4.b Write an Arduino/Raspberry Pi program to interface the LDR/Photo Sensor.
5 Write a program to interface an Ultrasonic Sensor with Arduino /Raspberry Pi.
Write a program on Arduino/Raspberry Pi to upload temperature and humidity
6
data to thingspeak cloud.
7
Write a program on Arduino/Raspbeii y Pi to retrieve temperature and humidity
data from thingspeak cloud.
P a g e 6 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

8 Write a program to interface LED using Telegram App.

9
Write a program on Arduino/Raspbei i y Pi to publish temperature data to the MQTT
broker.
Write a program to create a UDP server on Arduino/Raspberry Pi and respond with
10 humidity
data to the UDP client when requested.
Write a program to create a TCP server on Arduino /Raspberry Pi and respond with
11 humidity
data to the TCP client when requested.
Write a program on Arduino / Raspberry Pi to subscribe to the MQTT broker for
12 temperature
data and print it.

Evaluation Scheme
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is
50%. The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50)
and for the SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A
student shall be deemed to have satisfied the academic requirements and earned the credits allotted
to each subject/ course if the student secures a minimum of 40% (40 marks out of 100) in the sum
total of the CIE (Continuous Internal Evaluation) and SEE (Semester End Examination) taken
together.

Continuous Internal Evaluation (CIE):


CIE marks for the practical course are 50 Marks.
The split-up of CIE marks for record/ journal and test are in the ratio 60:40.
• Each experiment will be evaluated for conduction with an observation sheet and record write-
up. Rubrics for the evaluation of the journal/write-up for hardware/software experiments are
designed by the faculty who is handling the laboratory session and are made known to students
at the beginning of the practical session.
• The record should contain all the specified experiments in the syllabus and each experiment
write-up will be evaluated for 10 marks.
• The total marks scored by the students are scaled down to 30 marks (60% of maximum marks).
• Weightage is to be given for neatness and submission of record/write-up on time.
• The department shall conduct a test of 100 marks after the completion of all the
experiments listed in the syllabus.
• In a test, test write-up, conduction of experiment, acceptable result, and procedural
knowledge will carry a weightage of 60% and the rest 40% for viva-voce.
• The suitable rubrics can be designed to evaluate each student's performance and learning ability.
• The marks scored shall be scaled down to 20 marks (40% of the maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and marks of a test is
P a g e 7 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

the total CIE marks scored by the student.


Semester End Evaluation (SEE):
• SEE marks for the practical course are 50 Marks.
• SEE shall be conducted joinHy by the two examiners of the same institute, examiners
are appointed by the Head of the Institute.
• The examination schedule and names of examiners are informed to the university before the
conduction of the examination. These practical examinations are to be conducted within the
schedule mentioned in the university's academic calendar.
• All laboratory experiments are to be included for practical examination.
• (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer
script to be strictly adhered to by the examiners. OR based on the course requirement
evaluation rubrics shall be decided jointly by examiners.
• Students can pick one question (experiment) from the questions lot prepared by the examiners
jointly.
• Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly by
examiners. General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction
procedure and result in -60%, Viva-voce 20% of maximum marks. SEE for practical shall be
evaluated for 100 marks and scored marks shall be scaled down to 50 marks (however, based on
course type, rubrics shall be decided by the examiners)
Change of experiment is allowed only once and 15% of Marks allotted to the procedure part are to
be made zero.

Reference

Suggested Learning Resources:


 Vijay Madisetti, Arshdeep Bahga, Internet of Things. "A Hands-on Approach",
University Press
 Dr. SRN Reddy, Rachit Thukral, and Manasi Mishra, "Introduction to Internet of
Things: A Practical Approach", ETI Labs
 Pethuru Raj and Anupama C Raman, "The Internet of Things: Enabling Technologies,
Platforms, and Use Cases", CRC Press
 Jeeva Jose, "Internet of Things", Khanna Publishing House, Delhi
 Adrian McEwen, "Designing the Internet of Things", Wiley
 Raj Kamal, "Internet of Things: Architecture and Design", McGraw Hill

P a g e 8 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

P a g e 9 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

Experiments

1.0 Interfacing of LED/Buzzer with Arduino /Raspberry Pi

Experiment Date
Date Planed Marks
No Conducted
01.a

1a.1 Learning Objectives


 Student will able to obtain to interface LED/Buzzer with Arduino /Raspberry Pi and
write a program to ‘turn ON’ LED .
1a.2 Aim
To interface LED/Buzzer with Arduino /Raspberry Pi and write a program to ‘turn ON’
LED for 1 sec after every 2 seconds.

1a. Theory
3
LED, which stands for Light Emitting Diode, is a semiconductor device that emits light when an
electric current passes through it. LEDs are widely used for various applications due to their energy
efficiency, long lifespan, and versatility. Here are some key points about LEDs.
Basic Operation: LEDs work on the principle of electroluminescence. When electrons and holes
(positive counterparts of electrons) recombine within the semiconductor material, they release energy
in the form of photons, which produces light.
P a g e 10 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

Item Mi Max Unit


n
Forward Current 20 30 mA
Forward Voltage 1.8 2.2 V

1a. Diagram
4

1b.5 Program
int led=13;
void setup()
{
pinMode(led,OUTPUT);
}

void loop()
{
digitalWrite(led,HIGH);
delay(1000);
digitalWrite(led,LOW);
delay(2000);
}

1a. Output
P a g e 11 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

6
___________________________________________________________________________
___________________________________________________________________________

1a. Conclusion
7

___________________________________________________________________________
___________________________________________________________________________

Faculty Signature

1.0 Interfacing of Push button/Digital sensor (IR/LDR) with Arduino


/Raspberry Pi

Experiment Date
Date Planed Marks
No Conducted
01.b

1b.1 Learning Objectives


 Student will able to interface the Push button/Digital sensor (IR/LDR) with Arduino
/Raspberry Pi and write a program for the same.
1b.2 Aim
To interface the Push button/Digital sensor (IR/LDR) with Arduino /Raspberry Pi and
write a program to ‘turn ON’ LED when a push button is pressed or at sensor detection.
1b.3 Theory
Digital Pins of Arduino can be configured
as OUTPUT, INPUT or INPUT_PULLUP mode

P a g e 12 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

using pinMode() function. INPUT_PULLUP mode is used to enable the Internal PULL-UP
Resistor. The value of Internal PULL-UP resistor of Arduino Uno is about 20-50KΩ.
Here the switch is connected to digital pin 4 (D4) and LED is connected to digital pin 8 (D8)
of Arduino Uno. Thus pin D4 should be declared as INPUT and pin D8 as OUTPUT in the
sketch (program). 10KΩ resistor is used as PULL-UP resistor and a 680Ω resistor is used to
limit the current through the LED.
1b.4 Diagram

1b.5 Program

int button=4;
int led=8;
void setup()
{
pinMode(button,INPUT_PULLUP);
pinMode(led,OUTPUT);
}

voidloop()
{
intbuttonState=digitalRead(button);
if(buttonState==HIGH)
{
digitalWrite(led,LOW);
}
P a g e 13 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

else
{
digitalWrite(led,HIGH);
}

delay(50);
}

1b.6 Output
___________________________________________________________________________
___________________________________________________________________________

1b.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________

Faculty Signature

2.0 Interfacing of DHT11 sensor with Arduino /Raspberry Pi

Experiment Date
Date Planed Marks
No Conducted
02.a

2a. Learning Objectives


1

 Student will able to interface the DHT11 sensor with Arduino /Raspberry Pi and write a
program to print temperature and humidity readings.

2a. Aim
2

P a g e 14 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

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

2a. Theory of Signal Flow Graph


3
Interfacing the DHT11 Sensor with Arduino is helps to read temperature and humidity from a
DHT11 sensor. It is the first step to understanding how to use a DHT11 sensor in different
projects. At first, we will learn how to connect a DHT11 sensor module with Arduino and
write a simple DHT11 Temperature and Humidity sensor Arduino Code to read the
temperature and humidity from the sensor. Here we will measure room temperature and
humidity and print these values on the serial monitor window of the Arduino IDE.
 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) and
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 TON and TOFF are decoded as logic 1 or logic 0 or start
pulse or end of a frame.
Steps to use DHT11 sensor:
 Here, we will be using a DHT11 library by Mark Ruys from GitHub.
 Download this library from here.
 Extract the library and add the folder to the libraries folder path of Arduino
IDE.
 For information about how to add a custom library to the Arduino IDE and
use examples from it, refer Adding Library To Arduino IDE in the Basics
section.
 Once the library has been added to the Arduino IDE, open the IDE and open
the example sketch named DHT_Test from the library added.

2a. Diagram
4

P a g e 15 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

2a. Program
5

#include<SimpleDHT.h>
intpinDHT11=4;
SimpleDHT11dht11(pinDHT11);
bytetemperature=0;
bytehumidity=0;
voidsetup()
{
Serial.begin(9600);
}
voidloop()
{
interr=SimpleDHTErrSuccess;
if((err=dht11.read(&temperature,&humidity,NULL))!
=
SimpleDHTErrSuccess)
{
delay(500);
//return;
}
Serial.print("Temperature:");
Serial.print((String)temperature);
Serial.print("C,Humidity:");
Serial. Println((String)humidity);
delay(1000);
}
P a g e 16 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

 Temperature = ___________0C
 Humidity = _________
2a. Output
6

2a. Conclusion
7

___________________________________________________________________________
___________________________________________________________________________

Faculty Signature

P a g e 17 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

2.0 Interfacing of OLED with Arduino /Raspberry Pi

Experiment Date
Date Planed Marks
No Conducted
02.a

2b.1 Learning Objectives

 Student will able to interface the OLED with Arduino /Raspberry Pi and write a
program to print temperature and humidity readings.

2b.2 Aim

To interface the OLED with Arduino /Raspberry Pi and write a program to print
temperature and humidity readings.

2b.3 Theory

Most of us would be familiar with the 16×2 Dot matrix LCD display that is used in most of the projects
to display some information to the user. However, these LCD displays have a lot of limitations in what
they can do. In this tutorial, we are going to learn about OLED displays and how to use them with
Arduino. There are many types of OLED displays available in the market and there are lots of ways to
get them working.

There are many variants of this module available in the market, having different resolutions,
communication protocols, or pixel colours.

These OLED modules are driven by SSD1306 IC which is a driver IC for 128x64 Dot Matrix OLED
segments. The SSD1306 has its own controller and supports both SPI and I2C communication
protocols. Hence, there are various OLED modules in the market, some that support only SPI
communication, some that support only I2C communication, and some that support both I2C and SPI
communication. (Different number of pins for different modules)

Since the driver IC supports 128x64 resolution, there are some variants that have a lesser resolution like
128x32.

P a g e 18 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

Different modules support different colors like blue, yellow, and white. Some modules support multiple
colors as well. You will need to check the specifications of your display module to know which colors
are supported.

We are using a 4-pin I2C supported 128x64 OLED module similar to the one shown in the above
image.

For more information about OLED and how to use it, refer the topic SSD1306 OLED Display in the
sensors and modules section.

OLED 128x64 Pinout

OLED 128x64 Pinout


OLED 128x64 Pin Description

The above image shows a 128x64 I2C based OLED module.

VCC: This is the power pin for the module. A supply of 3.3V or 5V can be provided to this pin to
power the display.

GND: This is the ground pin for the module.

SCL and SDA: These are the serial clock and serial data pins for I2C communication.

2b.4 Diagram

P a g e 19 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

The connections are very simple, connect the GND pin to the GND pin of the Arduino and
VCC to the 5V pin. The SCL is connected to the A5 and the SDA is connected to the A4 pin
of the Arduino.
2b.5 Program
#include<SPI.h>
#include<Wire.h>
#include<Adafruit_GFX.h>
#include<Adafruit_SSD1306.h>
#include<SimpleDHT.h>
intpinDHT11=5;
SimpleDHT11dht11(pinDHT11);
#definescreen_width128
#definescreen_height64
#defineOLED_RESET-1
Adafruit_SSD1306display(screen_width,screen_height);
voidsetup()
{
Serial.begin(9600);
Serial. Println("TEMPERATUREANDHUMIDITY");
display.begin(SSD1306_SWITCHCAPVCC,0x3C);
display.clearDisplay();
}
voidloop()
{
bytetemperature=0;
bytehumidity=0;
P a g e 20 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

interr=SimpleDHTErrSuccess;
if((err=dht11.read(&temperature,&humidity,NULL))!=
SimpleDHTErrSuccess)
{
Serial.print("ReadDHT11failed,err="); Serial.println(err);delay(1000);
return;
}
Serial.print((int)temperature);
Serial.print("*C,");
Serial.print((int)humidity);
Serial.println("H");
display.clearDisplay();
display.setTextSize(1); display.setTextColor(SSD1306_WHITE);
display.setCursor(0,0);
display.print(" TEMP.&HUMIDITY");
display.setCursor(0,25);
display.print("TEMPERATURE:");
display.setCursor(90,25);
display.print((int)temperature);
display.setCursor(0,50);
display.print("HUMIDITY :");
display.setCursor(90,50);
display.print((int)humidity);
display.display();
}

2b.6 Output

 Temperature = ___________0C

2b.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________

P a g e 21 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

Faculty Signature

3.0 Interfacing of Motor using Relay with Arduino /Raspberry Pi

Experiment Date
Date Planed Marks
No Conducted
03

3.1 Learning Objectives

 Student will able to interface motor using relay with Arduino /Raspberry Pi.

3.2 Aim
To interface motor using relay with Arduino and write a program to ‘turn ON’ motor when
push button is pressed.

3.3 Theory
To control a DC motor with an Arduino and a relay, you will need to connect the relay to
the Arduino using a digital output pin. The relay acts as a switch that can be controlled by
the Arduino to turn the motor on and off.

1. Connect the motor to the relay‘s normally open (NO) and common (COM) terminals.
2. Connect the relay‘s control terminal to a digital pin on the Arduino.
3. In the Arduino code, use the digitalWrite() function to set the relay‘s control pin to HIGH or
LOW to turn the motor on and off.
It’s also important to note that a relay is an electromechanical device that is controlled by an electric
current, and typically requires more current than an Arduino can provide. To avoid damaging

P a g e 22 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

the Arduino, you will need to use an external power source to provide power to the relay and the
motor.
If you want to control the speed of the motor you can use a PWM pin and the analogWrite() function.
With this method you can change the duty cycle of the pin, and that will change the speed of the motor.

A relay is an electrically operated switch that can be used to control a 5V DC motor. The relay uses a
small amount of electrical current to control a larger current flowing to the motor. It typically consists
of an electromagnet that is used to open or close the switch, allowing the current to flow to the motor.
The 5V DC motor can be connected to the relay through the normally open or normally closed
contacts. The relay can be controlled by a microcontroller or other control circuit, which can be used to
turn the motor on or off, or to control its speed or direction.

3.4 Diagram

P a g e 23 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

3.5 Program
int button=6;
int motor=5;
void setup()
{
pinMode(button,INPUT_PULLUP);
pinMode(motor,OUTPUT);
}
Void loop()
{
int buttonState=digitalRead(button);
if(buttonState==HIGH)
{
digitalWrite(motor,LOW);
}
else
{
digitalWrite(motor,HIGH);
}
delay(50);
}

3.6 Output

3.7 Conclusion

Faculty Signature

P a g e 24 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

4.0 Interfacing of Soil Moisture Sensor with Arduino /Raspberry Pi

Experiment Date
Date Planed Marks
No Conducted
4a

4a. Learning Objectives


1

 Student will able to interface the soil moisture sensor with Arduino /Raspberry Pi and
write a program to print percentage soil moisture readings.

4a. Aim
2
To interface the soil moisture sensor with Arduino /Raspberry Pi and write a program to print
percentage soil moisture readings.

4a.3 Theory
The Soil Moisture Sensor is a simple breakout for measuring the moisture in the soil and similar
materials. The soil moisture sensor is pretty straightforward to use. The two large, exposed pads
function as probes for the sensor, together acting as a variable resistor. The more water that is in the soil
means the better the conductivity between the pads will be and will result in lower resistance, and a
higher SIG out.
To get the Soil Moisture Sensor functioning all you will need is to connect the VCC and GND pins to
your Arduino-based device (or compatible development board) and you will receive a SIG out which
will depend on the amount of water in the soil.

Features: Soil Moisture Sensor


 Simple to use

P a g e 25 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

 Passive component
 Resistive Sensor

Specifications: Soil Moisture Sensor


 Operating voltage: 3.3V~5V

 Dual output mode, analog output more accurate


A fixed bolt hole for easy installation
 With power indicator (red) and digital switching output indicator (green)
 Having LM393 comparator chip, stable
 Panel PCB Dimension: Approx.3cm x 1.5cm
 Soil Probe Dimension: Approx. 6cm x 3cm
 Cable Length: Approx.21cm
 VCC: 3.3V-5V
 GND: GND
 DO: digital output interface (0 and 1)
 AO: analog output interface

Here, the analog output of soil moisture sensor is processed using ADC. The
moisture content in terms of percentage is displayed on the serial monitor. The
output of the soil moisture sensor changes in the range of ADC value from 0 to
1023.This can be represented as moisture value in terms of percentage using
formula given below.
Analog Output = \frac{ADC Value}{1023}
Moisture in percentage = 100 – (Analog output * 100)
P a g e 26 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

For zero moisture, we get maximum value of 10-bit ADC, i.e. 1023. This, in turn,
gives 0% moisture.

4a.4 Diagram

4a.5 Program
const int sensor_pin = A1; /* Soil moisture sensor O/P pin */

void setup() {
Serial.begin(9600); /* Define baud rate for serial communication */
}

void loop() {
float moisture_percentage;
int sensor_analog;
sensor_analog = analogRead(sensor_pin);
moisture_percentage = ( 100 - ( (sensor_analog/1023.00) * 100 ) );
Serial.print("Moisture Percentage = ");
Serial.print(moisture_percentage);
//Serial.print("%\n\n");
delay(1000);
}

4a. Output
6

 Percentage soil moisture = _________

4a. Conclusion
7

P a g e 27 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

___________________________________________________________________________
___________________________________________________________________________

Faculty Signature

4.0 Interfacing of LDR/Photo sensor with Arduino /Raspberry Pi

Experiment Date
Date Planed Marks
No Conducted
4b

4b.1 Learning Objectives

 Student will able to interface LDR/Photo sensor with Arduino /Raspberry Pi and write a
program interface it.

4b.2 Aim
To interface LDR/Photo sensor with Arduino /Raspberry Pi and write a program interface it

4b.3 Theory

Working of the circuit: Basically when there is darkness the led will glow and when there is sufficient
light led will stop glowing. This a simple circuit for of interface Arduino uno with LDR sensor.

First of all, we need to knw what is LDR sensor and how it works?

LDR (light dependent resistor) also called photoresistors are responsive to light. Photoresistors are used
to indicate the intensity or the presence or the absence of light. When there is darkness the resistance of
photoresistor increases and when there is sufficient light it dramatically decreases.
P a g e 28 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

LDR light dependent resistor

LDR (light dependent resistor) which has two terminals. Terminal one is the signal pin which should be
connected according to the code. Another terminal is considered as the ground pin which should be
connected to the ground of the system.

Arduino Uno: The Arduino Uno is a microcontroller board based on the ATmega328. It has 20 digital
input/output pins (of which 6 can be used as PWM outputs and 6 can be used as analog inputs), a 16
MHz resonator, a USB connection, a power jack, an in-circuit system programming (ICSP) header, and
a reset button.

In the simplest terms, a light-emitting diode (LED) is a semiconductor device that emits light when an
electric current is passed through it. Light is produced when the particles that carry the current (known
as electrons and holes) combine together within the semiconductor material. Led has two terminals:
positive and negative.

4b.4 Diagram

4b.5 Program
P a g e 29 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

int led=3;
int ldr=6;
void setup()
{
pinMode (led, OUTPUT);
pinMode(ldr,INPUT_PULLUP);
}

void loop() {
int ldrState=digitalRead(ldr);
if(ldrState==HIGH)
{
digitalWrite (led, HIGH);
}
else
{
digitalWrite (led, LOW);
}
delay(50);
}

4b.6 Output

4b.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________

Faculty Signature

P a g e 30 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

5.0 Interfacing of ultrasonic sensor with Arduino /Raspberry Pi

Experiment Date
Date Planed Marks
No Conducted
5

5.1 Learning Objectives

 Student will able to interface ultrasonic sensor with Arduino /Raspberry Pi and write a
program to print distance measured.
5.2 Aim
To interface ultrasonic sensor with Arduino /Raspberry Pi and write a program to print
distance measured.

5.3 Theory
An Ultrasonic Sensor is a device that measures distance to an object using Sound Waves. It works by
sending out a sound wave at ultrasonic frequency and waits for it to bounce back from the object. Then,
the time delay between transmission of sound and receiving of the sound is used to calculate the
distance.
It is done using the formula Distance = (Speed of sound * Time delay) / 2
We divide the distance formula by 2 because the sound waves travel a round trip i.e from the sensor
and back to the sensor which doubles the actual distance.

P a g e 31 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

The HC-SR04 is a typical ultrasonic sensor which is used in many projects such as obstacle detector
and electronic distance measurement tapes. In this Instructable I'll teach you how to interface the HC-
SC04 with an Arduino Uno.

The HC-SR04 is an ultrasonic ranging module. This economical sensor provides 2cm to 400cm of
non-contact measurement functionality with a ranging accuracy that can reach up to 3mm. Each HC-
SR04 module includes an ultrasonic transmitter, a receiver and a control circuit.
There are Four Pins on the HC-SR04. They are:

 Vcc (5V supply)

 Gnd (Ground)

 Trig (Trigger)

 Echo (Receive)
The key features to be noted are:

 Operating Voltage: 5V DC

 Operating Current: 15mA

 Measure Angle: 15°

 Ranging Distance: 2cm - 4m

A timing diagram of the sensor is shown below. The difference in color of the SIG pin’s waveform
signifies which device is controlling the pin. For example, the Uno controls the pin to send a trigger
pulse (blue) and then the sensor controls the pin to send the HIGH pulse (black).

P a g e 32 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

Ultrasonic Sensor Timing Diagram

Since the received pulse from the sensor is in time, we have to perform some calculations to convert
the time into distance. The speed of sound travels at 1130 feet per second or 340 meters per second.
First, we need to convert the 340m/s into cm/sec by multiplying by 100 which is 34, 000cm/sec.
Then, convert cm/sec into cm/μsec by dividing by 1E6 which is 0.034cm/μsec.

5.4 Diagram

5.5 Program

#include <NewPing.h>
#define TRIGGER_PIN 9 // Arduino pin connected to trigger pin on the ultrasonic sensor.

P a g e 33 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

#define ECHO_PIN 10 // Arduino pin connected to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters).
Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and
maximum distance.
void setup() {
Serial.begin(9600); // Open serial monitor at 9600 baud to see the measured distance.
}
void loop() {
delay(500); // Wait for 50ms.
Serial.print("Distance: ");
Serial.print(sonar.ping_cm()); // Display distance in cm and print result (0 = outside set distance
range).
Serial.println("cm");
}

5.6 Output

 Distance = _________cm

5.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________
Faculty Signature
6.0 Upload temperature and humidity data to thingspeak cloud

Experiment Date
Date Planed Marks
No Conducted
6

6.1 Learning Objectives

 Student will able to interface ESP8266


 Student will able to upload temperature and humidity data to thingspeak cloud.
6.2 Aim
To write a program on Arduino to upload temperature and humidity data to thingspeak cloud.

6.3 Theory
ThingSpeak is an open-source Internet of Things (IoT) application and API that allows users to collect
and store sensor data in the cloud and perform analytics on that data. It allows users to create
“channels” to collect data from multiple sensors, and also has built-in support for visualizing and
P a g e 34 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

analyzing the data. ThingSpeak can be used for a variety of applications, such as monitoring
environmental conditions, tracking the location of assets, and controlling devices remotely. It is
available for free and also has paid subscription plans for additional features and support. The device
that sends the data must be configured with the correct channel information, such as the channel ID and
write API key.
Steps to Connect
Step 1: ThingSpeak Setup for Temperature and Humidity Monitoring
a. For creating your channel on Thingspeak, you first need to Sign up on Thingspeak.
b. In case if you already have an account on Thingspeak, just sign in using your id and password.

c. For creating your account go to www.thinspeak.com.

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


Step 2: Create a Channel for Your Data
a. Once you Sign in after your account verification, create a new channel by clicking “New
Channel” button.
b. After clicking on “New Channel”, enter the Name and Description of the data you want to
upload on this channel.
c. Enter the name of your data ‘Temperature’ in Field1 and ‘Humidity’ in Field2.
d. Click on the save channel button to save your details.

Step 3: API Key


a. 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.
b. Click on “API Keys” button to get your unique API key for uploading your sensor data.
c. Now copy your “Write API Key”. We will use this API key in our code.

Step 4: Installing the ThingSpeak Library


Go to Sketch > Include Library > Manage Libraries… and search for “ThingSpeak” in the Library
Manager. Install the ThingSpeak library by MathWorks.

6.4 Diagram

P a g e 35 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

6.5 Program
Arduino Program
//SendTemperature&HumiditytoESP8266fromArduino.
#include<SimpleDHT.h>
intpinDHT11=5;
SimpleDHT11dht11(pinDHT11);
bytetemperature=0;
bytehumidity=0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Interr=SimpleDHTErrSuccess;
if((err=dht11.read(&temperature,&humidity,NULL))!=
SimpleDHTErrSuccess)
{
delay(500);
//return;
}
Serial.println((String)temperature+","+

P a g e 36 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

(String)humidity);
delay(1500);
}
ESP8266Program
#include<ESP8266WiFi.h>
#include<ThingSpeak.h>
const char*ssid="Dmk"; /*Hotspot name*/
const char*password="abcdef"; /*Hotspot passward*/
WiFiClient client;
unsigned long channelId=2384685;
const char*API_Key="88GOBPCQ26D7XJ7W";/*write API key*/
String recData;
int temperature=0;
int humidity=0;
int nwConnectionLED=2;
void setup()
{
Serial.begin(9600);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
pinMode(nwConnectionLED,OUTPUT);
}
void loop()
{
if(WiFi.status()!=WL_CONNECTED)
{
digitalWrite(nwConnectionLED,HIGH);
while(WiFi.status()!=WL_CONNECTED)
{
WiFi.begin(ssid,password);
delay(5000);
}
}

P a g e 37 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

digitalWrite(nwConnectionLED,LOW);
if(Serial.available())
{
recData=Serial.readString();
temperature=recData.substring(0,
recData.indexOf(",")).toInt();
humidity=recData.substring(recData.indexOf(",")+1,
recData.length()).toInt();
}
ThingSpeak.setField(1,temperature);
ThingSpeak.setField(2,humidity);
int response=ThingSpeak.writeFields(channelId,API_Key);
delay(1000);
}

6.6 Output

 Temperature = _________0C
 Humidity =_________

6.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________
Faculty Signature
7.0 Retrieve temperature and humidity data from thingspeak cloud

Experiment Date
Date Planed Marks
No Conducted
7

7.1 Learning Objectives

 Student will able to interface ESP8266


 Student will able to read temperature and humidity data from thingspeak cloud.
7.2 Aim
To write a program on Arduino to retrieve temperature and humidity data from thingspeak
cloud.
P a g e 38 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

7.3 Theory
To read values from Thingspeak we need to upload some data in real time, to do this, first upload
temperature and humidity data to Thingspeak using previous experiment using NodeMCU 8266.
Installing the ThingSpeak Library
1. To send or receive sensor readings to ThingSpeak, we’ll use the ThingSpeak Arduino library.
Go to Sketch > Include Library > Manage Libraries… and search for “ThingSpeak” in the
Library Manager. Install the ThingSpeak library by MathWorks.
OR
2. Upload the Library from drive Go to Sketch > Include Library > Add ZIP Library.…
> open to install Library

Channel Settings that you need to do read data


Go to your Thingspeak account and do the following setting to receive temperature and humidity data.
1. Go to channel setting put ‘tick’ mark for both filed 1 and filed 2 and scroll down to bottom and
save it.
2. You need your channel ID to read the fields on your channel you wish to read so that copy your
channel id and paste in the code
3. You need your Read API key from your channel and copy Read API key.
4. use this Read API key in our code.
5. Write following program and upload in the Node MCU82666.
6. After successful upload Open the serial monitor; you will be able to see the values read from
your channel.

7.4 Diagram

P a g e 39 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

7.5 Program
/ESP8266 code to recceive data from ThingSpeak Cloud.
#include<ThingSpeak.h>
#include<ESP8266WiFi.h>
const char* ssid ="Dmk";
const char* password = "dmkumbhar12345";
unsigned long channelNumber = 2384685;
const char* readAPIKey = "YTZYEK2GPJWRGRL1";
const int fieldNumber1 = 1;
const int fieldNumber2 = 2;
WiFiClient client;
void setup()
{
Serial.begin(9600);
WiFi.begin(ssid, password);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
while(WiFi.status() != WL_CONNECTED)
{
P a g e 40 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

delay(500);
Serial.println("Wi-Fi Connecting......");
}
Serial.println("Wi-Fi connected successfully");
}
void loop()
{
long temp = ThingSpeak.readLongField(channelNumber, fieldNumber1, readAPIKey);
int statusCode = 0;
statusCode = ThingSpeak.getLastReadStatus();
if(statusCode == 200)
{
Serial.print("Temperature: ");
Serial.println(temp);
}
else
{
Serial.println("Unable to read channel/No internet connection");
}
delay(100);
long humidity = ThingSpeak.readLongField(channelNumber, fieldNumber2, readAPIKey);
statusCode = ThingSpeak.getLastReadStatus();
if(statusCode == 200)
{
Serial.print("Humidity: ");
Serial.println(humidity);
}
else
{
Serial.println("Unable to read channel/No internet connection");
}
delay(100);
}
P a g e 41 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

7.6 Output

 Temperature = _________0C
 Humidity =_________

7.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________
Faculty Signature

P a g e 42 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

8.0 LED ON/OFF using telegram app

Experiment Date
Date Planed Marks
No Conducted
8

8.1 Learning Objectives

 Student will able to interface ESP8266


 Student will able to turn on and off using Telegram App.
8.2 Aim
To write a program to turn on and off using Telegram App
8.3 Theory
To control an LED on or off using Telegram, need a microcontroller like ESP8266 or ESP32, a
Telegram bot, and a way to connect the microcontroller to a Telegram bot via WiFi. Then send
commands via Telegram to control the LED's state (on or off).
Telegram is a cloud-based instant messaging platform and communication app. It allows users to
send and receive messages, make voice and video calls, and share photos, videos, documents, and other
files. Telegram is available for smartphones running various operating systems, including iOS,
Android, and Windows.
Here's a general approach:
1. Create a Telegram Bot: Use the BotFather on Telegram to create a bot.
2. Connect your microcontroller to Telegram: Use libraries like Telepot for Python or Telegram
Bot Library for Arduino.
3. Develop the code: Write code on your microcontroller to:
 Listen for Telegram messages.
 Recognize commands like /on or /off (or similar).
 Control the LED's state (using HIGH or LOW values) based on the command.
4. Test and Deploy: Test your setup and deploy it to your desired location.
Here's a more detailed look at some components:
 ESP8266/ESP32:

These are popular microcontrollers with WiFi capabilities, allowing you to connect to the
internet and communicate with the Telegram bot.
 Telegram Bot:
This is a bot that you create on Telegram. It acts as an intermediary, receiving your commands
and sending them to your microcontroller.
P a g e 43 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

 Libraries:
Libraries like Telepot (Python) or Telegram Bot Library for Arduino simplify the process of
interacting with Telegram and your microcontroller.
Step to create Telegram Bot

1. Open telegram and find BotFather

2. Find the Botfather in the result and open it and click ok start.

3. Type /newbot and press enter.

4. Set the username for your bot.

5. Set the username for your bot (it must me end with bot)

6. You will get the token id, copy this ID and paste in Notepad

7. search IDBot in search and open it and click on start.

8. The bot will return the ID after you click on start

8.4 Diagram

8.5 Program
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

P a g e 44 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

#include <UniversalTelegramBot.h>

// Wi-Fi Credentials
const char* ssid = "Smart Bin";
const char* password = "7899262658";

// Telegram Bot Token


#define BOT_TOKEN "8151314051:AAG1fC84u1U23XWFAtqK9BEXq_p3Z1Yfx60"

WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);

const int ledPin = 5;


bool ledState = false;

unsigned long lastCheck = 0;


const unsigned long interval = 1000;

void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // LED initially OFF

WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(500); Serial.print(".");
}
Serial.println("\nConnected to Wi-Fi");
secured_client.setInsecure(); // For Telegram SSL
}

void handleMessage(String text, String chat_id) {


if (text == "/on") {
digitalWrite(ledPin, HIGH);
ledState = true;
bot.sendMessage(chat_id, "LED is ON", "");
}
else if (text == "/off") {
digitalWrite(ledPin, LOW);
P a g e 45 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

ledState = false;
bot.sendMessage(chat_id, "LED is OFF", "");
}
else if (text == "/status") {
bot.sendMessage(chat_id, ledState ? "LED is ON" : "LED is OFF", "");
}
else {
bot.sendMessage(chat_id, "Available Commands:\n/on\n/off\n/status", "");
}
}

void loop() {
if (millis() - lastCheck > interval) {
int newMsgs = bot.getUpdates(bot.last_message_received + 1);
while (newMsgs) {
for (int i = 0; i < newMsgs; i++) {
String chat_id = bot.messages[i].chat_id;
String text = bot.messages[i].text;
handleMessage(text, chat_id);
}
newMsgs = bot.getUpdates(bot.last_message_received + 1);
}
lastCheck = millis();
}
}

8.6 Output

 Status
 LED ON
 LED OFF

8.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________
Faculty Signature

P a g e 46 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

9.0 Upload temperature data to MQTT broker

Experiment Date
Date Planed Marks
No Conducted
9

9.1 Learning Objectives

 Student will able to interface ESP8266


 Student will able to upload temperature data to MQTT broker.
9.2 Aim
Write a program on Arduino to publish temperature data to MQTT broker.

9.3 Theory
MQTT stands for Message Queuing Telemetry Transport. MQTT is a simple messaging protocol,
designed for constrained devices with low bandwidth. So, it’s the perfect solution to exchange data
between multiple IoT devices.
Devices publish messages on a specific topic. All devices that are subscribed to that topic receive the
message.
In a publish and subscribe system, a device can publish a
message on a topic, or it can be subscribed to a particular
topic to receive messages
The MQTT broker is responsible for receiving all
messages, filtering the messages, deciding who is interested
in them, and then publishing the message to all subscribed
clients.
The MQTT broker is the central point of communication, and it is in charge of dispatching all messages
between the senders and the rightful receivers. A client is any device that connects to the broker and
can publish or subscribe to topics to access the information. A topic contains the routing information
for the broker. Each client that wants to send messages publishes them to a certain topic, and each
client that wants to receive messages subscribes to a certain topic. The broker delivers all messages
with the matching topic to the appropriate clients.
ThingSpeak™ has an MQTT broker at the URL mqtt3.thingspeak.com and port 1883. The ThingSpeak
broker supports both MQTT publish and MQTT subscribe.
In this Experiment, we will create a setup that allows a NODE MCUESP8266 board to send data to
another MCU ESP 8266, using MQTT (Message Queuing Telemetry Transport). The sender device,
P a g e 47 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

simply publishes a message to a broker service, which then can be subscribed to by a receiver device.
The data we will send consists of readings from a DHT11 sensor, including temperature and humidity
data, from a NODE MCU ESP8266 to another NODE MCU. This experiment utilizes the broker
test.mosquitto.org, an open-source service that is free for anyone to use.

Getting Started to MQTT


Go to Tools > Manage libraries.., and search for ArduinoMqttClient and install.

9.4 Diagram

9.5 Program
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>

// WiFi credentials
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

// MQTT Broker details


const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char* mqtt_topic = "nodeMCU/temperature";

// DHT sensor settings


#define DHTPIN D4 // GPIO2 on NodeMCU (change if needed)
#define DHTTYPE DHT11 // Change to DHT22 if using that sensor
P a g e 48 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

DHT dht(DHTPIN, DHTTYPE);


WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to WiFi: ");
Serial.println(ssid);

WiFi.begin(ssid, password);

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


delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected.");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Connecting to MQTT broker...");
if (client.connect("NodeMCUClient")) { // Client ID
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}

void setup() {
P a g e 49 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

Serial.begin(115200);
dht.begin();
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Read temperature as Celsius
float temperature = dht.readTemperature();

if (isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
} else {
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");

// Convert temperature to string


char tempStr[8];
dtostrf(temperature, 1, 2, tempStr);
// Publish temperature to MQTT topic
client.publish(mqtt_topic, tempStr);
}

delay(5000); // Publish every 5 seconds


}

9.6 Output

 Temperature = _________0C

9.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________
Faculty Signature

P a g e 50 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

10.0 Create UDP server

Experiment Date
Date Planed Marks
No Conducted
10

10.1 Learning Objectives

 Student will able to interface ESP8266


 Student will able to create UDP server on Arduino and respond with humidity data to
UDP client when requested.
10.2 Aim
Write a program to create UDP server on Arduino and respond with humidity data to UDP
client when requested.

10.3 Theory
User Datagram Protocol (UDP) is a network communication protocol that operates at the transport
layer of the Internet Protocol (IP) suite. It is a connectionless and lightweight protocol designed for fast
and efficient data transmission, but it does not provide the same level of reliability and error-checking
as Transmission Control Protocol (TCP).
UDP is a lightweight, connectionless, and fast protocol that prioritizes low-latency data transmission
over reliability. It is suitable for applications where occasional packet loss or out-of-order delivery can
be tolerated, and real-time communication is essential. However, for applications that require
guaranteed delivery and error recovery, TCP is a better choice.

To run Python code for UDP Server


1) Install python software
2) Open python IDLE
3) In python IDLE go to File  New File (it opens new script windows)  Type the code
4) Click on Run button and Save the program from script window
5) See the output from IDLE shell (command prompt)

10.4 Diagram

P a g e 51 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

10.5 Program
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <DHT.h>

#define DHTPIN D4
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

float temp;
char packet[1024];
const char* ssid = "choukimathwifi";
const char* password ="12345678";
const char* udpServerIP = "192.168.0.245"; // Replace <IP> with the actual IP address of your computer
unsigned int port = 9000;

WiFiUDP Udp; // Create a UDP object


void setup() {
Serial.begin(9600);
dht.begin();
WiFi.begin(ssid, password);

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


delay(500);
Serial.println("Connecting to WiFi...");
}
Serial.println("Wifi connected successfully");
}

void loop() {
P a g e 52 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

Udp.beginPacket(udpServerIP, port);

// Read temperature from DHT sensor and convert it to a string


temp = dht.readTemperature();
//confirm value in serila monitor
Serial.print("Temperature in degree Cel. :");
Serial.println(temp);
String tempStr = String(temp);

// Copy the temperature string into the packet buffer


tempStr.toCharArray(packet, 1024);

// Send the packet over UDP


Udp.write(packet);

// End the UDP packet and send it


Udp.endPacket();
delay(500);
}

Python code for UDP Server


import socket

UDP_IP = "192.168.0.245"
UDP_PORT = 9000

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


sock.bind((UDP_IP, UDP_PORT))

while True:
received_data, addr = sock.recvfrom(1024)
print(received_data)

10.6 Output

 Temperature = _________0C

10.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________
Faculty Signature

P a g e 53 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

11.0 Create TCP server

Experiment Date
Date Planed Marks
No Conducted
11

11.1 Learning Objectives

 Student will able to interface ESP8266


 Student will able to create TCP server on Arduino and respond with Temperature data to
TCP client when requested.
11.2 Aim
Write a program to create TCP server on Arduino and respond with Temperature data to TCP
client when requested.
11.3 Theory
The Transmission Control Protocol (TCP) is a widely used protocol in the Internet Protocol (IP) suite.
It is a connection-oriented protocol that provides reliable, ordered, and error-checked delivery of data
between applications running on hosts1. In IoT, TCP is used to establish connections between clients
and servers, allowing devices to interact with each other and resolve common problems.

A TCP server is a program that listens for incoming connections from clients and responds to their
requests. When a client connects to the server, it sends a request for data. The server then sends back
the requested data to the client. In IoT, TCP servers are used to provide access to data from sensors and
other devices
In the context of the Internet of Things (IoT), a TCP server refers to a network service running on a
device or gateway that listens for incoming TCP connections from other IoT devices or clients

In the context of IoT, TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are
two protocols of the Transport Layer that are used to transmit data between devices over a network.

TCP is a connection-oriented protocol that provides reliable delivery services by keeping track of the
segments being transmitted or received by assigning numbers to every single one of them. It also
implements an error control mechanism for reliable data transfer and takes into account the level of
congestion in the network .

On the other hand, UDP is a connectionless protocol that is used for simple request-response
communication when the size of data is less and hence there is lesser concern about flow and error
control. It is a suitable protocol for multicasting as UDP supports packet switching. Normally used for
real-time applications which cannot tolerate uneven delays between sections of a received message.

In summary, TCP is more reliable but slower than UDP, while UDP is faster but less reliable than TCP

Finding IP address of your computer


1) Search command Prompt from your PC
2) Type ipconfig in command prompt
P a g e 54 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

3) Search IPv4 Adress …….: 192.168.137.1 like this in prompt


4) Copy and paste the same in the program at tcpServerIP
11.4 Diagram

11.5 Program
#include <ESP8266WiFi.h>
#include <DHT.h>

#define DHTPIN D4
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

float temp;
const char* ssid = "choukimathwifi";
const char* password = "12345678";
const char* tcpServerIP = "192.168.1.6"; // Replace <IP> with the actual IP address of your computer
unsigned int port = 80; //most commonly used protocol port in TCP

WiFiClient client; // Create a TCP client object

void setup() {
Serial.begin(9600);
dht.begin();
WiFi.begin(ssid, password);

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


delay(500);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected successfully");

P a g e 55 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

void loop() {
client.connect(tcpServerIP, port);
// Read temperature from DHT sensor and convert it to a string
temp = dht.readTemperature();
// Confirm value in serial monitor
Serial.print("Temperature in degree Celsius: ");
Serial.println(temp);

// Send the temperature over TCP as a string


client.print(temp);
delay(500);

11.6 Output

 Temperature = _________0C

11.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________
Faculty Signature

12.0 Subscribe to MQTT broker for temperature data

Experiment Date
Date Planed Marks
No Conducted
12

12.1 Learning Objectives

 Student will able to interface ESP8266


 Student will able to subscribe to MQTT broker for temperature data and print it.

12.2 Aim
Write a program on Arduino to subscribe to MQTT broker for temperature data and print it.

12.3 Theory
The MQTT protocol was first introduced in 1999, as a light-weight publish and subscribe system. It is

P a g e 56 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

particularly useful for devices with low-bandwidth, where we can send commands, sensor values or
messages over the Internet with little effort.
A basic
explanation
on how it
works is
that a node,
for example
and
Arduino
with a Wi-
Fi module, sends a payload to a broker. A broker is a kind of "middle-point" server, that essentially
stores payloads sent to it, in something called topics. A topic, is a definition of what type of data it
contains, it could for example be "humidity" or " temperature". Another node can then subscribe to this
information, from the broker, and voilà, data has been moved from Node A to Node B over the
Internet.
One way to protect the data is for example, by using a token, something that is quite common when
working with various IoT services. For instance, if we are publishing something to a broker, anyone
that has the URL, e.g. randombroker.org/randomtopic can subscribe to it. But if we add a unique
token on both sides, they wouldn't be able to. These tokens could for example be Z6ACuLwr5T,
which is not exactly something easy to guess.

12.4 Diagram
P a g e 57 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

12.5 Program
#include <ESP8266WiFi.h>
#include <ArduinoMqttClient.h>

const char* ssid = "choukimathwifi";

const char* password ="12345678";

const char broker[] = "test.mosquitto.org";


int port = 1883;
const char topicT[] = "Temperature Value is ";
const char topicH[] = "Humidity Value is";

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

void setup() {

Serial.begin(9600);

Serial.print("Wifi connecting to ....");


Serial.print(ssid);
WiFi.begin(ssid, password);

while(WiFi.status()!=WL_CONNECTED){
Serial.println("connecting......");
delay(500);
P a g e 58 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

}
Serial.println("Wifi connected successfully");

Serial.print("Attempting to connect to the MQTT broker: ");


Serial.println(broker);

if (!mqttClient.connect(broker, port)) {
Serial.print("MQTT connection failed! Error code = ");
Serial.println(mqttClient.connectError());

while (1);
}
Serial.println("You're connected to the MQTT broker!");
Serial.println();

// set the message receive callback


mqttClient.onMessage(onMqttMessage);

Serial.print("Subscribing to topic: ");


Serial.println(topicH);
Serial.println(topicT);
Serial.println();

// subscribe to a topic
mqttClient.subscribe(topicT);
mqttClient.subscribe(topicH);

// topics can be unsubscribed using:


// mqttClient.unsubscribe(topic);

Serial.print("Topic Tempertaure: ");


Serial.println(topicT);
Serial.print("Topic Humidity: ");
Serial.println(topicH);
Serial.println();

void loop() {
mqttClient.poll();
delay(1000);
}
void onMqttMessage(int messageSize) {

P a g e 59 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in
Control systems Lab Manual / Semester – 4th
Electronics and Communication Engineering Department,

// we received a message, print out the topic and contents


Serial.println("Received a message with topic '");
Serial.print(mqttClient.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");

// use the Stream interface to print the contents


while (mqttClient.available()) {
Serial.print((char)mqttClient.read());
}
Serial.println();
Serial.println();
delay(1500);
}

12.6 Output

 Temperature = _________0C
 Humidity =_________

12.7 Conclusion

___________________________________________________________________________
___________________________________________________________________________
Faculty Signature

P a g e 60 | 60
____________________________________________________________________________________________________
_Nidasoshi-591 236, Tal :Hukkeri, Dist: Belagavi, Karnataka, India.
Phone: +91-8333-278887, Fax: 278886, Web: www.hsit.ac.in, E-mail: principal@hsit.ac.in

You might also like