67% found this document useful (9 votes)
13K views58 pages

BEC657C Internet of Things Lab Manual by Raghunath VTU

The document is a lab manual for the Internet of Things (IoT) course at Acharya Institute of Technology, detailing the Arduino UNO and its specifications, as well as various experiments involving interfacing sensors and devices with Arduino. It includes objectives, required components, connection diagrams, and sample code for multiple experiments such as controlling LEDs, reading temperature and humidity, and using communication protocols. The manual aims to equip students with practical skills for building IoT projects using Arduino and Raspberry Pi.

Uploaded by

Raghunath B H
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
67% found this document useful (9 votes)
13K views58 pages

BEC657C Internet of Things Lab Manual by Raghunath VTU

The document is a lab manual for the Internet of Things (IoT) course at Acharya Institute of Technology, detailing the Arduino UNO and its specifications, as well as various experiments involving interfacing sensors and devices with Arduino. It includes objectives, required components, connection diagrams, and sample code for multiple experiments such as controlling LEDs, reading temperature and humidity, and using communication protocols. The manual aims to equip students with practical skills for building IoT projects using Arduino and Raspberry Pi.

Uploaded by

Raghunath B H
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 58

ACHARYA INSTITUTE OF TECHNOLOGY

Bengaluru – 560 107.

Department of Electronics and Communication

LAB MANUAL

Academic Year : 2024 – 25(EVEN SEMESTER)

Programme (UG/PG) : UG

Year / Semester : VI

Course Code : BEC657C

Course Title : Internet of Things (IoT) Lab

Dr Raghunath B H

Name:________________________
USN:_________________________
SEM: _____Sec: _____ Batch :_______

1
IoT (Internet of Things) Lab Semester 6
Course Code BEC657C CIE Marks 50
Teaching Hours/Week (L:T:P: S) 0:0:2:0 SEE Marks 50
Credits 01 Exam Hours 3
Examination type (SEE) Practical
Course Objectives:
This course will enable students to

 To impart necessary and practical knowledge of components of the Internet of Things


 To develop skills required to build real-life IoT-based projects.

Sl.No. Experi
1(i) To interface LED/Buzzer with Arduino /Raspberry Pi and write a program to ‘turn ON’
LED for 1 sec after every 2 seconds.
1(ii) 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.
2 (i) To interface the DHT11 sensor with Arduino /Raspberry Pi and write a program to
print temperature and humidity readings.
2(ii) To interface OLED with Arduino /Raspberry Pi and write a program to print its
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(i) Write an Arduino/Raspberry Pi program to interface the Soil Moisture Sensor.
4(ii) 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.
6 Write a program on Arduino/Raspberry Pi to upload temperature and humidity
data to thingspeak cloud.
7 Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity
data from thingspeak cloud.
8 Write a program to interface LED using Telegram App.
9 Write a program on Arduino/Raspberry Pi to publish temperature data to the MQTT
broker.
10 Write a program to create a UDP server on Arduino/Raspberry Pi and respond with
humidity data to the UDP client when requested.
11 Write a program to create a TCP server on Arduino /Raspberry Pi and respond with
humidity data to the TCP client when requested.
12 Write a program on Arduino / Raspberry Pi to subscribe to the MQTT broker for
temperature data and print it.

2
Course outcomes (Course Skill Set):
At the end of the course, the student will be able to:

Interface basic input/output devices such as LEDs, buzzers, and push buttons with
CO1
Arduino/Raspberry Pi and implement control logic through programming.
Interface analog and digital sensors (e.g., IR, LDR, DHT11, Ultrasonic, Soil Moisture) for real-
CO2
time data acquisition
Integrate control display units and actuators (OLED, motors via relay) to visualize sensor data and
CO3
automate responses to environmental changes.
Implement IoT communication protocols to transmit sensor data using cloud platforms
CO4
(ThingSpeak), messaging services (Telegram), and network communication (MQTT, TCP, UDP).

Introduction to Arduino UNO


Arduino Uno is an open-source hardware development board designed by Arduino company and
user community that designs and manufactures single-board microcontrollers and microcontroller
kits for building digital devices.
Arduino has Development board and IDE(integrated development environment).
Arduino Uno development board is an 8-bit microcontroller embedded in a single board. Arduino
Uno Board looks likes as bellow image

Arduino UNO hardware specifica on

Microcontroller ATmega328P – 8 bit AVR Family Microcontroller

Operating Voltage 5V

input voltage limit 7.12V

3
analog input pins 6-20V

recommended input voltage 6(A0-A5)

digital I/O pins 14 (0-13)

DC current on I/O pins 40 mA

DC Current on 3.3v pin 50 mA

Flash Memory 32 kb

SRAM 2 KB

EEPROM 1 KB

Frequency 16 MHz

Arduino Uno Pin Diagram

Arduino Uno Pins Info. Table

 The required minimum voltage is 5v.


 having 14 Digital GPIO pins and 6 analog pins.
 5v and 3.3v power pins with 3 ground pins onboard.
 Another SMD microcontroller inbuilt for boot the Arduino main chip.
 there is also two voltage regulator one is for 5v and another is for 3.3v.
 for SPI protocol there is MISO, MOSI, SCK, and SS pin which is pin 12, pin 11, pin 13
and pin 10 respectively.
 for I2C protocol there are SCL and SDA pins above the pin 13 & Vref.

