0% found this document useful (0 votes)
3 views44 pages

IoT Lab Manual

The document is an IoT lab manual for the Department of Electronics & Communication Engineering, detailing course objectives, outcomes, and a syllabus for practical experiments. It includes a series of experiments involving Arduino and Raspberry Pi for interfacing various sensors and modules, aimed at developing students' skills in IoT project implementation. The manual also outlines program outcomes, educational objectives, and the vision and mission of the department to prepare students for professional engineering roles.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views44 pages

IoT Lab Manual

The document is an IoT lab manual for the Department of Electronics & Communication Engineering, detailing course objectives, outcomes, and a syllabus for practical experiments. It includes a series of experiments involving Arduino and Raspberry Pi for interfacing various sensors and modules, aimed at developing students' skills in IoT project implementation. The manual also outlines program outcomes, educational objectives, and the vision and mission of the department to prepare students for professional engineering roles.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Department of Electronics & Communication Engineering

IoT (Internet of Things) lab manual

Sub Code: 21ECS81

V SEMESTER

Scheme 2021

No. 22/1, Govindpura Main Road, Arabic College Post, Niagara, Bangalore-45

Prepared By: Scrutinized By:


Mr. Satish M Dr. Zahira Tabassum
Asst. Professor, Dept. of ECE Professor, Dept. of ECE

Lab In charge: Mr. Satish M

Lab Instructor: Mr. Asif Pasha


PROGRAM OUTCOMES
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization for the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet t h e specified needs with appropriate
consideration for public health and safety, and cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: use research based knowledge and research
methods including design of Experiments, analysis & interpretation of data, and synthesis of the
information to provide valid conclusions.
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.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with t h e society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of t h e
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.
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.

PSPOs

 An ability to understand the basic concepts in Electronics & Communication Engineering and
to apply them to various areas, like Electronics, Communications, Signal processing, VLSI,
Embedded systems etc., in the design and implementation of complex systems.
 An ability to solve complex Electronics and communication Engineering problems, using
latest hardware and software tools, along with analytical skills to arrive cost effective and
appropriate solutions.
 An ability to become an entrepreneur or to contribute to industrial services and / or Govt.
organizations in the field of Electronics and Communication Engg.
 An ability to work on multidisciplinary teams with efficiency in different Programming
techniques.
Vision & Mission of the Department

Vision
To shape the students as disciplined humane engineers who can build a strong, peaceful and vibrant
country and focus on mutual respect, tolerance and professional ethics.

Mission
 To provide the best possible educational experience through excellence in teaching
and research activities for today's students and professionals of tomorrow.
 To hone young minds and train them to be conscientious individuals who will serve
the society as competent professionals in the field of Electronics and communication.

Program Educational Objectives

 Our graduates will possess good knowledge in engineering fundamentals.


 Our graduates will be capable of analyzing and designing systems.
 Our graduates will be capable of creating innovative products in multidisciplinary areas.
 The graduates will be ethically strong personnel with good communication
and interpersonal skills with high moral values.
 They will have a desire for continuous learning and R&D.
Course objectives: This course will enable students to:
 To impart necessary and practical knowledge of components of Internet of Things.
 To develop skills required to build real-life IoT based projects.

Course outcomes: After studying this course, students will be able to:
 Understand internet of Things and its hardware and software components.
 Interface I/O devices, sensors & communication modules.
 Remotely monitor data and control devices.
 Develop real life IoT based projects.
Syllabus

Sl.No Experiments
1  To interface LED/Buzzer with Arduino/Raspberry Pi and write a program to ‘turn ON’ LED for 1
sec after every 2 seconds.
 To interface Push button/Digital sensor (IR/LDR) with Arduino/Raspberry Pi and write a Program
to ‘turn ON’ LED when push button is pressed or at sensor detection.
2  To interface DHT11 sensor with Arduino/Raspberry Pi and write a program to print temperature
and humidity readings.
 To interface OLED with Arduino/Raspberry Pi and write a program to print temperature and
Humidity readings on it.
3 To interface motor using relay with Arduino/Raspberry Pi and write a program to ‘turn ON’
Motor when push button is pressed.

