Internet of Things Lab
Course Code 22ADL682 CIE Marks 50
Number Lecture Hour/Week L T P TOTAL SEE Marks 50
0 0 2 2
Number of Lecture Hours 30 Exam Hours 03
Credits-01
Course Objectives: This course will enable students to
Gain foundational knowledge of Arduino and Raspberry Pi platforms, including their architecture,
programming environment, and basic functionalities.
Learn to interface various sensors with microcontrollers to collect and process environmental data.
Create visual representations of sensor data using OLED displays and 7-segment displays.
Implement the following problem statements
1. (a)To interface LED/Buzzer with Arduino/Raspberry Pi and write a program to ‘turn ON’ LED for 1
sec after every 2 seconds.
(b) 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. (a) To interface DHT11 sensor with Arduino/Raspberry Pi and write a program to print temperature
and humidity readings.
(b) 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 Light sensor to Arduino/Raspberry Pi and write a program to print Light sensor readings.
5. Write a program on Arduino/Raspberry Pi to upload temperature and humidity data to thingspeak
cloud.
6. Write a program on Arduino/Raspberry Pi to retrieve temperature and humidity data from thingspeak
cloud.
7. Write a program on Arduino/Raspberry Pi to publish temperature data to MQTT broker.
8. To interface Smart gas leakage email alert using things Speak.
9. Write a program on Arduino/Raspberry Pi to Weather display system using DHT11 and LCD.
10. Object distance display using 7-segment display and Ultrasonic sensor & read the sensor data when
specified key is pressed.
1. Getting started with raspberry Pi and ESP32, connecting to PC monitor & initial
setup.
a) To interface LED/Buzzer with Arduino/Raspberry Pi and write a program to ‘turn
ON’ LED for 1 sec after every 2 seconds.
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(2000); // wait for a two second
}
OUTPUT
b) 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.
#define LED 13
#define BUZZER 19
bool value;
void setup() {
// put your setup code here, to run once:
pinMode(LED,INPUT);
pinMode(BUZZER,OUTPUT);
Serial.begin(9600);
}
void loop() {
value = digitalRead(LED);
if(value==0)
{
digitalWrite(BUZZER,HIGH);
Serial.println("BUTTON PRESSED,BUZZER ON");
}
else{
digitalWrite(BUZZER,LOW);
Serial.println("BUTTON not PRESSED, BUZZER OFF");
}
delay(300);
}
OUTPUT
2. a) To interface DHT11 sensor with Arduino/Raspberry Pi and write a program to
print temperature and humidity readings.
#include "DHT.h"
#define DHTPIN 4 // Digital pin connected to the Dht sensor
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22
DHT Dht(DHTPIN, DHTTYPE);
float temp = 0;
float hum = 0;
void setup() {
Serial.begin(9600);
Serial.println("Dht11 test!");
Dht.begin();
}
void loop() { // Wait a few seconds between measurements.
delay(2000);
temp = Dht.readTemperature();
hum = Dht.readHumidity();
Serial.print("Temperature : ");
Serial.println(temp);
Serial.print("Humidity: ");
Serial.println(hum);
Serial.println();
}
OUTPUT
2b) To interface OLED with Arduino/Raspberry Pi and write a program to print
temperature and humidity readings on it.
#include"DHT_U.h"
#define DHTPIN 4
#define DHTTYPE DHT11
float temp;
float hum;
DHT Dht(DHTPIN,DHTTYPE);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Dht.begin();
}
void loop() {
// put your main code here, to run repeatedly:
temp = Dht.readTemperature();
hum = Dht.readHumidity();
Serial.print(" Temperature °C: ");
Serial.println(temp);
Serial.print(" Humidity %RH: ");
Serial.println(hum);
delay(2000);
}
3. To interface motor using relay with Arduino/Raspberry Pi and write a program to
‘turn ON’ motor when push button is pressed.
#define PB 15 // Push Button connected to GPIO15
#define RELAY 2 // Relay connected to GPIO2
void setup() {
Serial.begin(9600);
pinMode(PB, INPUT); // Or use INPUT_PULLUP if wiring GND to button
pinMode(RELAY, OUTPUT);
void loop() {
int pb = digitalRead(PB); // Read the push button state
Serial.println(pb);
if (pb == LOW) { // Button pressed (LOW if wired with pull-up logic)
digitalWrite(RELAY, HIGH); // Turn ON relay
} else {
digitalWrite(RELAY, LOW); // Turn OFF relay
delay(100); // Small debounce delay
OUTPUT
Connection :
From ESP32 15th pin to push button
From ESP32 GPIO2nd pin to relay-2
4. To interface Light sensor to Arduino/Raspberry Pi and write a program to print
Light sensor readings.
#define LDR 35
int value = 0;
int lightpercentage = 0;
void setup() {
// put your setup code here, to run once:
pinMode(LDR,INPUT),
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
value = analogRead(LDR);
lightpercentage = map(value,0,4095,0,100);
Serial.print(" LIGHT INTENSITY(BRIGHTNESS) :");
Serial.println(lightpercentage);
delay(1000);
}
Output
5. Write a program on Arduino/Raspberry Pi to upload temperature and humidity
data to thingspeak cloud.
#include <WiFi.h>
#include "DHT.h"
#include "ThingSpeak.h"
#define DHTPIN 4 // GPIO4
#define DHTTYPE DHT11
char* ssid = "xyz"; // Replace with your network SSID
char* passphrase = "123456789"; // Replace with your network password
WiFiClient client;
unsigned long myChannelNumber = 2991751; // Your ThingSpeak channel number
const char* myWriteAPIKey = "5ALAN5VP03OYQCMV"; // Your ThingSpeak write API key
unsigned long lastTime = 0;
unsigned long timerDelay = 20000; // 20 seconds is ThingSpeak's minimum update interval
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
dht.begin();
WiFi.begin(ssid, passphrase);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
Serial.println("\nWiFi Connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
if ((millis() - lastTime) > timerDelay) {
float h = dht.readHumidity();
float t = dht.readTemperature(); // Celsius
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" °C\tHumidity: ");
Serial.print(h);
Serial.println(" %");
ThingSpeak.setField(1, t);
ThingSpeak.setField(2, h);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200) {
Serial.println("ThingSpeak update successful.");
} else {
Serial.print("ThingSpeak update failed. HTTP error code: ");
Serial.println(x);
}
lastTime = millis();
OUTPUT
Steps to execute the progam
1.Goto google type thingspeak cloud.
2.Login
3. Goto single sign on and give your mailid and password
4. Under Mathworks box type your mailid and password.
5. After sign up Click on Channels and click on new channel.
6. Give channel name as DHT and Select 2 fields field 1 for Temp and field2 for
Humidity and click on save channel.
7. Goto Program and copy channel id and write API Key from thingspeak.
8. Your PC should Connect to wifi.
9. Before compile the program Install 2 libraries from Arudino IDE(1.ESP32 and
thingspeak by library manager).
10. Run the program and set the serial monitor as 115200 and check the output in
thingspeak.
Connection:
DHT11 ESP32
Label Notes
Pin Pin
3.3V or DHT11 supports both; 3.3V preferred
1 VCC
5V for ESP32
2 Data GPIO4 This is defined by #define DHTPIN 4
3 GND GND Common ground
6. Write a program on Arduino/Raspberry Pi to Retrieve temperature and humidity
data to thingspeak cloud.
include <WiFi.h> // Install the WiFi library
#include "ThingSpeak.h" // always include thingspeak header file after
// Network Parameters
char* ssid = "AI&DS"; // your network SSID (name)
char* pass ="Suk@2017" ; // your network password
WiFiClient client;
int field[2] = {1,2};
// ThingSpeak information
unsigned long channelNumber = 2992675;
const char * readAPIKey = "ETPYBT7YRGX3DYWC";
void setup() {
Serial.begin(115200); // Initialize serial
while (!Serial) {// wait for serial port to connect. Needed for Leonardo native USB port
only
}
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
// 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");
void loop() {
Serial.println("Waiting...");
int x = ThingSpeak.readMultipleFields(channelNumber, readAPIKey);
if(x == 200)
float t = ThingSpeak.getFieldAsFloat(field[0]); // Field 1
float h = ThingSpeak.getFieldAsFloat(field[1]); // Field 2
Serial.println("TEMPERATURE : " + String(t));
Serial.println("HUMIDITY : " + String(h));
}
else{
Serial.println("Problem reading channel. HTTP error code " + String(x));
Serial.println();
delay(20000); // no need to fetch too often
Steps to execute the progam
1. Steps are same as Program5
2. For retrieving temp and Humidity Copy Read API key from Thingspeak After channel
creation.(Channel id is same for both program 5 and Program 6)
7. Write a program on Arduino/Raspberry Pi to publish temperature data to MQTT
broker.
//Open Serial Monitor ans type and send "esp32/t" for temperature
and esp32/h" for humidity.
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
#define DHTPIN 4
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "IobiT Solutions";
const char* password = "IobiT@2023";
char *mqttServer = "test.mosquitto.org";
int mqttPort = 1883;
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message received on topic: ");
Serial.println(topic);
String messageTemp;
for (int i = 0; i < length; i++) {
messageTemp += (char)message[i];
}
if (String(topic) == "esp32/request_t") {
float t = dht.readTemperature();
if (!isnan(t)) {
char tempString[8];
dtostrf(t, 1, 2, tempString);
Serial.print("Publishing Temperature: ");
Serial.println(tempString);
mqttClient.publish("esp32/temperature", tempString);
}
}
if (String(topic) == "esp32/request_h") {
float h = dht.readHumidity();
if (!isnan(h)) {
char humString[8];
dtostrf(h, 1, 2, humString);
Serial.print("Publishing Humidity: ");
Serial.println(humString);
mqttClient.publish("esp32/humidity", humString);
}
}
}
void reconnect() {
while (!mqttClient.connected()) {
Serial.print("Connecting to MQTT...");
if (mqttClient.connect("ESP32Publisher")) {
Serial.println("Connected");
mqttClient.subscribe("esp32/request_t");
mqttClient.subscribe("esp32/request_h");
} else {
Serial.print("Failed, Error Code: ");
Serial.println(mqttClient.state());
delay(2000);
}
}
}
void setup() {
Serial.begin(9600);
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to Wi-Fi");
mqttClient.setServer(mqttServer, mqttPort);
mqttClient.setCallback(callback);
}
void loop() {
if (!mqttClient.connected()) reconnect();
mqttClient.loop();
}
8. To interface Smart gas leakage email alert using things Speak.
#include <WiFi.h>
#include <HTTPClient.h>
// WiFi credentials
const char* ssid = "AI&DS";
const char* password = "Suk@2017";
// ThingSpeak settings
const char* server = "api.thingspeak.com";
String apiKey = "NXA6QQ3OUZSO6YYI"; // Your ThingSpeak Write API Key
// MQ135 sensor pin
const int mq135Pin = 32;
// Timing
unsigned long lastTime = 0;
const unsigned long timerDelay = 15000; // ThingSpeak minimum is 15 seconds
void setup() {
Serial.begin(115200);
// Set ADC range to read full 3.3V
analogSetAttenuation(ADC_11db);
pinMode(mq135Pin, INPUT);
// Connect to WiFi
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" connected");
// Warm-up time for MQ135
Serial.println("Warming up MQ135 sensor (2 minutes)...");
delay(120000); // 2 minutes warm-up
Serial.println("Sensor ready.");
}
void loop() {
if (millis() - lastTime >= timerDelay) {
int gasValue = analogRead(mq135Pin); // Read sensor value
Serial.print("Gas Sensor Value: ");
Serial.println(gasValue);
// Send data to ThingSpeak
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String postData = "api_key=" + apiKey + "&field1=" + String(gasValue);
http.begin("http://" + String(server) + "/update");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpResponseCode = http.POST(postData);
if (httpResponseCode > 0) {
Serial.println("Data sent to ThingSpeak successfully.");
} else {
Serial.print("Failed to send data. HTTP error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi not connected. Skipping upload.");
}
lastTime = millis();
}
}
OUTPUT:
Connection:
First pin from ESP32 32th pin to MQ135 A0 pin (anlog pin)
Second pin from MQ135 GND to GND
Third pin From MQ135 5V to 5v.
9. Write a program on Arduino/Raspberry Pi to Weather display system using DHT11
and LCD.
#include <Adafruit_GFX.h>
#include<Adafruit_ST7735.h>
#include<SPI.h>
#include"DHT.h"
//define pins of TFT screen
#define TFT_CS 12 //chip select
#define TFT_RST 14 //RES(reset)
#define TFT_DC 13 //AO (SDA)serial data
#define TFT_SCLK 22 //Serial clock(scl)
#define TFT_MOSI 21 //SDA MASTER IN SLAVE OUT
#define DHTPIN 4
#define DHTTYPE DHT11
Adafruit_ST7735 tft =
Adafruit_ST7735(TFT_CS,TFT_DC,TFT_MOSI,TFT_SCLK ,TFT_RST);
DHT Dht(DHTPIN,DHTTYPE);
float temp;
float hum;
void setup(void) {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.print("ST7735 TFT grafics test");
tft.initR(INITR_BLACKTAB);
Serial.println("Initializing......");
tft.setTextWrap(true); //horizontizal(false) or vertical(true)
Dht.begin();
}
void loop() {
// put your main code here, to run repeatedly:
temp = Dht.readTemperature();
hum = Dht.readHumidity();
tft.fillScreen(ST7735_BLACK); //backgroundcolor
tft.setCursor(0,0);
tft.setTextColor(ST7735_RED);
tft.setTextSize(2);
tft.print("TEMP : ");
tft.setTextColor(ST7735_YELLOW);
tft.println(temp);
tft.setTextColor(ST7735_CYAN);
tft.print("HUM : ");
tft.setTextColor(ST7735_ORANGE);
tft.println(hum);
delay(2000);
}
OUTPUT
DHT11
DHT11 3.3V to 3.3 V left
DHT11 Mid Output pin to GPIO4 from ESP32
TFT Display ESP32
LED 5v
SCLK 22
SDA 21
A0(Anlog pin) 13
RES 14
CS 12
GND GND
VCC 5V
10. Object distance display using 7-segment display and Ultrasonic sensor & read the
sensor data when specified key is pressed.
const int trigPin = 22;
const int echoPin = 21;
//define sound speed in cm/uS
#define SOUND_SPEED 0.0343
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
void setup() {
Serial.begin(9600); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in
microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);
delay(1000);
}