4
 serial communication by the pin Rx & Tx Which are given at pin 1 & pin 2.

 There are also some PWM pins on the board you can see all the detail in the given diagram.
There is a 5v regulator which helps to convert the high voltage to the 5v. so that the. 5 volt only
goes to. the main controller and other components.

There is a dc port in the Arduino, where we can connect the dc voltage from 5v to 12 voltage. if
there is more than 12 voltage. the regulator ic inside the arduino board will convert the voltage to
5v. this will save our Arduino.
There is one more 3.3 volt regulator ic. which convert the 5v to 3.3 voltage. this is for a external
pin given by the arduino. on this pin arduino gives 3.3 v. there is many sensors available which
only can works on 3.3 voltage for example OLED display and RFID module.

There is Vin pin given at the arduino power port nearly gnd. this is given to provide vin to the
Arduino if you don’t have dc pin for dc port you can given power to the arduino by using this Vin
pin. but always make sure voltage not more than the 5v. because across the Vin there is no regulator
ic or any to protect the Arduino.
Direct given power more than 5v may cause damage to the microcontroller and other internal
articitectiure.

Arduino Uno pin descrip ons

Pin Category Pin Name Detail

Vin: Input voltage to Arduino when given external Voltage


Vin, 3.3v, 5v, 5v: 5v pin of Arduino from where you can connect sensors
Power
Gnd 3.3v : 3.3v given by the Arduino using regulator Ic
Gnd : Ground Pin

Reset Reset Pin To Reset thee micro controller

A0,A1,A2,A
Analog Pin to receive the analog Data
3,A4,A5,A6

Input/
0-13 0-13 digital input output pins
Output pins

Serial Rx, Tx to start the serial communication using UART

Inbuild LED 13 to indicate and check the program

5
Arduino IDE installa,on guide

1: goto to website h.ps://www.arduino.cc/en/so2ware/

Enter email and click on just download

Once download is complete , double click complete installation


Open Arduino ide by double clicking Arduino ide icon on desktop

6
Arduino ide will open

Check by open sample program. Go to file -> examples -> Basic -> Blink

7
Select Arduino UNO board

Select port name

Video Tutorial link : https://www.youtube.com/playlist?list=PLxzuVaJG716s6JgJsx-


Os8Mjqa-rTbfsv

8
EXPERIMENT – 1(a)
i. To interface LED/Buzzer with Arduino/Raspberry Pi and write a program to
turn ON LED for 1 sec after every 2 seconds.

AIM: Write a program to turn ON LED/ Buzzer for 1 sec after every 2 seconds with
Arduino/ Raspberry Pi.

COMPONENTS REQUIRED:

1. Arduino UNO/ Raspberry Pi.


2. LED/ Buzzer.
3. Resistor (220Ω)
4. Connecting cable or USB cable.
5. Breadboard.
6. Jumper wires.

CONNECTION DIAGRAM:

Code:
const int LED=13; //built in led connected to pin 13
void setup()
{
pinMode(LED, OUTPUT); // initialize digital pin 13 as an output.
}
void loop()
{
digitalWrite(LED, HIGH);
delay(1000); // wait for 1000ms i.e 1sec
digitalWrite(LED, LOW); // turn off LED by making the voltage LOW
delay(2000); // wait for a two seconds 2000ms
}

Video Tutorial Link : https://youtu.be/e328by9sgOg

9
To Control Buzzer, connect Buzzer as shown in diagram

const int buzzer=13; // buzzer


void setup()
{
pinMode(buzzer, OUTPUT); // initialize digital pin 13 as an output.
}
void loop()
{
digitalWrite(buzzer, HIGH); // turn the buzzer on (HIGH is the
voltage level)
delay(1000); // wait for 1000ms i.e 1sec
digitalWrite(buzzer, LOW); // turn the buzzer off by making the
voltage LOW
delay(2000); // wait for a two seconds
}

RESULT: LED/Buzzer is successfully controlled by Arduino UNO Board

Video Tutorial Link: https://youtu.be/oRjVMuzAjpE

10
1.ii. To interface Push button/Digital sensor (IR/LDR) with Arduino UNO and
write a program to turn ON LED when push button is pressed or at sensor
detection.

AIM: Write a program to turn ON LED when push button is pressed using Arduino UNO.
COMPONENTS REQUIRED:

1. Arduino UNO.
2. Push button.
3. LED.
4. Resistor (1KΩ)
5. Connecting cable or USB cable.
6. Breadboard.
7. Jumper wires.

CONNECTION DIAGRAM

const int buttonPin = 4;


int ledPin = 13; // the number of the LED pin
int buttonState = 0; // variable for reading the pushbutton status
void setup()
{
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}
void loop()
{
buttonState = digitalRead(buttonPin); //read the state of the pushbutton value
if (buttonState == HIGH)
{
digitalWrite(ledPin, HIGH); // turn LED ON
}

11
else
{
digitalWrite(ledPin, LOW); // turn built in LED off:
}
}

RESULT: Controlling LED by pressing push button using Arduino UNO.

Video Tutorial link: https://youtu.be/FxIfvESKsFg

12
AIM: Write a program to turn ON LED at sensor (IR) detection using Arduino UNO.

COMPONENTS REQUIRED:

1. Arduino UNO.
2. IR.
3. LED.
4. Resistor (220Ω)
5. Connecting cable or USB cable.
6. Breadboard.
7. Jumper wires.