4 To interface Bluetooth with Arduino/Raspberry Pi and write a program to send sensor data to
Smartphone using Bluetooth.
5 To interface Bluetooth with Arduino/Raspberry Pi and write a program to turn LED ON/OFF
When '1'/'0' is received from smartphone using Bluetooth.
6 Write a program on Arduino/Raspberry Pi to upload temperature and humidity data to
Thing speak cloud.
7 Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity data from
Thing speak cloud.
8 To install MySQL database on Raspberry Pi and perform basic SQL queries.
9 Write a program on Arduino/Raspberry Pi to publish temperature data to MQTT broker.
10 Write a program to create UDP server on Arduino/Raspberry Pi and respond with humidity data
To UDP client when requested.
11 Write a program to create TCP server on Arduino/Raspberry Pi and respond with humidity data
To TCP client when requested.
12 Write a program on Arduino/Raspberry Pi to subscribe to MQTT broker for temperature data
And print it.
Contents

Sl.no Name of the Experiment Page


No.
1. (1.1)LED/Buzzer To interface with Arduino/Raspberry Pi and write a program to 'turn ON' LED for 1sec after every 13-14
2 seconds.
(1.2)To interface Push button/Digital sensor (IR/LOR) with Arduino/Raspberry Pi and write a program to 'turn ON'
LEDwhen push button is pressed or at sensor detection.

2. (2.1) To interface DHTll sensor with Arduino/Raspberry Pi and write a program to print temperature and humidity 15-18
readings.
(2.2) To interface OLEO with Arduino/Raspberry Pi and write a program to print temperature and humidity
readings on it.

3. To interface motor using relay with Arduino/Raspberry Pi and write a program to 'turn ON' motor when push 19-19
button is pressed.

4. To interface Bluetooth with Arduino/Raspberry Pi and write a program to send sensor data to smartphone using 20-22
Bluetooth.

5. To interface Bluetooth with Arduino/Raspberry Pi and write a program to turn LED ON/OFF when '1'/'0' is received 23-25
from smartphone using Bluetooth.

6. Write a program on Arduino/Raspberry Pi to upload temperature and humidity data to thing speak cloud. 26-28

7. Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity data from thing speak cloud. 29-30

8. To install MySQL database on Raspberry Pi and perform basic SQL queries.

9. Write a program on Arduino/Raspberry Pi to publish temperature data to MQTT broker. 31-34


10. Write a program to create UDP server on Arduino/Raspberry Pi and respond with humidity data to UDP client 35-37
when requested.

11. Write a program to create TCP server on Arduino/Raspberry Pi and respond with humidity data to TCP client when 38-40
requested.

12. Write a program on Arduino/Raspberry Pi to subscribe to MQTT broker for temperature data 41-43
And print it.
IoT Lab 21ECS81

Procedure to Create Project in Arduino

1. Open The Arduino Software.

2. Open the new file.

Dept of E&CE, HKBKCE Page 8


IoT Lab 21ECS81

3. Select the board as arduino uno in software tools.

4. Select the exact com port connected to your computer system


from tool menu.

Dept of E&CE, HKBKCE Page 9


IoT Lab 21ECS81

5. Include the required library from the sketch menu.

6. Add the required libraries from manage libraries.

Dept of E&CE, HKBKCE Page 10


IoT Lab 21ECS81

7. verify the programme by clicking the tick button .

8. Compile the programme clicking the right arrow button.

Dept of E&CE, HKBKCE Page 11


IoT Lab 21ECS81

9. Observe The Output On Serial Monitor Or On The Circuit As Per


Your Program.

Dept of E&CE, HKBKCE Page 12


IoT Lab 21ECS81

Experiment 1.1:
LED/Buzzer To interface with Arduino/Raspberry Pi and write a program to 'turn ON' LED for 1sec after every 2 seconds.

Aim:
To interface LED/Buzzer with Arduino and write a program to ‘turn ON’ LED for 1 sec after every 2 seconds.
Program:

const int ledPin = 13;


void setup() {
pinMode(ledPin, OUTPUT);
}

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

Dept of E&CE, HKBKCE Page 13


IoT Lab 21ECS81

