BEC657C Internet of Things Lab Manual by Raghunath VTU
BEC657C Internet of Things Lab Manual by Raghunath VTU
LAB MANUAL
Programme (UG/PG) : UG
Year / Semester : VI
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
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).
Operating Voltage 5V
3
analog input pins 6-20V
Flash Memory 32 kb
SRAM 2 KB
EEPROM 1 KB
Frequency 16 MHz
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.
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
5
Arduino IDE installa,on guide
6
Arduino ide will open
Check by open sample program. Go to file -> examples -> Basic -> Blink
7
Select Arduino UNO board
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:
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
}
9
To Control Buzzer, connect Buzzer as shown in diagram
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
11
else
{
digitalWrite(ledPin, LOW); // turn built in LED off:
}
}
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);
void loop()
{ IRvalue=digitalRead(IR);
if (IRvalue==1)
else
digitalWrite(LED, LOW);
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:
CONNECTION DIAGRAM:
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
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);
}
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:
CONNECTION DIAGRAM:
• Search for “SSD1306” and install the “SSD1306” library from Adafruit in the Arduino IDE
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.
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.
20
EXPERIMENT – 4(a)
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.
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.
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:
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.
24
EXPERIMENT – 5
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.
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);
26
Serial.print(distance);
Serial.println("cm");
delay(2000);
}
Result: Ultrasonic sensor interfaced with Arduino and Distance measured and printed on
serial window
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:
28
ThingSpeak Account creation :
Create your account by typing your mail id and login using exis,ng gmail id.
29
And sign in
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.
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);
}
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.
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
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h> // Updated library for Telegram
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;
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:
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
40
Click on Dash boards New dashboard
Give name for it and click create
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
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>
// UDP Settings
44
WiFiUDP Udp;
unsigned int localUdpPort = 4210; // Port to listen on
char incomingPacket[255]; // buffer for incoming packets
void setup() {
Serial.begin(115200);
delay(1000);
// Connect to Wi-Fi
Serial.printf("Connecting to %s...\n", ssid);
WiFi.begin(ssid, password);
// Start UDP
Udp.begin(localUdpPort);
Serial.printf("UDP server started on port %d\n", localUdpPort);
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);
45
humidity = -1; // Error code
}
// Send response
String response = String(humidity) + "%";
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(response.c_str());
Udp.endPacket();
RESULT: Received humidity data to UDP client from UDP server on NodeMCU (ESP8266)
has successfully executed
46
EXPERIMENT – 11
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>
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);
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;
48
break; // after responding, break the inner loop
}
}
client.stop();
Serial.println("Client disconnected");
}
}
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);
}
}
}
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
52
Open Boards Manager from Tools > Board menu and find esp8266 platform
53
54
IoT Lab Viva Questions with Answers
Q3: What are the voltage and current requirements for an LED?
A3: Typically 2V and 20mA.
Q8: What is an LDR and how does it vary with light intensity?
A8: A light-dependent resistor; its resistance decreases with more light.
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.
56
Q38: How to calculate distance?
A38: Distance = Time * Speed of Sound / 2.
57
Q57: What is a broker?
A57: Server that handles message distribution.
58