CONNECTION DIAGRAM:

(c) IR sensor

int IR=9;

int IRvalue;

int LED=13;

void setup()

13
Serial.begin(9600);

pinMode(IR, INPUT);

pinMode(LED, OUTPUT); // LED Pin Output

void loop()

{ IRvalue=digitalRead(IR);

if (IRvalue==1)

digitalWrite(LED, HIGH); // LED High

Serial.println("Motion of Object detected");

else

digitalWrite(LED, LOW);

Serial.println("Motion not detected");

RESULT: Object detection by interfacing IR with Arduino UNO has successfully executed.

14
EXPERIMENT – 2i.
AIM: Write a program to interface DHT11 with Arduino to print temperature and humidity
readings.

COMPONENTS REQUIRED:

1. Arduino UNO/ Raspberry Pi.


2. DHT11.
3. Connecting cable or USB cable.
4. Jumper wires.

CONNECTION DIAGRAM:

DHT11 Sensor module

1 Vcc Power supply 3.5V to 5.5V

2 Data Outputs both Temperature and Humidity through serial Data

3 Ground Connected to the ground of the circuit


DHT11 Specifications
 Operating Voltage: 3.5V to 5.5V
 Operating current: 0.3mA (measuring) 60uA (standby)
 Output: Serial data
 Temperature Range: 0°C to 50°C
 Humidity Range: 20% to 90%
 Resolution: Temperature and Humidity both are 16-bit
 Accuracy: ±1°C and ±1%

15
Step 1: Install the library for DHT in Arduino IDE.
• Open Arduino IDE and navigate to Sketch > Include Library > Manage Libraries.
• Search for “DHTlib” and install the “DHTlib” library in the Arduino IDE.

#include "DHT.h"

#define DHTPIN 2
#define DHTTYPE DHT11 // for simulation use DHT22

DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
dht.begin();
}

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

Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% Temperature: ");
Serial.print(temperature);
Serial.println("°C ");
delay(2000);
}

Output in Serial monitor

Video Tutorial Link: h.ps://youtu.be/fUUoE0Bt0GU

16
2.ii. To interface OLED with Arduino and write a program to print temperature
and humidity readings on it.

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

COMPONENTS REQUIRED:

1. Arduino UNO/ Raspberry Pi.


2. DHT11.
3. (0.96 Inch) I2C/IIC 4pin OLED Display Module / I2C LCD .
4. Connecting cable or USB cable.
5. Jumper wires.

CONNECTION DIAGRAM:

Steps to interface I2C OLED with Arduino:


Step 1: Install the library for OLED display in Arduino IDE.
• Open Arduino IDE and navigate to Sketch > Include Library > Manage Libraries.

• Search for “SSD1306” and install the “SSD1306” library from Adafruit in the Arduino IDE

Step 2: Import “Adafruit_GFX.h” & “Adafruit_SSD1306.h” header files in the code.


Step 3: Connect I2C OLED display device to Arduino as per the circuit diagram.

17
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHT.h"
#define DHTPIN 6
#define DHTTYPE DHT11 // change to DHT22 for simulation
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
dht.begin();
oled.begin(SSD1306_EXTERNALVCC,0x3C);
delay(2000);
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
oled.clearDisplay();
oled.setTextSize(1.9);
oled.setTextColor(WHITE);
oled.setCursor(10,20);
oled.print("Temperature = ");
oled.println(temperature);
oled.println("");
oled.print(" Humidity = ");
oled.println(humidity);
oled.display();
delay(2000);
}
Output:

RESULT: Interfaced OLED and DHT11 with Arduino UNO and temperature and
humidity Readings printed on OLED.

Video Tutorial Link: https://youtu.be/J_8UcCe1Fw4

18
EXPERIMENT – 3

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

AIM: Write a program to turn ON motor when push button is pressed using relay with Arduino
UNO.

COMPONENTS REQUIRED:

1. Arduino UNO.
2. Relay.
3. Resistor (10kΩ).
4. Motor.
5. Connecting cable or USB cable.
6. Breadboard.
7. Jumper wires.

CONNECTION DIAGRAM:

19
int buttonstate = 0;
void setup()
{
pinMode(2, INPUT); //configure Pin 2 as input
pinMode(10, OUTPUT); //pin 10 as output
}

void loop()
{
buttonstate=digitalRead(2);
if (buttonstate == HIGH)
{digitalWrite(10,HIGH);
} else
{ digitalWrite(10, LOW);
}
delay(1000);
}

Result: Motor runs when push bu.on is pressed and stops when pushbu.on is released.

Video Tutorial Link : h.ps://youtu.be/FxIfvESKsFg

20
EXPERIMENT – 4(a)

AIM: Write an Arduino program to interface the Soil Moisture Sensor.

COMPONENTS REQUIRED:

1. Arduino UNO.
2. Soil Moisture Sensor.
3. Connecting cable or USB cable.
4. Breadboard.
5. Jumper wires.

CONNECTION DIAGRAM:

21
Soil moisture sensors work by measuring the resistance or capacitance of the soil, which is
affected by its moisture content. Resis,ve sensors measure the change in electrical resistance as
the soil becomes we.er or drier.

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);
Serial.println(sensor_analog);
moisture_percentage = (sensor_analog/876.00)*100 ;
Serial.print("Moisture Percentage = ");
Serial.print(moisture_percentage);
Serial.print("%\n\n");
delay(1000);
}