Experiment 1.2:
To interface Push button/Digital sensor (IR/LOR) with Arduino/Raspberry Pi and write a program to 'turn ON' LED
when push button is pressed or at sensor detection.
Aim:
To interface IR sensor with Arduino and write a program to ‘turn ON’ LED when sensor detection.
Program:

void setup() {
Serial.begin(9600);
pinMode(2,INPUT); // IR sensor(out pin) input to arduino uno
pinMode(10,OUTPUT); // Arduino 10th pin connect to the LED positive
}

void loop() {
int sensor_state=digitalRead(2);
if(sensor_state==1){
Serial.println("Motion Detected");
digitalWrite(10,HIGH);

}else{
Serial.println("Motion Not Detected");
digitalWrite(10,LOW);

}
}

Circuit Diagram:

Dept of E&CE, HKBKCE Page 14


IoT Lab 21ECS81

Experiment 2.1:
To interface DHTll sensor with Arduino/Raspberry Pi and write a program to print temperature and humidity readings.
Aim:
To interface DHT11 sensor with Arduino and write a program to print temperature and humidity readings.
Program:

#include "DHT.h"

#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
Serial.println(F("DHTxx test!"));

dht.begin();
}

void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();

if (isnan(h) || isnan(t) || isnan(f)) {


Serial.println(F("Failed to read from DHT sensor!"));
return;
}

Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.println(F(" degree C "));

Dept of E&CE, HKBKCE Page 15


IoT Lab 21ECS81

Circuit Diagram:

Dept of E&CE, HKBKCE Page 16


IoT Lab 21ECS81

Experiment 2.2:
To interface OLEO with Arduino/Raspberry Pi and write a program to print temperature and humidity readings on it.

Aim:
To interface OLED with Arduino and write a program to print temperature and humidity readings on it.
Program:

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHT.h"

#define dhtpin 2
#define dhttype DHT11

DHT dht(dhtpin, dhttype);

Adafruit_SSD1306 myDisplay(128, 64, &Wire);

void setup() {
myDisplay.begin(SSD1306_SWITCHCAPVCC, 0x3C);
dht.begin();
}

void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
myDisplay.clearDisplay();

myDisplay.setTextSize(1);
myDisplay.setCursor(0,0);
myDisplay.setTextColor(WHITE);
myDisplay.print("Temperature: ");
myDisplay.print(temperature);
myDisplay.println(" °C");
myDisplay.print("Humidity: ");
myDisplay.print(humidity);
myDisplay.println(" %");

myDisplay.display();
delay(3000);
}

Dept of E&CE, HKBKCE Page 17


IoT Lab 21ECS81

Circuit Diagram:

Dept of E&CE, HKBKCE Page 18


IoT Lab 21ECS81

Experiment 3:
To interface motor using relay with Arduino/Raspberry Pi and write a program to 'turn ON' motor when push button is pressed.
Aim:
To interface motor using relay with Arduino/Raspberry Pi and write a program to 'turn ON' motor when push button is pressed.

Program:

void setup() {
pinMode(2,INPUT); //IR sensor input
pinMode(10,OUTPUT); // output of arduino uno to input of the relay
}

void loop() {
int sensor_state=digitalRead(2);
if(sensor_state==1){
digitalWrite(10,HIGH);
}else{
digitalWrite(10,LOW);
}
}

Circuit Diagram:

Dept of E&CE, HKBKCE Page 19


IoT Lab 21ECS81

Experiment 4:
To interface Bluetooth with Arduino/Raspberry Pi and write a program to send sensor data to smartphone using Bluetooth.
Aim:
To interface Bluetooth with Arduino and write a program to send sensor data to smartphone using Bluetooth.
Procedure:
Install Serial Bluetooth Terminal in smart phone

Configuring with AT Commands (HC-05)


*AT command Mode*
1. Disconnect the +5v line from the modules end as shown in the hook diagram above.
2. Press and hold the switch (DO NOT RELEASE IT!)
3. Reconnect the +5v connection
4. Now Release the switch. Observe that the led on the module starts blinking once every two seconds, slower than
normal disconnected mode.
5. Upload the code below to the Arduino.
Program:

#include <SoftwareSerial.h>
#include "DHT.h"

#define dhtpin 2
#define dhttype DHT11
SoftwareSerial EEBlue(11, 10); // RX | TX