Result: Soil sensor interfaced with Arduino and Moisture value printed on serial monitor
window.

Video Tutorial Link: h.ps://youtu.be/PtKzAh1txT0

22
EXPERIMENT – 4(b)
AIM: AIM: Write a program to turn ON LED at sensor (LDR) detection using Arduino UNO.

COMPONENTS REQUIRED:

1. Arduino UNO.
2. LDR.
3. LED.
4. Resistor (1KΩ)
5. Connecting cable or USB cable.
6. Breadboard.
7. Jumper wires.

CONNECTION DIAGRAM:

const int ledPin = 10;


const int ldrPin = A0;
void setup() {

Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
}

void loop()

23
{
int ldrStatus = analogRead(ldrPin);
Serial.print("ldr sensor value =");
Serial.println(ldrStatus);

if (ldrStatus <=300)
{
digitalWrite(ledPin, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
}
delay(2000);
}

RESULT: Controlling LED by interfacing LDR with Arduino UNO has successfully executed.

Video Tutorial Link : h.ps://youtu.be/7Mg4WhjyLzg

24
EXPERIMENT – 5

AIM: Write a program to interface an Ultrasonic Sensor with Arduino UNO.

COMPONENTS REQUIRED:

1. Arduino UNO.
2. Ultrasonis Sensor.
3. Connecting cable or USB cable.
4. Breadboard.
5. Jumper wires.

CONNECTION DIAGRAM:

The HC-SR04 is an affordable and easy to use distance measuring sensor which has a range from
2cm to 400cm (about an inch to 13 feet).

25
The sensor is composed of two ultrasonic transducers. One is
transmitter which outputs ultrasonic sound pulses and the other
is receiver which listens for reflected waves. It’s basically
a SONAR which is used in submarines for detecting
underwater objects.
The sensor has 4 pins. VCC and GND go to 5V and GND pins
on the Arduino, and the Trig and Echo go to any digital
Arduino pin. Using the Trig pin we send the ultrasound wave from the transmitter, and with
the Echo pin we listen for the reflected signal.

int trigPin = 10;


int echoPin = 9;
long time;
float distance;

void setup()
{
pinMode(trigPin, OUTPUT); // SETTING OUTPUT PIN
pinMode(echoPin, INPUT); // SETTING INPUT PIN
Serial.begin(9600); // INITIALISING THE COMMUNICATION
}

void loop()
{
digitalWrite(trigPin,LOW);
delayMicroseconds(2);

// transmitting sound for 10 microseconds


digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(10, LOW);

// calculating distance and printing on serial monitor


time=pulseIn(echoPin , HIGH);
distance = time * 0.0343/2;
Serial.print("Distance:");

26
Serial.print(distance);
Serial.println("cm");
delay(2000);
}

Result: Ultrasonic sensor interfaced with Arduino and Distance measured and printed on
serial window

Video Tutorial link: https://youtu.be/Ul1RSYiFyaQ

27
EXPERIMENT – 6

AIM: Write a program on ESP8266 to upload temperature and humidity value using DHT11
sensor to Thingspeak cloud.

COMPONENTS REQUIRED:

1. ESP8266.
2. DHT11.
3. Connecting cable or USB cable.
4. Breadboard.
5. Jumper wires.

CONNECTION DIAGRAM:

install required libraries.


Go to menu Sketch >> Include Library >> Manage Library
Install DHT sensor library for ESPx by beegee library.
Install ThingSpeak library by MathsWorks

28
ThingSpeak Account creation :

Click on any of above two links

Create your account by typing your mail id and login using exis,ng gmail id.

29
And sign in

Click on New Channel


Give channel name and descrip,on
Field 1 nad Field 2 details update as shown below

Note down Write API Key by clicking on API keys

30
#include <DHT.h>
#include <ThingSpeak.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <Adafruit_Sensor.h>
#define DHTPIN D2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "iot";
const char* password = "project1234";
WiFiClient client;
unsigned long myChannelNumber = 2863470;
const char * myWriteAPIKey = "VG6F0WPBOUH2DGPI";
uint8_t temperature, humidity;
void setup()
{
Serial.begin(9600);
dht.begin();
delay(10);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Print the IP address
Serial.println(WiFi.localIP());
ThingSpeak.begin(client);
}
void loop()
{
temperature = dht.readTemperature();
humidity = dht.readHumidity();
Serial.print("Temperature Value is :");
Serial.print(temperature);
Serial.println("C");
Serial.print("Humidity Value is :");
Serial.print(humidity);
Serial.println("%");
ThingSpeak.writeField(myChannelNumber, 1, temperature, myWriteAPIKey);
ThingSpeak.writeField(myChannelNumber, 2, humidity, myWriteAPIKey);
delay(3000); // ThingSpeak will only accept updates every 3 seconds.

31
}

Result:

Result :Uploading of temperature and humidity data by DHT11 sensor to Thingspeak cloud
and verified.

Video Tutorial Link : https://youtu.be/Wn9oVPJtC6Q

32
EXPERIMENT – 7
AIM: Write a program on ESP32 to retrieve temperature and humidity values using
DHT11 sensor from Thingspeak cloud.

COMPONENTS REQUIRED:
1. ESP32.
2. Connecting cable or USB cable.

CONNECTION DIAGRAM:

#include <ESP8266WiFi.h>
#include <ThingSpeak.h>
WiFiClient client;
void setup()
{
Serial.begin(9600);
ThingSpeak.begin(client);
WiFi.disconnect();
delay(3000);
Serial.println("START");
WiFi.begin("iot","project1234");
while ((!(WiFi.status() == WL_CONNECTED))){
delay(300);
Serial.print("..");
}
Serial.println("Your IP is");

33
Serial.println((WiFi.localIP().toString()));
Serial.println("Connected");

}
void loop()
{
Serial.print("Temperature=");
Serial.println((ThingSpeak.readIntField(2863470,1,"EZ6WW2HWXOJ04F9Q")));
Serial.print("Humidity=");
Serial.println((ThingSpeak.readIntField(2863470,2,"EZ6WW2HWXOJ04F9Q")));
delay(3000);
}

Output verified in Serial Monitor

Video Tutorial Link : h.ps://youtu.be/MiCCoXDYQx0

34
EXPERIMENT – 8
Write a program to interface LED using Telegram App.

Telegram Messenger is a cloud-based instant messaging and voice over IP service. You can easily
install it in your smartphone (Android and iPhone) or computer (PC, Mac and Linux). It is free
and without any ads. Telegram allows you to create bots that you can interact with. “Bots are
third-party applications that run inside Telegram. Users can interact with bots by sending them
messages, commands and inline requests. The ESP32/ESP8266 will interact with the Telegram
bot to receive and handle the messages, and send responses.

Creating a Telegram Bot


Go to Google Play or App Store, download and install Telegram.

Open Telegram and follow the next steps to create a Telegram Bot. First, search for “botfather”
and click the BotFather as shown below. Or open this link t.me/botfather in your smartphone.

The following window should open and you’ll be prompted to click the start button.

35
If your bot is successfully created, you’ll receive a message with a link to access the bot and

the bot token. Save the bot token because you’ll need it so that the ESP32/ESP8266 can
interact with the bot.

open this link t.me/myidbot in your smartphone. Copy HTTP API key
and send it to mail or whatsapp. You have to paste in program code.
To interact with the Telegram bot, we’ll use the Universal Telegram Bot
Library

1. Go to Skech > Include Library > Manage Libraries.


2. Search for “Universal Telegram Bot Library” and install it
3. Search for “ArduinoJson”. And install it
he ESP8266 built-in LED is typically connected to GPIO2 (D4), also
known as pin 2 on the ESP8266 module.

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h> // Updated library for Telegram

//#define LED 5 // GPIO5 (D1 on NodeMCU)

36
const char* ssid = "hotspotname";
const char* password = "hotspotpassword";
const char* botToken = "7895865592:AAE7qsCNwMk8FcWa9uNtFSou7wJW-kiFJH8";

WiFiClientSecure client;
UniversalTelegramBot bot(botToken, client);
void setup() {
Serial.begin(115200);
delay(3000);
Serial.print("Connecting to WiFi: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}

Serial.println("\nWiFi connected!");
// Important: Allow insecure connection for Telegram API
client.setInsecure();
bot.sendMessage("5117743946", "ESP8266 Telegram Bot Started!", "");
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH); // Ensure LED is OFF at startup
}

void loop() {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages) {
for (int i = 0; i < numNewMessages; i++) {
String chat_id = bot.messages[i].chat_id;
String text = bot.messages[i].text;

Serial.println("Message received: " + text);

if (text.equalsIgnoreCase("on")) {
digitalWrite(LED_BUILTIN, LOW); // Turn LED ON
bot.sendMessage(chat_id, "LED is ON ", "");

37
Serial.println("LED turned ON");
}
else if (text.equalsIgnoreCase("off")) {
digitalWrite(LED_BUILTIN, HIGH); // Turn LED OFF
bot.sendMessage(chat_id, "LED is OFF ", "");
Serial.println("LED turned OFF");
}
else {
bot.sendMessage(chat_id, "Invalid command! Use 'on' or 'off'.", "");
}
}
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
}

38
EXPERIMENT - 9
Write a program on Arduino/Raspberry Pi to publish temperature data to MQTT broker.
AIM: Write a program on ESP8266 to publish temperature and humidity values using
DHT11 sensor to MQTT broker.

COMPONENTS REQUIRED:

1. ESP8266.
2. DHT11.
3. Connecting cable or USB cable.
4. Breadboard.
5. Jumper wires.

CONNECTION DIAGRAM:

 MQTT, or Message Queue Telemetry Transport, is a protocol for device communication


that Adafruit IO supports. Using a MQTT library or client you can publish and subscribe
to a feed to send and receive feed data.Mosquitto
A lightweight, open-source MQTT broker, suitable for small to medium-sized applications.
How an MQTT Broker Works:
1. MQTT clients connect to the broker.
2. Publishers publish messages to specific topics.

39
3. The broker receives the messages and filters them based on the topic.
4. The broker forwards the messages to subscribers who have subscribed to the relevant topic.
5. Subscribers receive the messages.
details to connect a MQTT client to Adafruit IO:
 Host: io.adafruit.com
 Port: 1883 or 8883 (for SSL encrypted connection)
 Username: your Adafruit account username (see the accounts.adafruit.com page here to
find yours)
 Password: your Adafruit IO key (click the AIO Key button on a dashboard to find the key)
CREATE account in io.adafruit.com and click on sign in

After creation of account, login

40
Click on Dash boards  New dashboard
Give name for it and click create

Click on create new block , select guage block

Enter values and click create block. Simillarly one more block with name Humidity
block to be created

41
#include <SimpleDHT.h>
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define WLAN_SSID "iot" //your hotspot name
#define WLAN_PASS "project1234" //hotspot password
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "raghunathbh" //replace with your Adafruitio username
#define AIO_KEY "aio_jJGy6271gfYdTRcbRWLxP02kTZW7" // key
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
Adafruit_MQTT_Publish Temperature = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Temperature");
Adafruit_MQTT_Publish Humidity = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Humidity");
int pinDHT11 = 0; //D3 pin
SimpleDHT11 dht11(pinDHT11);
byte hum = 0; //Stores humidity value
byte temp = 0; //Stores temperature value
void setup() {
Serial.begin(115200);
Serial.println(F("Adafruit IO Example"));
Serial.println();
Serial.println();
delay(10);
Serial.print(F("Connecting to .. "));
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
}
Serial.println();
Serial.println(F("WiFi connected"));
Serial.println(F("IP address: "));
Serial.println(WiFi.localIP());
connect();
}
void connect() {
Serial.print(F("Connecting to Adafruit IO... "));
int8_t ret;
while ((ret = mqtt.connect()) != 0) {
switch (ret) {
case 1: Serial.println(F("Wrong protocol")); break;
case 2: Serial.println(F("ID rejected")); break;
case 3: Serial.println(F("Server unavail")); break;
case 4: Serial.println(F("Bad user/pass")); break;
case 5: Serial.println(F("Not authed")); break;
case 6: Serial.println(F("Failed to subscribe")); break;
default: Serial.println(F("Connection failed")); break;
}

if(ret >= 0)
mqtt.disconnect();

42
Serial.println(F("Retrying connection..."));
delay(10000);
}
Serial.println(F("Adafruit IO Connected!"));
}

void loop() {
// ping adafruit io a few times to make sure we remain connected
if(! mqtt.ping(3)) {
// reconnect to adafruit io
if(! mqtt.connected())
connect();
}
dht11.read(&temp, &hum, NULL);
Serial.print((int)temp);
Serial.print(" *C, ");
Serial.print((int)hum);
Serial.println(" H");
delay(5000);

if (! Temperature.publish(temp))
{
Serial.println(F("Failed"));
}
if (! Humidity.publish(hum))
{
Serial.println(F("Failed"));
}
else {
Serial.println(F("Sent!"));
}
}

RESULT: Published temperature and humidity data to MQTT broker with ESP32
has successfully executed

43
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 NodeMCU (ESP8266) and respond
with humidity data to UDP client when requested.

COMPONENTS REQUIRED:

1. NodeMCU (ESP8266).
2. DHT11.
3. Connecting cable or USB cable.
4. Breadboard.
5. Jumper wires.

CONNECTION DIAGRAM:

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

// Replace with your network credentials


const char* ssid = "iot";
const char* password = "project1234";

// UDP Settings

44
WiFiUDP Udp;
unsigned int localUdpPort = 4210; // Port to listen on
char incomingPacket[255]; // buffer for incoming packets

// DHT Sensor settings


#define DHTPIN D4 // Connect your DHT sensor data pin to D4
#define DHTTYPE DHT11 // or DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(115200);
delay(1000);