DHT dht(dhtpin, dhttype);


void setup()
{

Serial.begin(9600);
configure_HC05();
EEBlue.begin(9600); //Default Baud for comm, it may be different for your Module.
Serial.println("The bluetooth gates are open.\n Connect to HC-05 from any other bluetooth device
with 0000 OR 1234 as pairing key!.");
dht.begin();

void loop()
{
float temperature = dht.readTemperature();

Dept of E&CE, HKBKCE Page 20


IoT Lab 21ECS81

float humidity = dht.readHumidity();


Serial.print("Temperature: ");
delay(100);
Serial.print(temperature);
delay(500);
Serial.print(" °C, Humidity: ");
delay(100);
Serial.print(humidity);
delay(500);
Serial.println(" %");
delay(100);

EEBlue.print("Temperature: ");
delay(100);
EEBlue.print(temperature);
delay(500);
EEBlue.print(" degree C, Humidity: ");
delay(100);
EEBlue.print(humidity);
delay(500);
EEBlue.println(" %");
delay(2000);

}
void configure_HC05(){
EEBlue.begin(38400);
EEBlue.println("AT");
delay(500);
EEBlue.println("AT+ORGL");
delay(1000);
}

Dept of E&CE, HKBKCE Page 21


IoT Lab 21ECS81

Circuit Diagram:

Dept of E&CE, HKBKCE Page 22


IoT Lab 21ECS81

Experiment 5:
To interface Bluetooth with Arduino/Raspberry Pi and write a program to turn LED ON/OFF when '1'/'0' is received from
smartphone using Bluetooth.
Aim:
To interface Bluetooth with Arduino and write a program to turn LED ON/OFF when '1'/'0' is received from smartphone using
Bluetooth.
Procedure:
Install Serial Bluetooth Terminal in smart phone

Configuring with AT Commands (HC-05)


*AT command Mode*
1. Disconnect the +5v line from the modules end as shown in the hook diagram above.
2. Press and hold the switch (DO NOT RELEASE IT!)
3. Reconnect the +5v connection
4. Now Release the switch. Observe that the led on the module starts blinking once every two seconds, slower than
normal disconnected mode.
5. Upload the code below to the Arduino.

Program:

#include <SoftwareSerial.h>

const int LED= 13;


const char turnON ='1';
const char turnOFF ='0';
SoftwareSerial EEBlue(11, 10); // RX | TX

void setup()
{

Serial.begin(9600);
pinMode(LED, OUTPUT);
configure_HC05();
EEBlue.begin(9600); //Default Baud for comm, it may be different for your Module.
Serial.println("The bluetooth gates are open.\n Connect to HC-05 from any other bluetooth device
with 1234 as pairing key!.");
Serial.print("Now You can TURN ON LED by sending '1' and TURN OFF by '0'");
EEBlue.println("Now You can TURN ON LED by sending '1' and TURN OFF by '0'");

Dept of E&CE, HKBKCE Page 23


IoT Lab 21ECS81

void loop()
{
char message;

if (EEBlue.available()) {
message=EEBlue.read();
Serial.write(message);

if(message==turnON){
digitalWrite(LED, HIGH); //Turn LED ON
Serial.println(" :LED Turned ON");
EEBlue.println(" :LED Turned ON");
delay(500);
}

else if(message==turnOFF){
digitalWrite(LED, LOW); //Turn LED Off
Serial.println(" :LED Turned OFF");
EEBlue.println(" :LED Turned OFF");
delay(500);
}
}

}
void configure_HC05(){
EEBlue.begin(38400);
EEBlue.println("AT");
delay(500);
EEBlue.println("AT+ORGL");
delay(1000);
}

Dept of E&CE, HKBKCE Page 24


IoT Lab 21ECS81

Circuit Diagram:

Dept of E&CE, HKBKCE Page 25


IoT Lab 21ECS81

Experiment 6:
Write a program on Arduino/Raspberry Pi to upload temperature and humidity data to thing speak cloud.
Aim:
Write a program on Arduino/Raspberry Pi to upload temperature and humidity data to thing speak cloud.
Procedure:
Step-1: Create a new account in ThingSpeak and login into the account.
Step-2: Create a new Channel in ThingSpeak.
Step-3: Mention the details of Mobile hotspot username and password correctly in Arduino program.
Step-4: Copy the Channel ID from ThingSpeak and note in the program.
Step-5: Copy the Write API Key from thingSpeak Api keys generator and note the same in arduino program.
Step-6: Create a widget tab for observing the last values of temperature and humidity individually.
Step-7: Run the program to check the last values of temperature and humidity in widget tab or command window in Arduino software
(The last value of Temperature and humidity will be exported from Thingspeak)

Program:

#include "WiFiEsp.h"
#include "ThingSpeak.h" // always include thingspeak header file after other header files and
custom macros
#include "DHT.h"

#define dhtpin 2
#define dhttype DHT11

DHT dht(dhtpin,dhttype);
char ssid[] = "SATHISH"; // change your wifi ssid
char pass[] = "123456789"; // change your wifi password
unsigned long myChannelNumber = 2296803; // change your thingspeak channel ID

const char * myWriteAPIKey = "IN3JETGQSH3DV2IX"; // change your thingspeak write api key
WiFiEspClient client;

#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX

String myStatus = "";

void setup() {
Serial.begin(115200); // Initialize serial
dht.begin(); // Initialize serial for DHT sensor
Dept of E&CE, HKBKCE Page 26
IoT Lab 21ECS81

Serial1.begin(19200); // initialize serial for ESP module


Serial.print("Searching for ESP8266...");
// initialize ESP module
WiFi.init(&Serial1);
// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or
WEP network
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected.");
}

ThingSpeak.begin(client); // Initialize ThingSpeak


}

void loop() {
float t=dht.readTemperature();
float h=dht.readHumidity();
ThingSpeak.setField(1, t);
ThingSpeak.setField(2, h);
// set the status
ThingSpeak.setStatus(myStatus);
// write to the ThingSpeak channel
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
delay(20000); // Wait 20 seconds to update the channel again
}

Dept of E&CE, HKBKCE Page 27


IoT Lab 21ECS81

Circuit Diagram:

Dept of E&CE, HKBKCE Page 28


IoT Lab 21ECS81

Experiment 7:
Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity data from thing speak cloud.
Aim:
Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity data from thing speak cloud.
Procedure:
Step-1: Create a new account in ThingSpeak and login into the account.
Step-2: Create a new Channel in ThingSpeak.
Step-3: Mention the details of Mobile hotspot username and password correctly in Arduino program.
Step-4: Copy the Channel ID from ThingSpeak and note in the program.
Step-5: Copy the Write API Key from thingSpeak Api keys generator and note the same in arduino program.
Step-6: Create a widget tab for observing the last values of temperature and humidity individually.
Step-7: Run the program to check the last values of temperature and humidity in widget tab or command window in Arduino software
(The last value of Temperature and humidity will be exported from Thingspeak)
Program:

#include "WiFiEsp.h"
#include "ThingSpeak.h" // always include thingspeak header file after other header files and
custom macros
char ssid[] = "SATHISH"; // change your wifi ssid
char pass[] = "123456789"; // change your wifi password
unsigned long counterChannelNumber = 2296803; // change your thingspeak channel ID
const char * myCounterReadAPIKey = "ZJN3QM0H28MHAVF5";// change your thingspeak read api key

WiFiEspClient client;

#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX

void setup() {
Serial.begin(115200); //Initialize serial and wait for port to open
Serial1.begin(19200); // initialize serial for ESP module
Serial.print("Searching for ESP8266...");
// initialize ESP module
WiFi.init(&Serial1);
delay(5000);
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP
network

Dept of E&CE, HKBKCE Page 29


IoT Lab 21ECS81
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected");
}
ThingSpeak.begin(client); // Initialize ThingSpeak
}

void loop() {
int statusCode = 0;
float temperature = ThingSpeak.readFloatField(counterChannelNumber, 1, myCounterReadAPIKey); //1
indicates temperature field in thingspeak.com(my channel)
delay(1000);
float humidity=ThingSpeak.readFloatField(counterChannelNumber, 2, myCounterReadAPIKey); //2
indicates humidity field in thingspeak.com(my channel)
// Check the status of the read operation to see if it was successful
statusCode = ThingSpeak.getLastReadStatus();
delay(2000);
if(statusCode == 200){
Serial.println("Temperature: " + String(temperature)+" deg C");
Serial.println("Humidity: "+String(humidity)+" %");
}
else{
Serial.println("Problem reading channel. HTTP error code " + String(statusCode));
}
delay(15000); // No need to read the counter too often.
}

Circuit Diagram:

Dept of E&CE, HKBKCE Page 30


IoT Lab 21ECS81

Experiment 9:
Write a program on Arduino/Raspberry Pi to publish temperature data to MQTT broker.

Aim:
Write a program on Arduino/Raspberry Pi to publish temperature data to MQTT broker.
Procedure:
TO CREATE A CHANNEL AND MQTT USER NAME AND PASSWORD
Turn on your hotspot and note down the SSID (hotspot name) and password.
CREATE A CHANNEL
• Go to your Thing Speak account on a web browser.
• Navigate to the "Channels" tab and click on "New Channel."
• Fill in the required details for the new channel, such as name and description.
• Note down the Channel ID provided after creating the channel.

CREATE MQTT USER NAME AND PASSWORD


• In your Thing Speak account, click on "Devices" and then select "MQTT."
• Click on "Add Device" and provide the necessary information like device name and optional description.
• In the "Authorize to Channel" section, select the channel you created earlier, then click "Add Channel" and "Add Device."
• Note down or download the MQTT client ID, user ID, and password provided.
• In program, find the section responsible for MQTT client connection.
Replace the placeholders for SSID, password, Channel ID, MQTT user ID, and password with the respective values obtained in the
Previous steps.

Program:

#include <DHT.h>
#include <WiFiEsp.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>

#define DHTPIN 2 // connect to D4 on ESP-01


#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

SoftwareSerial Serial1(6, 7); // RX, TX for ESP-01

char ssid[] = "SATHISH"; // change your wifi ssid


char pass[] = "123456789"; // change your wifi password

WiFiEspClient espClient;
Dept of E&CE, HKBKCE Page 31
IoT Lab 21ECS81

PubSubClient client(espClient);

const char* mqtt_server = "mqtt3.thingspeak.com"; // change your mqtt server

const char* publishTopic = "channels/2296803/publish"; // REPLACE WITH YOUR CHANNEL ID


const char* subscribeTopicFor_Command_1 = "channels/2296803/subscribe/fields/field1"; // REPLACE
WITH YOUR CHANNEL ID

const unsigned long postingInterval = 20L * 1000L; // Post data every 20 seconds.

unsigned long lastUploadedTime = 0;

void setup_wifi() {
delay(10);
Serial.print("\nConnecting to ");
Serial.println(ssid);

WiFi.init(&Serial1);
int status = WiFi.begin(ssid, pass);

while (status != WL_CONNECTED) {


delay(500);
Serial.print(".");
status = WiFi.begin(ssid, pass);
}

randomSeed(micros());
Serial.println("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());
}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("JwgTGQc1HikbMBwpNC4RISs", "JwgTGQc1HikbMBwpNC4RISs",
"w25Z2L14X8OkDNwIgttnlk8k")) { // REPLACE WITH YOUR MQTT USERNAME AND PASSWORD
Serial.println("connected");
client.subscribe(subscribeTopicFor_Command_1);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
Dept of E&CE, HKBKCE Page 32
IoT Lab 21ECS81

void callback(char* topic, byte* payload, unsigned int length) {


String incomingMessage = "";
for (int i = 0; i < length; i++) incomingMessage += (char)payload[i];

Serial.println("Message arrived [" + String(topic) + "] " + incomingMessage);


}

void publishMessage(const char* topic, String payload, boolean retained) {


if (client.publish(topic, payload.c_str(), retained)) {
Serial.println("Message published [" + String(topic) + "]: " + payload);
}
}

void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
Serial1.begin(19200);
dht.begin();

setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

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

if (millis() - lastUploadedTime > postingInterval) {


String dataText = String("field1=" + String(temperature)+"&status=MQTTPUBLISH");
publishMessage(publishTopic, dataText, true);
lastUploadedTime = millis();
}
}

Dept of E&CE, HKBKCE Page 33


IoT Lab 21ECS81

Circuit Diagram:

Dept of E&CE, HKBKCE Page 34


IoT Lab 21ECS81

Experiment 10:
Write a program to create UDP server on Arduino/Raspberry Pi and respond with humidity data
To UDP client when requested.
Aim:
Write a program to create UDP server on Arduino/Raspberry Pi and respond with humidity data
To UDP client when requested.

Program 1 in Arduino IDE – UDP Server:

#include <DHT.h>
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include "SoftwareSerial.h"
// Replace pin and type with your sensor details
#define DHTPIN 2 // connect to D4 on ESP-01
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// SoftwareSerial pins for communication with ESP-01
SoftwareSerial Serial1(6, 7); // RX, TX
// WiFi settings
char ssid[] = "SATHISH"; // change your wifi ssid
char pass[] = "123456789"; // change your wifi password
WiFiEspUDP udp;
void setup() {
Serial.begin(115200);
Serial1.begin(19200);
WiFi.init(&Serial1);

connectToWiFi();
// Print the local IP address
Serial.print("Arduino IP Address: ");
Serial.println(WiFi.localIP());
// Initialize the DHT sensor
dht.begin();
// Start UDP
udp.begin(8888);
}

void loop() {
// Check if data is available to read
int packetSize = udp.parsePacket();
if (packetSize) {
// Read the request
char request[packetSize];
udp.read(request, packetSize);
request[packetSize] = '\0'; // Null-terminate the string
// Check the request content
Dept of E&CE, HKBKCE Page 35
IoT Lab 21ECS81

if (strcmp(request, "GET_HUMIDITY") == 0) {
float humidity = dht.readHumidity();
char response[10];
//snprintf(response, sizeof(response), "%.2f", humidity); don't use this line creating error
dtostrf(humidity, 4, 2, response);
// Send the response to the UDP client
udp.beginPacket(udp.remoteIP(), udp.remotePort());
udp.write(response, strlen(response));
udp.endPacket();
}
}
}
void connectToWiFi() {
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
if (WiFi.begin(ssid, pass) != WL_CONNECTED) {
Serial.println("Failed to connect to WiFi. Retrying...");
delay(5000);
}
}
Serial.println("Connected to WiFi");
}

Program 2 in Python(Idle) – UDP Client for data request to verify:


import socket

UDP_IP = "192.168.43.37" # change your board IP address


UDP_PORT = 8888
MESSAGE = "GET_HUMIDITY"

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


sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
data, addr = sock.recvfrom(1024)
print(f"Received humidity: {data.decode('utf-8')}")

sock.close()

Dept of E&CE, HKBKCE Page 36


IoT Lab 21ECS81

Circuit Diagram:

Dept of E&CE, HKBKCE Page 37


IoT Lab 21ECS81

Experiment 11:
Write a program to create TCP server on Arduino/Raspberry Pi and respond with humidity data
to TCP client when requested.
Aim:
Write a program to create TCP server on Arduino/Raspberry Pi and respond with humidity data
to TCP client when requested.

Program 1 in Arduino IDE – TCP Server:

#include <DHT.h>
#include <WiFiEsp.h>
#include "SoftwareSerial.h"

// Replace pin and type with your sensor details


#define DHTPIN 2 // connect to D4 on ESP-01
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// SoftwareSerial pins for communication with ESP-01


SoftwareSerial Serial1(6, 7); // RX, TX

// WiFi settings
char ssid[] = "SATHISH"; // change your wifi ssid
char pass[] = "123456789"; // change your wifi password

WiFiEspServer server(80); // Port 80 for HTTP

void setup() {
Serial.begin(115200);
Serial1.begin(19200);

WiFi.init(&Serial1);

// Connect to WiFi
connectToWiFi();

// Print the local IP address


Serial.print("Arduino IP Address: ");
Serial.println(WiFi.localIP());

// Initialize the DHT sensor


dht.begin();

// Start the server


server.begin();

Dept of E&CE, HKBKCE Page 38


IoT Lab 21ECS81

void loop() {
// Check for a client request
WiFiEspClient client = server.available();

if (client) {
Serial.println("New client connected");

// Read the request


String request = client.readStringUntil('\r');
Serial.println(request);

// Check the request content


if (request.indexOf("GET_HUMIDITY") != -1) {
// Respond with humidity data
float humidity = dht.readHumidity();
char response[10];
dtostrf(humidity, 4, 2, response);
//sending response
client.println(response);

// Close the connection


client.stop();
Serial.println("Client disconnected");
}

// Other tasks in your loop can go here


}

void connectToWiFi() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Connecting to WiFi");
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
Serial.println("Failed to connect to WiFi. Retrying...");
delay(5000);
}
Serial.println("Connected to WiFi");
}
}