// Connect to Wi-Fi
Serial.printf("Connecting to %s...\n", ssid);
WiFi.begin(ssid, password);

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


delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

// Start UDP
Udp.begin(localUdpPort);
Serial.printf("UDP server started on port %d\n", localUdpPort);

// Initialize DHT sensor


dht.begin();
}

void loop() {
int packetSize = Udp.parsePacket();
if (packetSize) {
// Receive incoming UDP packet
int len = Udp.read(incomingPacket, 255);
if (len > 0) {
incomingPacket[len] = '\0'; // Null-terminate the string
}
Serial.printf("Received packet: %s\n", incomingPacket);

// If the request is "humidity", respond with humidity value


if (String(incomingPacket) == "humidity") {
float humidity = dht.readHumidity();
if (isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");

45
humidity = -1; // Error code
}

// Send response
String response = String(humidity) + "%";
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(response.c_str());
Udp.endPacket();

Serial.printf("Sent response: %s\n", response.c_str());


}
}
}

download Packet sender and set following ASCII = humidity

RESULT: Received humidity data to UDP client from UDP server on NodeMCU (ESP8266)
has successfully executed

46
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 NodeMCU (ESP8266) and respond
with humidity data to TCP client when requested.

COMPONENTS REQUIRED:

1. NodeMCU (ESP8266).
2. DHT11.
3. Connecting cable or USB cable.
4. Breadboard.
5. Jumper wires.

CONNECTION DIAGRAM:

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

// Replace with your network credentials


const char* ssid = "hotspotname";
const char* password = "hotspotpassword";

// TCP Server Settings


WiFiServer server(4210); // Create a TCP server on port 4210

// DHT Sensor settings


#define DHTPIN D4 // Connect DHT data pin to D4 (GPIO2)

47
#define DHTTYPE DHT11 // or use DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(115200);
delay(1000);

// Connect to WiFi
Serial.printf("Connecting to %s...\n", ssid);
WiFi.begin(ssid, password);

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


delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

// Start TCP Server


server.begin();
Serial.println("TCP server started");

// Initialize DHT sensor


dht.begin();
}

void loop() {
WiFiClient client = server.available(); // Listen for incoming clients

if (client) {
Serial.println("Client connected");
String request = "";
unsigned long timeout = millis(); // timeout in case client gets stuck

while (client.connected()) {
if (client.available()) {
char c = client.read();
request += c;

// Process as soon as "humidity" keyword is detected


if (request.indexOf("humidity") != -1) {
Serial.print("Received request: ");
Serial.println(request);

float humidity = dht.readHumidity();


if (isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
humidity = -1; // Error code
}

String response = String(humidity) + "%\n";


client.print(response);
Serial.print("Sent response: ");
Serial.println(response);

48
break; // after responding, break the inner loop
}
}

// Timeout if client doesn't send valid data in 5 seconds


if (millis() - timeout > 5000) {
Serial.println("Client timeout, disconnecting");
break;
}
}

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

Output on Serial Monitor

RESULT: Received humidity data to TCP client from TCP server on NodeMCU

49
EXPERIMENT – 12
AIM: Write a program on Arduino to subscribe to the MQTT broker for temperature data and
print it.
#include <SimpleDHT.h>
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define WIFI_SSID "hotspotname"
#define WIFI_PASS "hotspotpassword"
#define ADAFRUIT_SERVER "io.adafruit.com"
#define ADAFRUIT_PORT 1883
#define ADAFRUIT_USERNAME "adafruitid"
#define ADAFRUIT_KEY "your key"
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, ADAFRUIT_SERVER,ADAFRUIT_PORT,ADAFRUIT_USERNAME, ADAFRUIT_USERNAME, ADAFRUIT_KEY);
Adafruit_MQTT_Subscribe Temperature = Adafruit_MQTT_Subscribe (&mqtt, ADAFRUIT_USERNAME "/feeds/Temperature");

void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected())
{
return;
}
Serial.print("Connecting to MQTT... ");
while ((ret = mqtt.connect()) != 0) {
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
}

Serial.println("MQTT Connected!");
}

void setup() {
Serial.begin(115200);
delay(10);

50
// Connect to Wi-Fi
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);

WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP Address: ");
Serial.println(WiFi.localIP());

mqtt.subscribe(&Temperature);
}

void loop() {
MQTT_connect();
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(5000)))
{
if (subscription == &Temperature)
{
Serial.print(F("Received temperature value is: "));
Serial.println((char *)Temperature.lastread);
}
}
}

Output On Serial Monitor . Add data in io.adafruit.com & select


feedstemperature
You Can retrieve Data from MQTT which uploaded instantly. Once data is uploaded
, immediately Data will be retrieved.

51
Video Tutorial link: https://youtu.be/XDUn6oFTM4k
ESP 8266 NodeMCU

 802.11 b/g/n
• Integrated low power 32-bit MCU
• Typical frequency of 80MHz
• SRAM- 160 Kbytes
• SPI Flash, up to 16 MBytes
• Integrated 10-bit ADC
• Integrated TCP/IP protocol stack

• SDIO (Secure Digital Input Output) 2.0, (H) SPI, UART, I2C, I2S (Inter IC
Sound), IRDA(Infrared Data Association), PWM, GPIO
• Supports antenna diversity
• Integrated PLL, regulators, and power management unit
• Wi-Fi 2.4 GHz, support WPA(Wi-Fi Protected Access)/WPA2
• Support STA( Station) /AP ( Access point) /STA+AP operation modes
• Operating temperature range -40C ~ 125C

How to Use Arduino IDE to Program nodeMCU

1. Start Arduino IDE and open Preferences window from File


2. Enter http://arduino.esp8266.com/stable/package_esp8266com_index.json
Into Additional Board Manager URLs field

52
Open Boards Manager from Tools > Board menu and find esp8266 platform

53
54
IoT Lab Viva Questions with Answers

Q1: What is the purpose of `delay()` in Arduino?


A1: It pauses the program for the specified time in milliseconds.

Q2: How do you connect an LED or buzzer to a GPIO pin?


A2: Anode to GPIO through a resistor, cathode to GND.

Q3: What are the voltage and current requirements for an LED?
A3: Typically 2V and 20mA.

Q4: How does timing control work in microcontroller programming?


A4: By using functions like delay or timers.

Q5: What are the differences between digitalWrite and analogWrite?


A5: digitalWrite sets HIGH or LOW, analogWrite sets PWM output.

Q6: How do you read the status of a push button in Arduino?


A6: Using digitalRead on the GPIO pin.

Q7: What is an IR sensor and how does it detect objects?


A7: It uses infrared light to detect object reflection.

Q8: What is an LDR and how does it vary with light intensity?
A8: A light-dependent resistor; its resistance decreases with more light.

Q9: What kind of signal do LDRs or IR sensors produce?


A9: Analog signal for LDR, digital/analog for IR sensor.

Q10: What is pull-up and pull-down configuration?


A10: Used to ensure a known voltage level when input is not active.

Q11: What type of sensor is DHT11?


A11: A digital temperature and humidity sensor.

Q12: What are the typical operating ranges of DHT11?


A12: 0-50-C for temperature and 20-90% for humidity.

Q13: What library is used to interface DHT11 in Arduino?


A13: The 'DHT' library by Adafruit.

Q14: How often can DHT11 be polled for new readings?


A14: Once every 1 second.

Q15: What is the data format returned by the DHT11 sensor?