Dept of E&CE, HKBKCE Page 39


IoT Lab 21ECS81

Program 2 in Python(Idle) – TCP Client for data request to verify:


import socket

TCP_IP = "192.168.43.37" # Replace with the actual IP address of your ESP8266


TCP_PORT = 80

def send_tcp_request(request):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((TCP_IP, TCP_PORT))
s.sendall(request.encode())
response = s.recv(1024).decode()
print("Received response:", response)

# Test the "GET_HUMIDITY" request


send_tcp_request("GET_HUMIDITY")

Circuit Diagram:

Dept of E&CE, HKBKCE Page 40


IoT Lab 21ECS81

Experiment 12:
Write a program on Arduino/Raspberry Pi to subscribe to MQTT broker for temperature data
And print it.

Aim:
Write a program on Arduino/Raspberry Pi to subscribe to MQTT broker for temperature data
And print it.
Procedure:
TO CREATE A CHANNEL AND MQTT USER NAME AND PASSWORD
Turn on your hotspot and note down the SSID (hotspot name) and password.
CREATE A CHANNEL
• Go to your Thing Speak account on a web browser.
• Navigate to the "Channels" tab and click on "New Channel."
• Fill in the required details for the new channel, such as name and description.
• Note down the Channel ID provided after creating the channel.