A15: Digital data sent as a series of bytes.

Q16: What is an OLED display?


A16: A display made of organic LEDs that emit light individually.

Q17: Which communication protocol is used by OLED?


A17: I2C or SPI.

Q18: How do you interface an OLED display with a microcontroller?


A18: Connect SDA, SCL, GND, and VCC pins appropriately.

55
Q19: What library do we use to control OLED on Arduino?
A19: Adafruit SSD1306 or U8g2 library.

Q20: How do you print temperature and humidity values on the OLED?
A20: Convert to string and use display.print() methods.

Q21: What is the function of a relay?


A21: It acts as a switch controlled by a low-power signal.

Q22: How do you control a motor using a relay with Arduino?


A22: Connect relay input to GPIO and motor to relay output.

Q23: What is NO and NC in a relay?


A23: Normally Open and Normally Closed contacts.

Q24: Why is a flyback diode used?


A24: To protect the circuit from voltage spikes from inductive loads.

Q25: What precautions should be taken with high-power devices?


A25: Use isolation and ensure current ratings are met.

Q26: How does a soil moisture sensor work?


A26: It measures conductivity or capacitance in the soil.

Q27: What type of signal does it output?


A27: Analog or digital depending on the model.

Q28: Use of soil moisture sensor in agriculture?


A28: Automated irrigation systems.

Q29: Difference: capacitive vs resistive sensor?


A29: Capacitive is more durable and accurate.

Q30: How to calibrate it?


A30: Compare with actual soil moisture and adjust thresholds.

Q31: What does an LDR do?


A31: Changes resistance based on light intensity.

Q32: How to use LDR on Arduino?


A32: Connect in a voltage divider and read analog input.

Q33: Use case of LDR in IoT?


A33: Automatic lighting systems.

Q34: How to use LDR with Raspberry Pi?


A34: Use ADC like MCP3008 as Pi lacks analog input.

Q35: Can LDR detect motion?


A35: No, it's for light intensity detection.

Q36: How does an ultrasonic sensor work?


A36: Sends sound wave and measures reflection time.

Q37: What is the function of TRIG and ECHO?


A37: TRIG sends pulse, ECHO receives it.

56
Q38: How to calculate distance?
A38: Distance = Time * Speed of Sound / 2.

Q39: Max range of HC-SR04?


A39: Up to 4 meters.

Q40: What affects ultrasonic accuracy?


A40: Obstacles, angle, and environmental conditions.

Q41: What is ThingSpeak?


A41: A cloud platform for IoT data storage and visualization.

Q42: How to send data to ThingSpeak?


A42: Using HTTP GET requests with API key.

Q43: What are API keys?


A43: Authentication tokens to access or update data.

Q44: How to connect Arduino to internet?


A44: Using WiFi module like ESP8266.

Q45: How often can you send data to ThingSpeak?


A45: Once every 15 seconds (free account).

Q46: How to retrieve data from ThingSpeak?


A46: Use HTTP GET request with channel ID and API key.

Q47: Function for HTTP GET in Arduino?


A47: Use WiFiClient and HTTPClient libraries.

Q48: Data format from ThingSpeak?


A48: JSON or XML.

Q49: What is a channel ID?


A49: Unique ID for each data channel.

Q50: How to parse JSON in Arduino?


A50: Using ArduinoJson library.

Q51: How to use Telegram with IoT?


A51: Using a bot and Bot Token for communication.

Q52: How does the bot receive messages?


A52: Through Telegram Bot API.

Q53: What is a chat ID?


A53: Unique ID representing user or group chat.

Q54: How to control LED with message?


A54: Parse message and trigger digitalWrite.

Q55: Is Telegram secure?


A55: It uses encryption but security depends on implementation.

Q56: What is MQTT?


A56: A lightweight publish-subscribe messaging protocol.

57
Q57: What is a broker?
A57: Server that handles message distribution.

Q58: How to publish data in MQTT?


A58: Use MQTT client and call publish function.

Q59: Popular MQTT brokers?


A59: Mosquitto, HiveMQ, Adafruit IO.

Q60: Use of MQTT in IoT?


A60: Efficient data exchange with low overhead.

Q61: What is UDP?


A61: Connectionless communication protocol.

Q62: How to create UDP server?


A62: Bind socket to port and listen for datagrams.

Q63: When to use UDP in IoT?


A63: When speed is more important than reliability.

Q64: Is UDP reliable?


A64: No, it does not guarantee delivery.

Q65: Why use UDP for sensors?


A65: For fast, lightweight data transfer.

Q66: What is TCP?


A66: Connection-oriented protocol for reliable communication.

Q67: How to create TCP server?


A67: Listen on a port and accept incoming connections.

Q68: Difference between TCP and UDP?


A68: TCP is reliable, UDP is faster.

Q69: How to send humidity on request?


A69: Read sensor and write to client socket.

Q70: What library is used for TCP in Arduino?


A70: WiFiServer or EthernetServer.

Q71: How to subscribe to MQTT?


A71: Call subscribe() with topic name.

Q72: What happens when new data is published?


A72: Client callback function is triggered.

Q73: Can a client publish and subscribe at once?


A73: Yes, it's common in IoT systems.

Q74: How to print received temperature?


A74: Use message callback and Serial.print().

Q75: Why is MQTT efficient?


A75: Low bandwidth usage and fast delivery.

58

You might also like