CREATE MQTT USER NAME AND PASSWORD


• In your Thing Speak account, click on "Devices" and then select "MQTT."
• Click on "Add Device" and provide the necessary information like device name and optional description.
• In the "Authorize to Channel" section, select the channel you created earlier, then click "Add Channel" and "Add Device."
• Note down or download the MQTT client ID, user ID, and password provided.
• In program, find the section responsible for MQTT client connection.
Replace the placeholders for SSID, password, Channel ID, MQTT user ID, and password with the respective values obtained in the
Previous steps.
Program:

#include <WiFiEsp.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>

SoftwareSerial Serial1(6, 7); // RX, TX for ESP-01

char ssid[] = "SATHISH"; // change your wifi ssid


char pass[] = "123456789"; // change your wifi password

WiFiEspClient espClient;
PubSubClient client(espClient);

const char* mqtt_server = "mqtt3.thingspeak.com";

Dept of E&CE, HKBKCE Page 41


IoT Lab 21ECS81

const char* subscribeTopicFor_Field1 = "channels/2296803/subscribe/fields/field1"; // REPLACE WITH


YOUR CHANNEL ID

void setup_wifi() {
delay(10);
Serial.print("\nConnecting to ");
Serial.println(ssid);

WiFi.init(&Serial1);
int status = WiFi.begin(ssid, pass);

while (status != WL_CONNECTED) {


delay(500);
Serial.print(".");
status = WiFi.begin(ssid, pass);
}

randomSeed(micros());
Serial.println("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {


String incomingMessage = "";
for (int i = 0; i < length; i++) incomingMessage += (char)payload[i];

Serial.println("Message arrived [" + String(topic) + "] " + incomingMessage);


}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("JwgTGQc1HikbMBwpNC4RISs", "JwgTGQc1HikbMBwpNC4RISs",
"w25Z2L14X8OkDNwIgttnlk8k")) {
Serial.println("connected");
// Subscribe to the desired topics here
client.subscribe(subscribeTopicFor_Field1);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}

Dept of E&CE, HKBKCE Page 42


IoT Lab 21ECS81

void setup() {
Serial.begin(115200);
Serial1.begin(19200);

setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}

Circuit Diagram:

Dept of E&CE, HKBKCE Page 43

You might also like