IoT_Applications_Practical_Approach_final
IoT_Applications_Practical_Approach_final
Approach
First Edition
Contact Details:
TI-310, FTBI, TIIR Building
National Institute of Technology Rourkela
Rourkela, Odisha – 760098, India
Email: [email protected]
Mobile: +91- 9437940105
Index
Sl. Exp. Name of the Practical Experiment Page
No. No. No.
1. 1 Familiarization with ESP32 and Arduino IDE and perform 4-7
necessary software installation.
2. 2 Program for blinking an LED. 8-9
3. 3 LED control using push button. 10-11
4. 4 Reading DHT 11 Sensor data and display it on the Serial 12-15
Monitor.
5. 5 Reading BMP 180 Sensor data and display it on Serial 16-19
Monitor.
6. 6 Reading IMU Sensor data and display it on Serial Monitor 20-22
7. 7 Display serial monitor input data on OLED. 23-26
8. 8 Read DHT 11 Sensor data and display it on OLED 27-31
9. 9 Read BMP 180 Sensor data and display it on OLED 32-36
10. 10 Read IMU Sensor data and display it on OLED. 37-41
11. 11 Relay Toggling 42-45
12. 12 Interfacing Speaker (Beep Sound) 46-49
13. 13 Alarm system at High temperatures 50-54
14. 14 Activating Alarm at IMU readings 55-59
15. 15 Reading the data from SD Card 60-64
16. 16 Writing the data to SD Card 61-69
17. 17 Display Sensor Data on Mobile Application using Bluetooth 70-73
18. 18 Relay control using Blynk IoT mobile app 74-82
19. 19 Data Transmission using Wi-Fi (ESP-32 Web Server) 83-87
20. 20 Display Sensor Data in Blynk Mobile & Web Application 88-92
using Wi-Fi
21. 21 Retrieving Data from Thing Speak Cloud Platform 93-99
22. 22 Test GSM using AT Commands 100-105
23. 23 Data Transmission using GSM 106-114
24. 24 SMS Alert on Accident detection (Without Location) 115-121
25. 25 Test LoRa 122-126
26. 26 Data Transmission using LoRa 127-135
27. 27 Data Transmission using FSO 136-140
28. 28 Upload Sensor Data in SQLITE Database 141-146
29. 29 Retrieve Sensor Data from SQLITE Database 147-152
2|Page
30. 30 Remote LED Control using ESP32 / IOT Development Board 153-159
Web Server
31. 31 Weather Station 160-166
32. 32 IMU Data Monitoring using Arduino, HTML, and Node.js 167-180
3|Page
Experiment. No: 01
Title: Familiarization with ESP32 and Arduino IDE and perform necessary
software installation.
Components Used:
Software Used:
• Arduino IDE
Introduction:
Uploading code to an Arduino board via the Arduino IDE is crucial for deploying projects. This
process involves installing the IDE, setting up the ESP32 board manager, and selecting the
appropriate drivers. These steps ensure a seamless connection between your development
environment and the target hardware, facilitating smooth code execution.
Procedure:
1. Software Install
• Download the software from the Arduino website.
2. Setup ESP32 board manager
• Open the Arduino IDE.
• Go to File -> Preferences.
• In the "Additional Board Manager URLs" field, add the following
URL:
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-
pages/package_esp32_index.json
4|Page
Open the Boards Manager:
• In the Boards Manager window, type esp32 into the search bar.
5|Page
Select Your ESP32 Board:
• Scroll down to the "ESP32 Arduino" section and select your specific ESP32 board (e.g.,
"ESP32 Dev Module").
6|Page
Install the Drivers:
Conclusion:
Following these steps will prepare your Arduino IDE to upload code to the ESP32, enabling
you to run and test various projects seamlessly. This setup ensures that your development
environment is correctly configured for programming and interfacing with the ESP32
microcontroller.
7|Page
Experiment. No: 02
Title: Program for blinking an LED
Components Used:
Hardware Used:
• DOIT ESP32 DevKit V1Module
Software Used:
• Arduino IDE
Introduction:
In this experiment, we will blink an LED connected to the ESP32 microcontroller. Blinking an
LED is a basic but essential task to get started with microcontrollers and embedded systems. It
helps in understanding how to control digital output pins. The LED will turn on and off
alternately with a delay of one second, demonstrating basic GPIO (General Purpose
Input/Output) functionality.
Block Diagram:
Circuit Diagram:
Procedure:
• Install Arduino IDE and set up the environment for ESP32.
• Use the provided code to control the in-built LED.
• Select the board: DOIT ESP32 DEVKIT V1.
8|Page
• Compile the code and upload it to the ESP32.
• Observe the LED blinking with a one-second interval.
Code:
void setup() {
pinMode(2, OUTPUT);
}
void loop() {
digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Output:
Conclusion:
In conclusion, we successfully interfaced an LED with the ESP32 and controlled it using digital
output pins. The LED blinked at one-second intervals, demonstrating the basic functionality of
GPIO operations. This experiment provided a fundamental understanding of controlling digital
outputs with microcontrollers, which is a building block for more complex projects involving
sensors and actuators.
Applications:
• Visual indicators in embedded systems
• Debugging tool for microcontroller projects
• Basic understanding for beginners in microcontroller programming
9|Page
Experiment. No: 03
Title: LED control using push button.
Components Used:
Hardware Used:
• DOIT ESP32 DevKit V1 Module
• Pushbutton
• 10k ohm Resistor
Software Used:
• Arduino IDE
Introduction:
In this experiment, we will control an LED using a pushbutton connected to the ESP32
microcontroller. When the pushbutton is pressed, the LED will turn on, and when the
pushbutton is released, the LED will turn off. This experiment demonstrates how to read digital
input from a pushbutton and control digital output to an LED, providing a fundamental
understanding of interfacing input devices with microcontrollers.
Block Diagram:
Circuit Diagram:
Pin Connections Table
Procedure:
• Install Arduino IDE and set up the environment for ESP32.
• Connect one side of the pushbutton to GPIO12 of the ESP32.
• Connect the other side of the pushbutton to GND.
• Use the provided code to control the LED with the pushbutton.
• Select the board: DOIT ESP32 DEVKIT V1.
• Compile the code and upload it to the ESP32.
• Press the pushbutton to observe the LED turning on and off.
Code:
const int buttonPin = 12; // the number of the pushbutton pin
const int ledPin = 2; // the number of the LED pin
10 | P a g e
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
Output:
Conclusion:
In conclusion, we successfully interfaced a pushbutton and an LED with the ESP32
microcontroller. The pushbutton was used to control the LED, turning it on when pressed and
off when released. This experiment provided a fundamental understanding of reading digital
inputs and controlling digital outputs with microcontrollers, which is essential for building
interactive embedded systems.
Applications:
• Interactive devices and user interfaces
• Basic input/output control in embedded systems
• Learning foundation for more complex input/output operations
11 | P a g e
Experiment. No: 04
Title: Reading DHT 11 Sensor data and display it on the Serial Monitor.
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
Introduction:
In this experiment, we will read temperature and humidity data from the DHT 11 sensor and
display it on the Serial Monitor using an Arduino. The DHT 11 is a basic, ultra-low-cost digital
temperature and humidity sensor. It uses a capacitive humidity sensor and a thermistor to
measure the surrounding air, and spits out a digital signal on the data pin. This experiment aims
to demonstrate how to interface the DHT 11 sensor with an Arduino and visualize the collected
data on the Serial Monitor.
Block Diagram:
12 | P a g e
Circuit Diagram:
Procedure:
• Install Arduino IDE and set up the environment for ESP32.
• Connect Data pin of DHT11 sensor to GPIO27 of ESP32.
• Install `Wire.h`, `Adafruit_GFX.h`, and `Adafruit_SSD1306.h` libraries in the Arduino
IDE.
• Use the provided code to find out the humidity and temperature of the surroundings
using DHT11 sensor.
• Select the board: DOIT ESP32 DEVKIT V1.
• Compile the code and upload it to the ESP32.
• Open the Serial Monitor in Arduino IDE with a baud rate of 115200 to check the output.
13 | P a g e
Code:
#include "DHT.h"
void setup() {
// Start the serial communication
Serial.begin(115200);
// Start the DHT sensor
dht.begin();
}
void loop() {
// Wait a few seconds between measurements
delay(2000);
// Check if any reads failed and exit early (to try again)
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print the results to the Serial Monitor
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" *C");}
14 | P a g e
Output:
Conclusion:
In conclusion, we successfully interfaced the DHT 11 sensor with the Arduino to read
temperature and humidity data. The data was displayed on the Serial Monitor, demonstrating
the sensor's capability to measure and report environmental conditions. This experiment
provided a fundamental understanding of how to work with digital sensors and read data using
Arduino, which can be applied to various projects involving environmental monitoring and
control systems.
Applications:
15 | P a g e
Experiment. No: 05
Title: Reading BMP 180 Sensor data and display it on Serial Monitor.
Components Used:
Hardware Used:
• DOIT ESP32 DevKit V1Module
• BMP180 Module
Software Used:
• Arduino IDE
Introduction:
In this project, we will interface the BMP180 sensor with an Arduino to measure atmospheric
pressure and temperature. The BMP180 is a barometric pressure sensor that is capable of
measuring pressure with a high degree of precision. It can also be used to estimate altitude
when combined with temperature readings. This sensor communicates with the Arduino over
I2C, making it relatively straightforward to connect and program. The collected data will be
displayed on the Serial Monitor, allowing us to observe the pressure and temperature in real-
time.
Block Diagram:
Circuit Diagram:
16 | P a g e
Pin Connections Table:
BMP180 ESP32
GND GND
VCC 3.3V
SCL GPIO 22
SDA GPIO 21
Procedure:
• Install Arduino IDE and set up the environment for ESP32.
• Connect SCL and SDA pins of BMP180 sensor to GPIO22 and GPIO 21 of ESP32.
• Install `Wire.h`, `Adafruit_Sensor.h`, and `Adafruit_BMP085_U.h` libraries in the
Arduino IDE.
• Use the provided code to find out the altitude and the pressure of the surroundings using
BMP180 sensor.
• Select the board: DOIT ESP32 DEVKIT V1.
• Compile the code and upload it to the ESP32.
• Open the Serial Monitor in Arduino IDE with a baud rate of 115200 to check the output.
Code:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
void setup () {
Serial.begin(115200);
Serial.println("BMP180 Sensor Test");
17 | P a g e
if (event.pressure) {
// Display the pressure in hPa
Serial.print("Pressure: ");
Serial.print(event.pressure);
Serial.println(" hPa");
Output:
Conclusion:
By successfully interfacing the BMP180 sensor with the Arduino, we have created a functional
system to measure and display atmospheric pressure and temperature. This project
demonstrates the practical application of I2C communication and sensor data acquisition using
an Arduino. The data obtained from the BMP180 sensor can be used for various applications,
including weather monitoring, altitude estimation, and environmental data logging. This
18 | P a g e
project not only enhances our understanding of how to work with sensors and microcontrollers
but also opens up possibilities for more complex and integrated systems in future projects.
Applications:
19 | P a g e
Experiment. No: 06
Title: Reading IMU Sensor data and display it on Serial Monitor
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
Introduction:
In this project, we will interface an Inertial Measurement Unit (IMU) sensor with an Arduino
to measure and display sensor data on the Serial Monitor. IMU sensors typically include
accelerometers, gyroscopes, and sometimes magnetometers, allowing them to measure
acceleration, angular velocity, and magnetic field strength. These measurements are crucial for
understanding the motion and orientation of the sensor in three-dimensional space. By
connecting an IMU sensor to an Arduino, we can capture and analyze this data in real-time,
providing valuable insights into the dynamics of the system being monitored.
Block Diagram:
Circuit Diagram:
Procedure:
• Install Arduino IDE and set up the environment for ESP32.
• Connect SCL and SDA pin of IMU (MPU 9250) sensor to GPIO22 aNd GPIO21 of
ESP32.
• Install `Wire.h`, `MPU9250_asukiaaa.h`, and `WiFi.h` libraries in the Arduino IDE.
• Use the provided code to find out the acceleration and gyroscope using IMU
(MPU9250) sensor.
• Select the board: DOIT ESP32 DEVKIT V1.
• Compile the code and upload it to the ESP32.
• Open the Serial Monitor in Arduino IDE with a baud rate of 115200 to check the output.
Code:
#include <Wire.h>
#include <MPU9250_asukiaaa.h>
#include <WiFi.h>
MPU9250_asukiaaa myIMU;
void setup () {
Serial.begin(115200);
Wire.begin();
myIMU.setWire(&Wire);
myIMU.beginAccel();
myIMU.beginGyro();
}
void loop () {
myIMU.accelUpdate();
myIMU.gyroUpdate();
float accelX = myIMU.accelX();
21 | P a g e
float accelY = myIMU.accelY();
float accelZ = myIMU.accelZ();
float gyroX = myIMU.gyroX();
float gyroY = myIMU.gyroY();
float gyroZ = myIMU.gyroZ();
Conclusion:
By successfully interfacing an IMU sensor with the Arduino, we have created a system that can
measure and display acceleration, angular velocity, and magnetic field strength in real-time.
This project demonstrates the practical application of sensor data acquisition and processing
using an Arduino. The data obtained from the IMU sensor can be used in various applications,
including motion tracking, robotics, drones, and VR/AR systems. This project not only
enhances our understanding of how to work with sensors and microcontrollers but also opens
up possibilities for more complex and integrated systems in future projects.
Applications:
• Motion Tracking
• Drones and UAVs
• Automotive Industry
22 | P a g e
Experiment. No: 07
Title: Interface OLED to ESP32 and display Serial Monitor data on OLED.
Components Used:
Hardware Used:
Software Used:
1. Arduino IDE
Introduction:
In this experiment, we aim to display serial monitor input data on an OLED screen
using an ESP32 microcontroller and Arduino IDE. By capturing data from the serial monitor,
we can visualize the information in real-time on the OLED display. This setup enhances the
readability and accessibility of the data, making it more user-friendly and easier to interpret.
Whether monitoring sensor outputs or debugging system information, presenting serial data on
an OLED screen provides a convenient and effective way to keep track of live inputs and
system statuses.
Block Diagram:
23 | P a g e
Circuit Diagram:
Code:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
24 | P a g e
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
void setup() {
// Initialize Serial communication
Serial.begin(115200);
void loop() {
if (Serial.available() > 0) {
String input = Serial.readStringUntil('\n');
25 | P a g e
Figure: Output at OLED Display.
Conclusion:
In conclusion, displaying serial monitor input data on an OLED screen with an ESP32
microcontroller enhances data visualization and accessibility. This setup is beneficial for real-
time monitoring and debugging, providing clear and immediate feedback for system status and
sensor outputs.
Applications:
• Prototype Development
• Field Testing
• Education and Training
• Home Automation
• Data Logging
26 | P a g e
Experiment. No: 08
Title: Read DHT 11 Sensor data and display it on OLED
Components Used:
Hardware Used:
1. DOIT ESP32 DevKit V1Module
2. DHT11 Temperature Sensor Module
3. 0.96” OLED Display
Software Used:
1. Arduino IDE
Introduction:
In this experiment, we will interface a DHT11 temperature and humidity sensor with an ESP32
microcontroller to read environmental data. The collected data will then be displayed on an
OLED screen. The ESP32, known for its low power consumption and Wi-Fi capability, will
facilitate the sensor data acquisition, while the OLED screen provides a compact and clear way
to visualize the readings. This project is ideal for learning about IoT and sensor integration.
Block Diagram:
Circuit Diagram:
27 | P a g e
Pin Connections Table
ESP32 DHT11
3.3V VCC
GND GND
GPIO 27 DATA
Procedure:
• Connect DHT11 VCC to ESP32 using given pin connection table
• Open the Arduino IDE and install `DHT` and `Adafruit_SSD1306` libraries.
• Select the `DOIT ESP32 DEVKITV1` board in the Arduino IDE.
• Verify and upload the code to the ESP32.
• Open the Serial Monitor and set the baud rate to 9600.
• Observe temperature readings on the Serial Monitor.
• Check temperature readings on the OLED display.
• Record and analyze the temperature data.
Code:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHT.h"
#define DHTPIN 27
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println(F("DHT test!"));
28 | P a g e
dht.begin();
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // infinite loop to stop execution
}
display.display();
delay(2000); // Pause for 2 seconds
display.clearDisplay();
}
void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print(F("Temp: "));
display.print(t);
display.print(F(" C"));
display.setCursor(0, 20);
display.print(F("Temp: "));
display.print(f);
display.print(F(" F"));
display.display();
Serial.print(F("Temp: "));
Serial.print(t);
Serial.print(F(" C ,"));
Serial.print(F("Temp: "));
Serial.println(f);
display.print(F("Humidity: "));
display.print(h);
29 | P a g e
display.print(F("%"));
display.setCursor(0, 10);
}
Output:
Conclusion:
This experiment shows how to use the DHT11 sensor with the DOIT ESP32 DevKit V1 to
measure temperature in a straightforward yet efficient manner. Depending on the needs of the
particular experiment, the given code may be extended to provide further features like data
logging, remote monitoring, or interaction with IoT systems. All things considered, the
30 | P a g e
amalgamation of these constituents provides an economical and easily obtainable resolution
for environmental monitoring purposes.
Applications:
• Home Automation
• Environment Monitoring
• Smart Agriculture
31 | P a g e
Experiment. No: 09
Title: Read BMP 180 Sensor data and display it on OLED
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
Introduction:
In this experiment, we'll read atmospheric pressure and temperature data from a BMP180
sensor and display it on an OLED screen using an ESP32 microcontroller. The BMP180 sensor
is a high-precision digital barometric pressure sensor that also measures temperature. By
integrating it with the ESP32 and an OLED display, we'll create a compact and efficient system
for environmental monitoring. This project demonstrates how to collect, process, and visualize
sensor data using modern IoT development tools.
Block Diagram:
32 | P a g e
Circuit Diagram:
BMP180 ESP32
VCC 3.3V
GND GND
SCL GPIO 22
SDA GPIO 21
33 | P a g e
Code:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
void setup() {
Serial.begin(115200);
while (!Serial);
if (!bmp.begin()) {
Serial.println("Could not find a valid BMP180 sensor, check wiring!");
while (1);
}
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.display();
delay(2000);
display.clearDisplay();
}
void loop() {
sensors_event_t event;
bmp.getEvent(&event);
display.clearDisplay();
if (event.pressure) {
float pressure = event.pressure;
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Pressure: ");
display.print(pressure);
display.println(" hPa");
34 | P a g e
float seaLevelPressure = 1013.25;
float altitude = bmp.pressureToAltitude(seaLevelPressure, event.pressure);
display.print("Altitude: ");
display.print(altitude);
display.println(" m");
Serial.print("Pressure: ");
Serial.print(pressure);
Serial.println(" hPa");
Serial.print("Altitude: ");
Serial.print(altitude);
Serial.println(" m");
} else {
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("Sensor error");
display.display();
}
delay(2000);
}
Output:
35 | P a g e
Figure: Output on the OLED Display.
Conclusion:
This experiment successfully interfaces a BMP180 sensor with an ESP32 to measure and
display barometric pressure, altitude, and temperature on a 0.96’’ OLED screen. This setup is
useful for environmental monitoring applications and demonstrates the integration of sensor
data with a visual display interface.
Applications:
36 | P a g e
Experiment. No: 10
Title: Read IMU Sensor data and display it on OLED.
Components Used:
Hardware Used:
• DOIT ESP32 DevKit V1Module
• IMU(MPU9250) Module
• 0.96’’ OLED Display
Software Used:
• Arduino IDE
Introduction:
In this experiment, we'll read acceleration and gyroscope data from an IMU
(MPU9250) sensor and display it on an OLED screen using an ESP32 microcontroller. The
MPU9250 is a high-precision sensor that measures acceleration and rotational motion. By
integrating it with the ESP32 and an OLED display, we'll create a compact and efficient system
for motion and orientation monitoring. This project demonstrates how to collect, process, and
visualize sensor data using modern IoT development tools.
Block Diagram:
37 | P a g e
Circuit Diagram:
Procedure:
• Set up Arduino IDE and install required libraries.
• Ensure the hardware connections are secure, particularly the SCL and SDA pins of the
IMU (MPU9250) sensor to GPIO22 and GPIO21 of the ESP32, and the connections to
the OLED display.
• Install the `Wire.h`, `MPU9250_asukiaaa.h`, `Adafruit_SSD1306.h`, and
`Adafruit_GFX.h` libraries in the Arduino IDE.
• Select the appropriate board (DOIT ESP32 DEVKIT V1) and port in Arduino IDE.
• Verify and upload the provided code to the ESP32.
38 | P a g e
• Ensure the IMU sensor and OLED display initialize correctly.
• Ensure the baud rate in the Serial Monitor matches the baud rate mentioned in the code
(typically 115200).
• Observe sensor data on the Serial Monitor and OLED display.
• Record acceleration and gyroscope readings displayed on the OLED screen.
• Analyze the recorded data for consistency and accuracy.
• Save and close the program.
Code:
#include <Wire.h>
#include <MPU9250_asukiaaa.h>
#include <WiFi.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
void setup () {
Serial.begin(115200);
Wire.begin();
// Initialize IMU
myIMU.setWire(&Wire);
myIMU.beginAccel();
myIMU.beginGyro();
display.clearDisplay();
}
void loop () {
myIMU.accelUpdate();
myIMU.gyroUpdate();
39 | P a g e
float accelX = myIMU.accelX();
float accelY = myIMU.accelY();
float accelZ = myIMU.accelZ();
float gyroX = myIMU.gyroX();
float gyroY = myIMU.gyroY();
float gyroZ = myIMU.gyroZ();
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Accel X: "); display.print(accelX); display.println("
m/s^2");
display.print("Accel Y: "); display.print(accelY); display.println("
m/s^2");
display.print("Accel Z: "); display.print(accelZ); display.println("
m/s^2");
display.setCursor(0, 32);
display.print("Gyro X: "); display.print(gyroX); display.println(" rad/s");
display.print("Gyro Y: "); display.print(gyroY); display.println(" rad/s");
display.print("Gyro Z: "); display.print(gyroZ); display.println(" rad/s");
display.display();
delay(1000);
}
40 | P a g e
Output:
Conclusion:
The integration of IMU sensors with OLED displays using ESP32 microcontrollers
provides a practical approach to real-time motion and orientation monitoring. This system not
only offers immediate visual feedback but also enhances data accuracy and consistency. As
technology continues to advance, the effectiveness and accessibility of these systems are likely
to improve, offering greater utility in various applications. Investing in and adopting IMU-
based monitoring systems is a crucial step towards ensuring safety, precision, and efficiency in
multiple fields.
Applications:
• Motion Tracking
• Enhanced Safety
• Real-Time Monitoring
• Industrial Monitoring
• Robotics
• Wearable Technology
41 | P a g e
Experiment. No: 11
Title: Relay Toggling using ESP32
Components Used:
Hardware Used:
• DOIT ESP32 Dev Kit V1Module
• Relay Module
Software Used:
• Arduino IDE
Introduction:
In this experiment, we'll demonstrate how to control an LED using a relay module with an
ESP32 microcontroller and display the LED status on a 0.96” OLED screen. A relay is an
electrically operated switch that allows low-power circuits to control high-power devices
safely. The experiment involves setting up the ESP32 to toggle the LED on and off through the
relay, with the OLED display providing real-time visual feedback. This setup highlights the
integration of microcontroller control, actuator switching, and visual display.
Block Diagram:
42 | P a g e
Circuit Diagram:
VCC 3.3V
GND GND
Procedure:
• Install Arduino IDE and set up the environment for ESP32.
• Connect Relay trigger pin to GPIO13 of ESP32.
• Install `Wire.h`, `Adafruit_GFX.h`, and `Adafruit_SSD1306.h` libraries in the Arduino
IDE.
• Use the provided code to control the relay and LED
• Select the board: DOIT ESP32 DEVKIT V1.
• Compile the code and upload it to the ESP32.
• Open the Serial Monitor in Arduino IDE with a baud rate of 9600 to check the output.
43 | P a g e
Code:
#include <Wire.h>
Output:
44 | P a g e
Figure: LED on and off indicating status of relay
Conclusion:
In this experiment, we successfully demonstrated how to control an LED using a relay module
and an ESP32 microcontroller. The OLED display was used to visually indicate the status of
the LED, while the relay acted as an actuator to switch the LED on and off. This setup can be
extended to control various high-power devices safely using low-power signals from
microcontrollers.
Applications:
• Home Automation
• Industrial Control System
• Remote Device Control
45 | P a g e
Experiment. No: 12
Title: Interfacing Speaker (Beep Sound)
Components Used:
Hardware Used:
1. Arduino Uno
2. LM386 Audio amplifier
3. Speaker
Software Used:
1. Arduino IDE
Introduction:
In this experiment, we will control the volume of an audio signal using Pulse Width Modulation
(PWM) with an Arduino board and an LM386 audio amplifier. By varying the duty cycle of
the PWM signal, we can adjust the input to the amplifier, thereby controlling the volume output
to a speaker. This experiment demonstrates how digital signals can be used to modulate audio
output, providing a practical example of PWM in audio applications.
Block Diagram:
46 | P a g e
Circuit Diagram:
Procedure:
• Install Arduino IDE and setup the environment for ESP32.
• Connect LM386 Audio Amplifier to ESP32 according to given pin connections.
• Connect the speaker to the output pins of LM386.
• Power up the Arduino board.
• Open Arduino IDE, write the provided PWM control code, and upload it to the
Arduino board.
• Open the Serial Monitor in Arduino IDE and adjust the volume by entering values
between 0 and 255.
• Play audio through the connected speaker and verify volume adjustment.
47 | P a g e
Code:
const int ampPin = 25; // GPIO for amplifier input
int maxDutyCycle = 255; // Maximum duty cycle (volume)
void setup() {
Serial.begin(115200);
pinMode(ampPin, OUTPUT);
}
void loop() {
// Generate a PWM signal with adjustable volume
for (int dutyCycle = 0; dutyCycle <= maxDutyCycle; dutyCycle += 5) {
analogWrite(ampPin, dutyCycle);
delay(10);
}
for (int dutyCycle = maxDutyCycle; dutyCycle >= 0; dutyCycle -= 5) {
analogWrite(ampPin, dutyCycle);
delay(10);
}
Output:
Upon uploading the code to the Arduino board, the PWM signal adjusts the volume as per the
set duty cycle. The serial monitor displays the current volume setting, providing real-time
feedback on adjustments made.
48 | P a g e
Conclusion:
This experiment demonstrates the effective use of Arduino's PWM capabilities for volume
control in audio applications. The flexibility of PWM allows for precise control over analog
characteristics using digital methods. Further enhancements could include integrating this
setup into audio amplification systems or as part of interactive sound installations.
Applications:
• DIY Audio Amplifiers
• Smart Home Systems
• Interactive Sound Installations:
• Portable Speaker Systems
• Hearing Aid Devices
• Automotive Audio Systems
• Sound Level Monitoring
49 | P a g e
Experiment. No: 13
Title: Activating Alarm system at High temperatures.
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
Introduction:
In recent years, climate change and the rising frequency of extreme weather events have
underscored the importance of innovative solutions to manage and mitigate environmental
hazards. These systems are designed to provide early warnings in situations where excessive
heat can lead to severe consequences, including health risks, fire hazards, and damage to
infrastructure. By leveraging advanced technology and sensors, these alarm systems can play
a crucial role in enhancing safety and preparedness in both residential and industrial settings.
Block Diagram:
50 | P a g e
Circuit Diagram:
DHT11 ESP32
GND GND
VCC 3.3V
DATA GPIO 27
Procedure:
Code:
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
void setup () {
Serial.begin(115200);
dht.begin();
pinMode(ALARM_PIN, OUTPUT);
digitalWrite(ALARM_PIN, LOW); // Initialize the alarm as off
Serial.println("DHT11 sensor alarm system initialized.");
}
void loop () {
// Reading temperature
float temp = dht.readTemperature();
52 | P a g e
}
Serial.print("Temperature: ");
Serial.print(temp);
Serial.println(" *C");
// Check if temperature exceeds the threshold
if (temp > TEMP_THRESHOLD) {
tone (ALARM_PIN, 1000); // Turn on the alarm (1 kHz tone)
Serial.println("Alarm ON - High temperature detected!");
}
else {
noTone(ALARM_PIN); // Turn off the alarm
Serial.println("Alarm OFF");
}
Delay (2000); // Wait 2 seconds before the next loop
}
Output:
53 | P a g e
Figure: Indicating ESP32, DHT11 sensor and LM386 sensor
Conclusion:
Applications:
• Residential Safety
• Industrial Settings
• Healthcare Facilities
54 | P a g e
Experiment. No: 14
Title: Activating Alarm at IMU readings
Components Used:
Hardware Used:
• DOIT ESP32 DevKit V1Module
• IMU(MPU9250) Module
• Audio Amplifier Module (LM386)
Software Used:
• Arduino IDE
Introduction:
In this experiment, we use an ESP32 microcontroller to activate an alarm based on
acceleration readings from an IMU sensor. The ESP32, programmed via Arduino IDE,
continuously monitors the IMU's data and triggers the alarm when the acceleration exceeds a
predefined threshold. This setup enables real-time detection of significant movement,
enhancing applications like machinery monitoring, fall detection, and security systems by
providing immediate alerts and ensuring timely interventions.
Block Diagram:
55 | P a g e
Circuit Diagram:
56 | P a g e
Procedure:
• Install Arduino IDE and set up the environment for ESP32.
• Ensure the hardware connections are secure, particularly the SCL and SDA pins of the
IMU (MPU9250) sensor to GPIO22 and GPIO21 of the ESP32.
• Install the `Wire.h`, `MPU9250_asukiaaa.h`, and `WiFi.h` libraries in the Arduino IDE.
• Use the provided code to monitor the acceleration from the IMU (MPU9250) sensor.
• Add code to trigger an alarm when the acceleration exceeds a specified threshold.
• Select the board: DOIT ESP32 DEVKIT V1.
• Compile the code and upload it to the ESP32.
• Ensure the baud rate of the serial monitor matches the one declared in the code.
• Verify the output in serial monitor and check for the acceleration values and alarm.
• Save and close the program when finished.
Code:
#include <Wire.h>
#include <MPU9250_asukiaaa.h>
#include <WiFi.h>
MPU9250_asukiaaa myIMU;
void setup() {
Serial.begin(115200);
Wire.begin();
myIMU.setWire(&Wire);
myIMU.beginAccel();
myIMU.beginGyro();
void loop() {
}
myIMU.accelUpdate();
57 | P a g e
float accelX = myIMU.accelX();
float accelY = myIMU.accelY();
float accelZ = myIMU.accelZ();
Output:
Conclusion:
The integration of acceleration-based alarm systems using IMU sensors and ESP32
microcontrollers provides a proactive approach to managing risks associated with sudden
movements or vibrations. These systems not only deliver immediate alerts that can prevent
accidents and equipment damage but also contribute to long-term safety and reliability in
various applications. As technology advances, the effectiveness and accessibility of these
systems are likely to improve, offering enhanced protection against dynamic and potentially
58 | P a g e
hazardous conditions. Investing in and adopting acceleration-based alarm systems is a crucial
step towards ensuring a safer, more resilient future in various fields.
Applications:
• Enhanced Safety
• Real-Time Monitoring
• Accident prevention
• Elderly Monitoring
• Motion Tracking
• Industrial Monitoring
• Robotics
• Wearable Technology
59 | P a g e
Experiment. No: 15
Title: Reading Hexadecimal Number from SD Card and Displaying on OLED using ESP32
Components Used:
Hardware Used:
• ESP32 Development Board
• OLED Display (SSD1306)
• MICROSD CARD MODULE
• SD Card
Software Used:
• Arduino IDE
Introduction:
This experiment involves reading a hexadecimal number from a text file on an SD card
using an ESP32 and displaying it on an OLED display.
Block Diagram:
Circuit Diagram:
60 | P a g e
Pin Connections Table:
.96” OLED DISPLAY ESP32
GND GND
VCC 3.3V
SCL GPIO 22
SDA GPIO 21
Procedure:
• Connect the SD card module and OLED display to the ESP32 as per the pin diagram.
• Install the required libraries in the Arduino IDE:
o SD
o Wire
o Adafruit_SSD1306
• Create an Arduino sketch to read the hexadecimal number from the SD card and display
it on the OLED display.
• Open the Arduino IDE.
• Install the required libraries: SD, Wire, Adafruit_SSD1306.
• Connect the ESP32, SD card module, and OLED display as per the pin diagram.
• Copy the provided Arduino sketch into the Arduino IDE.
• Upload the code to the ESP32.
• Create a text file named hex.txt on the SD card.
• Write a hexadecimal number (e.g., 0x1A2B3C) into the file and save it.
• Insert the SD card into the SD card module connected to the ESP32.
61 | P a g e
• After uploading, the hexadecimal number from the SD card will be displayed on the
OLED screen.
Code:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <SD.h>
#include <SPI.h>
void setup() {
Serial.begin(115200);
if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.display();
delay(2000);
display.clearDisplay();
if (!SD.begin(CS_PIN)) {
Serial.println("SD card initialization failed!");
return;
}
Serial.println("SD card initialized.");
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("Reading Hex");
display.display();
delay(1000);
62 | P a g e
}
myFile.close();
display.clearDisplay();
display.setCursor(0, 0);
display.print("Hex: ");
display.println(hexNumber);
display.display();
} else {
Serial.println("Failed to open file.");
}
}
void loop() {
// Nothing to do here
}
Output:
Figure: The hexadecimal number read from the SD card / Created if not present.
63 | P a g e
The hexadecimal number read from the text file on the SD card is displayed on the
OLED screen.
Conclusion:
The experiment demonstrates reading a hexadecimal number from an SD card and
displaying it on an OLED display using an ESP32.
Applications:
64 | P a g e
Experiment. No: 16
Title: Reading Data from DHT11 Sensor and Writing to SD Card using ESP32
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
• HTML for Web Interface
Introduction:
This experiment demonstrates reading temperature and humidity data from a DHT11
sensor using an ESP32 and writing the data to an SD card. The ESP32 hosts a web interface to
initiate the operations.
Block Diagram:
65 | P a g e
Circuit Diagram:
Procedure:
Code:
Arduino (AmpServer.ino):
#include <SD.h>
#include <SPI.h>
#include <WiFi.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT11
File myFile;
const int chipSelect = 5;
const char* ssid = "OnePlus";
const char* password = "719622@Aa";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
dht.begin();
if (!SD.begin(chipSelect)) {
Serial.println("SD card initialization failed!");
return;
}
Serial.println("SD card initialized.");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi.");
server.begin();
}
void loop() {
67 | P a g e
WiFiClient client = server.available();
if (client) {
String request = client.readStringUntil('\r');
client.flush();
if (request.indexOf("/read_write_data") != -1) {
float h = dht.readHumidity();
float t = dht.readTemperature();
myFile = SD.open("data.txt", FILE_WRITE);
if (myFile) {
myFile.print("Humidity: ");
myFile.print(h);
myFile.print("%, Temperature: ");
myFile.print(t);
myFile.println(" *C");
myFile.close();
Serial.println("Data written to file.");
} else {
Serial.println("Failed to open file.");
}
client.print("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
client.print("<html><body><h1>Data written to SD card</h1>");
client.print("<p>Humidity: ");
client.print(h);
client.print("%</p><p>Temperature: ");
client.print(t);
client.print(" *C</p>");
client.print("<button onclick=\"readWriteData()\">Read & Write
Data</button>");
client.print("<script>");
client.print("function readWriteData() {");
client.print("fetch('/read_write_data').then(response =>
response.text()).then(data => {");
client.print("document.getElementById('output').innerHTML = data;");
client.print("}).catch(error => {");
client.print("document.getElementById('output').innerText = 'Error: ' +
error;");
client.print("});");
client.print("}");
client.print("</script>");
client.print("</body></html>");
}
delay(1);
client.stop();
}
}
68 | P a g e
Output:
The temperature and humidity data from the DHT11 sensor are written to a text file on the SD
card, and a confirmation is displayed on the web interface.
Conclusion:
The experiment demonstrates reading data from a DHT11 sensor and writing it to an SD card
using an ESP32.
Applications:
69 | P a g e
Experiment. No: 17
Title: Display Sensor Data on Mobile Application using Bluetooth
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
• Bluetooth Serial Terminal Mobile Application
Introduction
This project integrates the DHT11 sensor with the ESP32 microcontroller and enables
Bluetooth serial communication to facilitate remote monitoring of temperature and humidity
readings. The ESP32 continuously reads sensor data and transmits it over Bluetooth to an
Android device running a serial terminal application. This report outlines the implementation
details and functionality of the system.
Block Diagram:
70 | P a g e
Circuit Diagram:
Procedure:
• Install the Arduino IDE and necessary libraries (BluetoothSerial and DHT) using the Library
Manager.
• Connect the DHT11 sensor to the ESP32 development board according to the provided pin
connections table.
• Open the Arduino IDE and select the ESP32 board from Tools > Board.
• Copy and paste the provided code into a new Arduino sketch.
• Verify and upload the code to ESP32.
• Open the Bluetooth Serial Terminal Mobile Application on your Android device and pair it
with the ESP32.
71 | P a g e
• Observe the temperature and humidity readings displayed on both the Arduino Serial Monitor
and the Bluetooth Terminal Mobile Application.
Code:
#include <BluetoothSerial.h>
#include "DHT.h"
#define dhtPin 32
#define DHTTYPE DHT11
void setup() {
Serial.begin(115200);
SerialBT.begin("DHT11");
dht.begin();
}
void loop() {
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
SerialBT.println("Failed to read from DHT sensor!");
return;
}
SerialBT.print("Temperature: ");
SerialBT.print(temperature);
SerialBT.print(" °C\t");
SerialBT.print("Humidity: ");
SerialBT.print(humidity);
SerialBT.println(" %");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\t");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
delay(2000);
}
72 | P a g e
Output:
Conclusion:
Applications:
73 | P a g e
Experiment. No: 18
Title: Relay control using Blynk IoT mobile app/Web app
Components Used:
Hardware Used:
Software Used:
1. Arduino IDE
2. Blynk IoT Mobile App/ Web App
Introduction:
In this experiment, we explore relay control using the Blynk IoT mobile app with an
ESP32 microcontroller. By integrating Blynk's intuitive interface and cloud connectivity, we
can remotely control relays from a smartphone or tablet. This setup allows for seamless
interaction with electronic devices or appliances connected to the relays, enhancing
convenience and flexibility in home automation or industrial applications. Through the Blynk
app, users can toggle relay states, monitor device status, and even schedule automated tasks,
offering a versatile solution for IoT-based relay control scenarios.
Block Diagram:
74 | P a g e
Circuit Diagram:
RELAY ESP32
RELAY TRIGGER PIN GPIO 13
VCC 3.3V
GND GND
Procedure:
75 | P a g e
• Give your project a relevant name and click "Done"
• Go to the "Datastreams" section, create a datastream, and select the "Virtual Pin" option.
76 | P a g e
• Give it a relevant name and select a free pin, e.g., V0, then click "Create".
• Click on the settings option on the switch, give it a name, and select the datastream you
previously created (e.g., V0 for LED control). Click "Create".
77 | P a g e
• Select the on/off labels and click "Save".
• Click on the "Save" option on the main page of the web dashboard.
• Now go to Mobile dash board part and follow the instructions to set up this in mobile
app.
• Go to the "Devices" section and click on "New Device", then select "From Template".
78 | P a g e
• Select the previously created template (e.g., LED Control) and click "Create".
• Copy the credentials that appear at the top right corner of the desktop and save them for
further use.
79 | P a g e
• Modify the necessary credentials such as, SSID, Password, BLYNK_TEMPLATE_ID,
BLYNK_TEMPLATE_NAME, BLYNK_AUTH_TOKEN, Virtual pin number,
wherever required.
• Compile the code.
• Upload the code to the ESP32.
• Ensure the baud rate of the serial monitor matches the one declared in the code.
• Control the Relay from the Mobile/Web app remotely and observe the output on the kit
and serial monitor.
• Save and close the program when finished.
Code:
#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL3Va0X1X3K"
#define BLYNK_TEMPLATE_NAME "Led Control"
#define BLYNK_AUTH_TOKEN "uTodbIY3sZKdL9ENxUnCAs-M-eKvGOfS"
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
// Relay pin
#define RELAY_PIN 13
void setup() {
// Debug console
Serial.begin(115200);
80 | P a g e
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Connected to WiFi");
// Print IP address
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// Initialize Blynk
Blynk.config(auth);
// This function will be called every time the Button Widget on V0 changes
state
BLYNK_WRITE(V0) {
int pinValue = param.asInt(); // Get value from virtual pin V0
digitalWrite(RELAY_PIN, pinValue); // Set relay state
if(pinValue == 0) {
Serial.println("LED is OFF");
} else {
Serial.println("LED is ON");
}
}
void loop() {
// Run Blynk
Blynk.run();
}
81 | P a g e
Output:
Conclusion:
In conclusion, controlling relays via the Blynk IoT mobile app and ESP32
microcontroller enables convenient remote operation of electronic devices. This integration
enhances flexibility in home automation and industrial applications, offering easy toggling of
relay states and scheduling automated tasks for enhanced efficiency.
Applications:
• Home Automation
• Industrial Automation
• Security Systems
• Energy Management
• Smart Irrigation
82 | P a g e
Experiment. No: 19
Title: Data Transmission using Wi-Fi (ESP-32 Web Server)
Components Used:
Hardware Used:
• DO IT ESP32 Development Board
• DHT11 Temperature and Humidity Sensor
Software Used:
• Arduino IDE
• Bluetooth Serial Terminal Mobile Application
Introduction:
In this experiment, we integrate the DHT11 sensor with the ESP32 microcontroller to create a
web server that displays temperature and humidity readings. The ESP32 connects to a Wi-Fi
network and hosts a web server. When accessed by a client device, the web server displays
real-time sensor data.
Block Diagram:
Circuit Diagram:
83 | P a g e
Figure: Circuit Diagram
Pin Connections Table
ESP32 DHT11
3.3V VCC
GND GND
GPIO 27 DATA
Procedure:
• Setup Hardware: Connect the DHT11 sensor to the ESP32 as per the pin connections
table.
• Install Arduino IDE: Ensure Arduino IDE is installed on your computer.
• Include Necessary Libraries: Add the WiFi and DHT libraries in the Arduino IDE.
• Configure Wi-Fi: Define your Wi-Fi SSID and password in the code.
• Initialize Serial Communication: Set up serial communication at a baud rate of
115200 for debugging.
• Connect to Wi-Fi: Use WiFi.begin() to connect the ESP32 to the specified Wi-Fi
network and wait until it connects.
• Start Web Server: Begin the web server using server.begin() and print the local IP
address of the ESP32.
• Read Sensor Data: Use the dht.readHumidity() and dht.readTemperature()
functions to read humidity and temperature from the DHT11 sensor.
• Handle Client Requests: Check for client connections, read the client request, and
send an HTML response with the sensor data.
• Deploy Code: Upload the code to the ESP32 and monitor the serial output to verify
successful Wi-Fi connection and data readings.
Code:
#include <WiFi.h>
#include <DHT.h>
// WiFi credentials
const char *ssid = "1011"; // Replace with your network SSID
const char *password = "244466666"; // Replace with your network password
// Create an instance of the server
WiFiServer server(80);
// DHT11 sensor setup
#define DHTPIN 27 // Pin which is connected to the DHT11 sensor
#define DHTTYPE DHT11 // DHT11 sensor type
84 | P a g e
DHT dht(DHTPIN, DHTTYPE);
// Variables to store the sensor readings
float temperature = 0.0;
float humidity = 0.0;
unsigned long previousMillis = 0; // Stores the last time sensor was updated
const long interval = 5000; // Interval at which to read sensor
(milliseconds)
void setup() {
// Start the serial communication
Serial.begin(115200);
delay(10); // Small delay to ensure serial monitor initializes
// Connect to WiFi
Serial.println();
Serial.println("Connecting to WiFi");
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// Initialize the DHT sensor
dht.begin();
}
void loop() {
// Check the current time
unsigned long currentMillis = millis();
// If 5 seconds have passed, read the sensor
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// Read the DHT11 sensor
humidity = dht.readHumidity();
temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Output the readings to the Serial Monitor (for debugging)
Serial.print("Temperature: ");
Serial.print(temperature);
85 | P a g e
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.println(" %");
}
// Check if a client has connected
WiFiClient client = server.available();
if (client) {
Serial.println("New Client.");
// Wait until the client sends some data
while (!client.available()) {
delay(1);
}
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Send the response to the client
String response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: text/html\r\n";
response += "\r\n";
response += "<!DOCTYPE HTML>\r\n";
response += "<html>\r\n";
response += "<head><title>ESP32 Web Server</title></head>\r\n";
response += "<body><h1>Hello from ESP32!</h1>\r\n";
response += "<p>Temperature: " + String(temperature) + " ℃</p>\r\n";
response += "<p>Humidity: " + String(humidity) + " %</p>\r\n";
response += "</body></html>\r\n";
client.print(response);
// Give the web browser time to receive the data
delay(1);
// Close the connection
client.stop();
Serial.println("Client disconnected.");
}
}
Output:
86 | P a g e
Conclusion:
In this experiment, we successfully created a web server using the ESP32 to display real-time
temperature and humidity data from the DHT11 sensor. This project demonstrates the ESP32's
capability to connect to a Wi-Fi network, read sensor data, and serve it over the web. It is an
excellent example of how microcontrollers can be used for IoT applications, providing a simple
yet effective solution for remote monitoring.
Applications:
• Home Automation Systems
• Remote Weather Stations
• Industrial Automation
• Agricultural Monitoring
• Educational Projects
87 | P a g e
Experiment. No: 20
Title: Display Sensor Data in Blynk Mobile & Web Application using Wi-Fi.
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
• Blynk IoT Mobile App
Introduction:
In this experiment, we focus on displaying sensor data in the Blynk mobile and web
applications using Wi-Fi connectivity with an ESP32 microcontroller. By leveraging Blynk's
platform, which facilitates easy IoT device integration and cloud-based data visualization, we
can transmit sensor readings such as temperature, humidity, or any other environmental metrics
to the Blynk app interface in real-time. This allows users to monitor and analyze sensor data
remotely from their mobile devices or web browsers, enabling informed decision-making and
timely responses based on the captured environmental conditions. Through seamless Wi-Fi
connectivity and Blynk's customizable interface, this experiment demonstrates the effective
integration of sensor data into practical IoT applications for enhanced monitoring and control
capabilities.
Block Diagram:
Circuit Diagram:
88 | P a g e
Figure: Circuit Diagram
Pin Connections Table:
ESP32 DHT11
3.3V VCC
GND GND
GPIO 27 DATA
Procedure:
• Setup the Blynk environment:
• Sign up using the Blynk web or mobile app.
• Go to the "Devices" section and create a new device by clicking on the "New Device"
option at the top.
• Give your project a relevant name and click "Done"
• Go to the "Datastreams" section, create 2 datastreams, and select the "Virtual Pin"
option.
• Give it a relevant name and select a free pin, e.g., V1 and later V2, and set data type
option as Double, then click "Create".
• Go to the "Web Dashboard" section to create an interface.
• From the Widget Box on the left, drag the Label widget and place it on the dashboard.
• Click on the settings option on the switch, give it a name, and select the datastream
you previously created (e.g., V1 for Tempertaure). Click "Create".
• Select the on/off labels and click "Save".
89 | P a g e
• Click on the "Save" option on the main page of the web dashboard.
• Now go to Mobile dash board part and follow the instructions to set up this in mobile
app.
• Go to the "Devices" section and click on "New Device", then select "From
Template".
• Select the previously created template (e.g., DHT_11) and click "Create".
• Copy the credentials that appear at the top right corner of the desktop and save them
for further use.
• Blynk Setup is done let’s get into the code.
• Open the Arduino Ide.
• Paste the code and download the required libraries (BlynkSimpleEsp32, WiFi) from
Library Manager.
• Verify the pin connections of the Hardware used.
• Modify the necessary credentials such as, SSID, Password,
BLYNK_TEMPLATE_ID, BLYNK_TEMPLATE_NAME,
BLYNK_AUTH_TOKEN, Virtual pin number, wherever required.
• Compile the code.
• Upload the code to the ESP32.
• Ensure the baud rate of the serial monitor matches the one declared in the code.
• Verify the output in serial monitor and check the data in the Web Dashboard.
• Save and close the program when finished.
Code:
#define BLYNK_TEMPLATE_ID "TMPL394uz6nCQ" // Replace with your Blynk Template
ID
#define BLYNK_TEMPLATE_NAME "DHT11 ESP32" // Replace with your Blynk Template
Name
#define BLYNK_AUTH_TOKEN "qo37fQ_qJGG41UyRzZ0jWx8UgdVDu1SV" // Replace with
your Blynk Auth Token
#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <DHT.h>
char auth[] = "qo37fQ_qJGG41UyRzZ0jWx8UgdVDu1SV"; // Replace with your Blynk
Auth Token
char ssid[] = "1011"; // Replace with your WiFi SSID
char pass[] = "244466666"; // Replace with your WiFi Password
90 | P a g e
#define DHTPIN 27 // GPIO pin connected to the DHT11 sensor
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
BlynkTimer timer;
void sendSensorData()
{
float h = dht.readHumidity();
float t = dht.readTemperature(); // or dht.readTemperature(true) for
Fahrenheit
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(t);
Serial.print("°C, Humidity: ");
Serial.print(h);
Serial.println("%");
// Send data to Blynk
Blynk.virtualWrite(V1, t); // V1 for temperature
Blynk.virtualWrite(V2, h); // V2 for humidity
Serial.println("Displayed data in Blynk app.");
}
void setup()
{
Serial.begin(115200);
Serial.println("Connecting to WiFi...");
Blynk.begin(auth, ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
dht.begin();
// Setup a function to be called every 5 seconds
timer.setInterval(5000L, sendSensorData);
}
void loop()
{
Blynk.run();
timer.run();
}
91 | P a g e
Output:
Figure: Output of the DHT 11 sensor readings displaying on Blynk IoT App
Conclusion:
In conclusion, displaying sensor data in the Blynk mobile and web applications via Wi-
Fi with an ESP32 microcontroller allows for real-time monitoring and analysis. This integration
enhances remote accessibility to environmental data, facilitating informed decision-making
and responsive actions based on captured sensor readings.
Applications:
• Remote Monitoring
• Data Visualization
• Asset Tracking
• Weather Stations
• IoT Projects
92 | P a g e
Experiment. No: 21
Title: Retrieving Data from Thing Speak cloud platform
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
• Thing Speak
Introduction:
Block Diagram:
93 | P a g e
Circuit Diagram:
Procedure:
• Setup the hardware: Connect the OLED display to the ESP32, ensuring all necessary
connections (power, ground, SDA, and SCL) are properly made.
• Include necessary libraries: Include libraries for Wi-Fi, HTTP client, Thing Speak, JSON
parsing, and OLED display in the code.
• Configure Wi-Fi and Thing Speak: Define Wi-Fi credentials (SSID and password) and
define ThingSpeak channel ID and API key.
• Initialize components: Initialize the serial monitor for debugging, initialize the OLED
display, initialize the Wi-Fi connection and wait until connected, and initialize
ThingSpeak.
• Create and send HTTP GET request: Construct the URL for the Thing Speak GET request
and send the HTTP GET request to the Thing Speak server.
• Parse the JSON response: Check if the HTTP request was successful, parse the JSON
response, and extract the relevant data fields.
• Display the data: Clear the OLED display and print the extracted data fields (e.g.,
temperature, pressure, humidity) on the OLED screen.
94 | P a g e
• Repeat the process: Wait for a specified period (e.g., 15 seconds) before repeating the
process to fetch and display new data.
Code:
#include <WiFi.h>
#include <HTTPClient.h>
#include <ThingSpeak.h>
#include <ArduinoJson.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// WiFi credentials
const char* ssid = "manas";
const char* password = "12345678";
// ThingSpeak credentials
const unsigned long channelID = 2565609;
const char* apiKey = "IM8RXILTI9RFXY45";
void setup() {
Serial.begin(115200);
delay(100);
// Connect to WiFi
Serial.print("Connecting to WiFi...");
95 | P a g e
display.print("Connecting to WiFi...");
display.display();
WiFi.begin(ssid, password);
// Initialize ThingSpeak
ThingSpeak.begin(client);
}
void loop() {
// Create the URL for the GET request
String url = String("http://api.thingspeak.com/channels/") + channelID +
"/feeds.json?api_key=" + apiKey + "&results=1";
Serial.print("Requesting URL: ");
Serial.println(url);
96 | P a g e
float field1Value = doc["feeds"][0]["field1"].as<float>();
float field2Value = doc["feeds"][0]["field2"].as<float>();
float field3Value = doc["feeds"][0]["field3"].as<float>();
Serial.print("Displaying Data from Thing Speak");
Serial.print("Temperature: ");
Serial.println(field1Value);
Serial.print("Pressure: ");
Serial.println(field2Value);
Serial.print("Humidity: ");
Serial.println(field3Value);
// Display values on OLED
display.clearDisplay();
display.setCursor(0, 0);
display.print("Field 1: ");
display.println(field1Value);
display.print("Field 2: ");
display.println(field2Value);
display.print("Field 3: ");
display.println(field3Value);
display.display();
}
} else {
Serial.printf("HTTP GET request failed, error: %s\n",
http.errorToString(httpCode).c_str());
display.clearDisplay();
display.setCursor(0, 0);
display.print("HTTP GET failed: ");
display.print(http.errorToString(httpCode).c_str());
display.display();
}
http.end();
delay(15000); // Wait for 15 seconds before reading again
}
97 | P a g e
Output:
Figure: Thing Speak data is being retrieved and displayed on serial monitor.
Figure: Thing Speak data is being retrieved and displayed on OLED display.
Conclusion:
In conclusion, we successfully demonstrated how to retrieve and display environmental
data from the ThingSpeak server using an ESP32 microcontroller. By establishing a WiFi
98 | P a g e
connection and utilizing the capabilities of ThingSpeak, we were able to fetch real-time data
and visualize it on an OLED display. This process involved integrating various software
libraries, constructing and sending HTTP requests, and parsing JSON responses to extract
relevant information.
Applications:
• Smart Agriculture
• Air Quality Monitoring
• Remote Weather Monitoring
• Greenhouse Automation
99 | P a g e
Experiment. No: 22
Title: Testing GSM using AT Commands
Components Used:
Hardware Used:
1. DOIT ES32 Devkit V1 Module
2. GSM A7672s
Software Used:
1. Arduino IDE
Introduction:
In this experiment, we test a GSM module using AT commands to verify its
responsiveness. By sending a series of AT commands through a microcontroller or serial
monitor, we can communicate with the GSM module and assess its functionality. This setup
allows us to check the module's network registration status, signal strength, and ability to send
and receive SMS or voice calls. By systematically testing these functions, we ensure that the
GSM module is operational and ready for integration into various applications, such as remote
monitoring, data communication, and IoT projects. This experiment provides a foundational
understanding of GSM module operations, facilitating reliable mobile communication in
embedded systems.
Block Diagram
100 | P a g e
Circuit Diagram
GND GND
VCC 5V
GND GND
TXD GPIO 32 (RX)
RXD GPIO 33 (TX)
V-INT 3.3V
Procedure:
• Download and install the Arduino IDE from the official website.
• Connect Arduino Board: Use a USB cable to connect your Arduino board to your
computer.
101 | P a g e
• Arduino IDE: Launch the Arduino IDE application on your computer.
• Create or Open Sketch: Start a new sketch if you're beginning a new project or open an
existing one if you've worked on it before.
• Paste and Save Code: Copy your Arduino code into the IDE's code editor. Save your
sketch with a meaningful name.
• Set Board and Port: Select your specific Arduino board model (e.g., Arduino Uno,
Arduino Mega) from the `Tools -> Board` menu. Then, choose the correct port your
Arduino is connected to from the `Tools -> Port` menu.
• Verify and Upload: Click on the `Verify` button (checkmark icon) to compile your code
and check for errors. Once verified, click on the `Upload` button (right arrow icon) to
upload the compiled code to your Arduino board.
• Open Serial Monitor: After uploading the code successfully, navigate to `Tools -> Serial
Monitor` to open the Serial Monitor window. Adjust the baud rate if necessary to match
the settings in your Arduino code (e.g., 115200).
• Test and Verify: Monitor the Serial Monitor for any output from your Arduino board.
Ensure that your Arduino performs its intended functions, such as displaying messages
on an OLED screen or communicating with external devices like a GSM module.
Code:
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <HardwareSerial.h>
void setup() {
// Start serial communication with the GSM module
gsmSerial.begin(baudRate, SERIAL_8N1, 32, 33); // RX = GPIO16, TX = GPIO17
102 | P a g e
Serial.begin(115200);
void loop() {
// Check if data is available on the Serial Monitor
if (Serial.available()) {
String command = Serial.readStringUntil('\n');
command.trim(); // Remove any leading or trailing whitespace
sendATCommand(command.c_str());
}
103 | P a g e
// Display command on Serial Monitor and OLED
Serial.print("Command: ");
Serial.println(command);
display.clearDisplay();
display.setCursor(0, 0);
display.println(F("Command:"));
display.println(command);
display.display();
104 | P a g e
Output:
Conclusion:
In conclusion, through the development of the GSM AT Command Tester using the
ESP32, OLED display, and GSM module, we have gained practical insights into serial
communication, microcontroller interfacing, and AT command interaction with GSM
hardware. This experiment enabled us to effectively send and receive AT commands, monitor
responses in real-time via the Serial Monitor and OLED display, and troubleshoot any issues
encountered during command execution. By implementing this project, we enhanced our
understanding of embedded systems, learned valuable debugging techniques, and acquired
skills essential for testing and integrating GSM modules into larger IoT and communication
projects.
Applications:
• Remote Monitoring
• IoT Applications
• Versatile Connectivity
• Cost-Effective Solution
105 | P a g e
Experiment. No: 23
Title: Data Transmission using GSM
Components Used:
Hardware Used:
• DOIT ES32 Devkit V1 Module
• GSMA7672s
• BMP085(Barometric Sensor)
• DHT11 (Temperature and Humidity Sensor)
• 0.96” OLED Display
Software Used:
• Arduino IDE
Introduction:
In this experiment, we focus on transmitting sensor data using a GSM A7672S module.
The module will send real-time temperature, humidity, and atmospheric pressure readings,
collected by DHT11 and BMP180 sensors, to a remote server. Using an ESP32 microcontroller
and Arduino IDE, we will interface with the GSM A7672S to establish a cellular connection
and transmit the data over the network. By sending these live sensor readings, we can monitor
environmental conditions remotely, providing timely information for analysis and decision-
making. This experiment demonstrates the capability of using GSM technology for data
transmission, which is essential for applications where Wi-Fi or other traditional connectivity
options are unavailable. It enables real-time tracking and management of environmental
parameters, thereby enhancing our ability to respond swiftly to changing conditions and
improve overall resource management and monitoring strategies.
106 | P a g e
Block Diagram:
Circuit Diagram:
107 | P a g e
Pin Connections Table
DHT11 ESP32
GND GND
DATA GPIO 27
VCC 3.3V
BMP180 ESP32
VCC 3.3V
GND GND
SCL GPIO 22
SDA GPIO 21
108 | P a g e
4G/GSM MODEM ESP32
GND GND
VCC 5V
GND GND
TXD GPIO 32 (RX)
RXD GPIO 33 (TX)
V-INT 3.3V
Procedure:
• Open the Arduino Ide.
• Paste the code and download the required libraries (Adafruit_Sensor,
Adafruit_BMP085, Adafruit_SSD1306, DHT, DHT_Universal, HardwareSerial) from
Library Manager.
• Verify the pins of declared in the code with actual connections.
• Modify the necessary credentials such as, Phone Number, if required.
• Compile the code.
• Upload the code to the ESP32.
• Ensure the baud rate of the serial monitor matches the one declared in the code.
• Verify the output in serial monitor and check the data in the message box of the phone
number you provided in the code.
• Save and close the program when finished.
Code:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#include <DHT_U.h>
#include <HardwareSerial.h>
// DHT11 parameters
#define DHTPIN 27
109 | P a g e
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// BMP180 instance
Adafruit_BMP085 bmp;
void setup() {
// Start serial communication with the GSM module
gsmSerial.begin(baudRate, SERIAL_8N1, 32, 33); // RX = GPIO16, TX = GPIO17
110 | P a g e
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println(F("Initializing sensors..."));
display.display();
}
void loop() {
// Read sensor values
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
float pressure = bmp.readPressure() / 100.0F;
111 | P a g e
while (millis() - startTime < 2000) { // 2 seconds timeout
if (gsmSerial.available()) {
String response = gsmSerial.readString();
Serial.println(response);
if (response.indexOf("OK") != -1) {
return true; // Command succeeded
}
break;
}
}
Serial.println("Command failed or timed out");
return false; // Command failed
}
void sendSMS(const char* number, const char* text) {
gsmSerial.print("AT+CMGS=\"");
gsmSerial.print(number);
gsmSerial.println("\"");
delay(100);
gsmSerial.print(text);
delay(100);
112 | P a g e
Output:
113 | P a g e
Conclusion:
The GSM Module A7672s, combined with the ESP32, successfully collects and transmits
sensor data (temperature, humidity, and pressure) to a mobile phone via SMS. The integration
of the GSM module with various sensors, such as the DHT11 and BMP180, allows for real-
time monitoring and reporting of environmental conditions. The data transmission process is
reliable, with the ESP32 handling the processing and communication tasks efficiently. The
system initializes the sensors and GSM module, reads the sensor values, displays them on an
OLED screen, and sends the formatted data as an SMS to a specified phone number.
Applications:
• Environmental Monitoring
• Disaster Management
• Smart Agriculture
• Remote Weather Stations
• Industrial Monitoring
• Health Monitoring
• Smart Home Systems
114 | P a g e
Experiment. No: 24
Title: SMS Alert on Accident detection
Components Used:
Hardware Used:
• DOIT ESP32 DevKit V1Module
• IMU(MPU9250) Module
• GSM A7672s
Software Used:
• Arduino IDE
Introduction:
In this experiment, we focus on implementing an SMS alert system using an ESP32
microcontroller in conjunction with a GSM module A7672s and an IMU (MPU9250) sensor.
The GSM module enables real-time communication via SMS, while the IMU sensor detects
and monitors accelerations indicative of potential accidents. By integrating these components,
we aim to develop a proactive safety mechanism that detects sudden impacts or movements
and automatically alerts designated contacts via SMS. This project highlights the application
of IoT and sensor technology in enhancing emergency response systems, ensuring prompt
notifications in critical situations for improved safety and security measures.
Block Diagram:
115 | P a g e
Circuit Diagram:
Procedure:
• Set up Arduino IDE and ensure libraries for GSM module A7672s (`GSM.h`) and IMU
(MPU9250) sensor (`MPU9250_asukiaaa.h`) are installed.
116 | P a g e
• Connect the GSM module A7672s and IMU (MPU9250) sensor to the ESP32
microcontroller according to their respective pin configurations.
• Define necessary credentials such as SIM card details (SIM PIN, phone number), WiFi
credentials (SSID, password), and server details (if applicable).
• Write and upload the code to the ESP32 microcontroller, incorporating functions to
initialize the GSM module for SMS alerts and read data from the IMU sensor for accident
detection.
• Compile the code and ensure there are no errors before uploading it to the ESP32.
• Verify the baud rate of the serial monitor matches the one declared in the code (typically
115200) to monitor system behaviour and debug any issues.
• Test the functionality by simulating accident scenarios or sudden movements to trigger
the IMU sensor.
• Monitor the GSM module's response to ensure SMS alerts are sent promptly upon
detecting significant accelerations or impacts.
• Validate the system's reliability and responsiveness by analyzing SMS alerts received on
designated mobile devices or monitoring platforms.
• Fine-tune the system parameters and adjust code as necessary to optimize performance
and accuracy in accident detection and SMS alert notifications.
• Save and close the Arduino IDE program once testing and validation are complete.
Code:
#include <Wire.h>
#include <MPU9250_asukiaaa.h>
#include <WiFi.h>
MPU9250_asukiaaa myIMU;
117 | P a g e
// Function prototypes
bool sendATCommand(const char* command, unsigned long timeout = 2000);
bool sendSMS(const char* number, const char* text);
bool waitForResponse(const char* expectedResponse, unsigned long timeout);
void setup() {
Serial.begin(115200);
Wire.begin();
// Initialize IMU
myIMU.setWire(&Wire);
myIMU.beginAccel();
myIMU.beginGyro();
void loop() {
myIMU.accelUpdate();
float accelX = myIMU.accelX();
float accelY = myIMU.accelY();
float accelZ = myIMU.accelZ();
118 | P a g e
bool sendATCommand(const char* command, unsigned long timeout) {
gsmSerial.println(command);
unsigned long startTime = millis();
while (millis() - startTime < timeout) {
if (gsmSerial.available()) {
String response = gsmSerial.readString();
Serial.print("Response from GSM module: ");
Serial.println(response);
if (response.indexOf("OK") != -1) {
return true; // Command succeeded
} else if (response.indexOf("ERROR") != -1) {
Serial.println("AT command returned ERROR");
return false; // Command failed
}
}
}
Serial.println("Command failed or timed out");
return false; // Command failed
}
gsmSerial.print(text);
delay(100);
119 | P a g e
unsigned long startTime = millis();
while (millis() - startTime < timeout) {
if (gsmSerial.available()) {
String response = gsmSerial.readString();
Serial.print("Response to command: ");
Serial.println(response);
if (response.indexOf(expectedResponse) != -1) {
return true; // Expected response received
} else if (response.indexOf("ERROR") != -1) {
Serial.println("Received ERROR response");
return false; // Received ERROR response
}
}
}
Serial.println("Timeout waiting for response");
return false; // Timeout waiting for response
}
Output:
120 | P a g e
Conclusion:
Implementing an SMS alert system using the ESP32, GSM module A7672s, and IMU
(MPU9250) sensor offers a robust solution for detecting and notifying accidents in real-time.
This setup enables immediate communication through SMS alerts upon detecting significant
accelerations or impacts, thereby enhancing emergency response capabilities. By leveraging
IoT and sensor technologies, this project demonstrates a proactive approach to ensuring safety
and rapid intervention in critical situations.
Applications:
• Automotive Safety
• Industrial Safety
• Personal Safety Devices
• Healthcare Monitoring
• Construction Site Safety
• Security Systems
• Public Safety
121 | P a g e
Experiment. No: 25
Title: Test LoRa
Components Used:
Hardware Used:
• DOIT ESP32 DevKit V1Module
• LoRa Module
Software Used:
• Arduino IDE 2.3.2
Introduction:
LoRa, short for Long Range, is a wireless communication technology designed for long-
distance, low-power, and low-data-rate communication. It is particularly suitable for Internet
of Things (IoT) applications, where devices need to communicate small amounts of data over
long distances while conserving battery life.
Modulation Technique: LoRa uses Chirp Spread Spectrum modulation, which spreads a
narrowband signal over a wider band of frequencies. This technique increases resistance to
interference and multipath fading.
Chirps: A chirp is a signal in which the frequency increases (up-chirp) or decreases (down-
chirp) over time. LoRa modulates the data into chirps, which are resistant to noise and can be
decoded even at low signal-to-noise ratios.
Long Range: LoRa technology can achieve communication ranges up to 15 kilometres (about
10 miles) in rural areas and up to several kilometres in urban settings, depending on the
environment and antenna setup.
Low Power Consumption: Devices using LoRa can operate on small batteries for many years,
making it ideal for remote and low-maintenance applications.
122 | P a g e
Low Data Rate: LoRa is optimized for small data packets and has data rates ranging from 0.3
kbps to 50 kbps, which is sufficient for many sensor-based applications.
Robustness: LoRa's modulation technique makes it resistant to interference and allows for
reliable communication even in noisy environments.
License-Free Spectrum: LoRa operates in the unlicensed ISM (Industrial, Scientific, and
Medical) bands, which vary by region (e.g., 868 MHz in Europe, 915 MHz in North America,
433 MHz in Asia).
Block Diagram:
Circuit Diagram:
123 | P a g e
Pin Connections Table
LORA BOARD (868MHZ) ESP32
GND GND
MISO GPIO 19
MOSI GPIO 23
SCK GPIO 18
NSS GPIO 5
RST GPIO 14
DIO0 GPIO 2
VCC 3.3V
Procedure:
• Open Arduino IDE and setup environment for ESP32
• Install LoRa Library:
Go to Sketch -> Include Library -> Manage Libraries.
Search for LoRa and install the LoRa by Sandeep Mistry library.
• Write the code given below and choose the correct board and port.
o Board: DOIT ESP32 DEVKIT V1 (or the appropriate ESP32 board you are
using).
o Port: port to which the ESP32 is connected.
• Verify and upload the code to the ESP32
Code:
#include <SPI.h>
#include <LoRa.h>
void setup() {
Serial.begin(115200);
while (!Serial);
Serial.println("LoRa Sender");
LoRa.setPins(csPin, resetPin, irqPin);
if (!LoRa.begin(868E6)) {
Serial.println("Starting LoRa failed!");
124 | P a g e
while (1);
}
Serial.println("LoRa Initializing OK!");
}
void loop() {
Serial.println("Sending packet: Hello");
LoRa.beginPacket();
LoRa.print("Hello");
LoRa.endPacket();
delay(1000);
}
Output:
125 | P a g e
Conclusion:
In this experiment, we successfully implemented a LoRa communication setup using an ESP32
DevKit V1 module and a LoRa module operating at 868 MHz. The experiment demonstrated
how to establish a basic LoRa transmitter that sends packets of data over long distances with
low power consumption. The system was initialized, and a "Hello" message was sent
periodically. This experiment highlights the simplicity and efficiency of using LoRa technology
for IoT applications, especially where long-range communication and low power consumption
are essential.
Applications:
• Environmental Monitoring
• Smart Agriculture
• Asset Tracking
126 | P a g e
Experiment. No: 26
Title: Data Transmission using LoRa
Components Used:
Hardware Used:
• DOIT ESP32 DevKit V1Module x2
• LoRa Module with antenna x2
• SSD1306(OLED)
• DHT11 Sensor
Software Used:
• Arduino IDE
Introduction:
This experiment demonstrates the use of LoRa (Long Range) technology to transmit humidity
and temperature data from a DHT11 sensor connected to one ESP32 module (Transmitter) to
another ESP32 module (Receiver). The system leverages LoRa's long-range, low-power
communication capabilities, making it ideal for remote IoT applications. Data collected by the
DHT11 sensor is displayed on an OLED screen and transmitted wirelessly using LoRa, and the
received data is displayed on another OLED screen connected to the receiver ESP32 module.
Block Diagram:
127 | P a g e
Circuit Diagram:
128 | P a g e
NSS GPIO 5
RST GPIO 14
DIO0 GPIO 2
GND 3.3V
Procedure:
129 | P a g e
• Ensure the DHT11 sensor is functioning and data is being displayed on the OLED screen
connected to the transmitter.
• Open the Serial Monitor from the Arduino IDE to observe the initialization messages.
• Ensure the LoRa module is properly receiving data and the OLED screen displays the
received data.
• Check the Serial Monitor on both the transmitter and receiver to ensure data packets are
being sent and received.
• Verify that the humidity and temperature readings from the DHT11 sensor are correctly
displayed on both OLED screens.
• Use the Serial Monitor to debug any issues with sensor readings or data transmission.
• Adjust the code and connections as needed to ensure reliable communication.
• Test the range and reliability of the LoRa communication by varying the distance between
the transmitter and receiver.
• Observe the RSSI (Received Signal Strength Indicator) values on the receiver's Serial
Monitor to evaluate signal quality.
Code:
Transmitter Side:
#include <DHT.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Wire.h>
#include <SPI.h>
#include <LoRa.h>
#define DHTPIN 27
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
130 | P a g e
Serial.begin(9600);
while (!Serial);
dht.begin();
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // infinite loop to stop execution
}
display.display();
delay(2000);
display.clearDisplay();
Wire.begin();
Serial.println("LoRa Transmitter");
LoRa.setPins(csPin, resetPin, irqPin);
if (!LoRa.begin(868E6)) { // Change frequency if necessary
Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print(F("Temp: "));
display.print(t);
display.print(F(" C"));
display.setCursor(0, 20);
display.print(F("Temp: "));
display.print(f);
display.print(F(" F"));
display.setCursor(0, 40);
display.print(F("Hum: "));
131 | P a g e
display.print(h);
display.print(F(" %"));
display.display();
Serial.print(F("Hum: "));
Serial.print(h);
Serial.print(F(" % ,"));
Serial.print(F("Temp: "));
Serial.println(f);
LoRa.beginPacket();
LoRa.print(packet);
LoRa.endPacket();
delay(2000);
}
Receiver Side:
#include <SPI.h>
#include <LoRa.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
void setup() {
Serial.begin(9600);
while (!Serial);
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // infinite loop to stop execution
}
132 | P a g e
display.display();
delay(2000); // Pause for 2 seconds
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("LoRa Receiver");
display.display();
delay(1000);
Serial.println("LoRa Receiver");
LoRa.setPins(csPin, resetPin, irqPin);
display.setCursor(0, 0);
int packetSize = LoRa.parsePacket();
if (packetSize) {
while (LoRa.available()) {
received += (char)LoRa.read();
}
Serial.print(received);
display.print(received);
int rssi = LoRa.packetRssi();
Serial.print(" with RSSI ");
Serial.println(rssi);
display.print(" with RSSI ");
display.print(rssi);
display.display();
delay(1000);
}
display.clearDisplay();
}
133 | P a g e
Output:
Transmitter side:
Receiver Side:
Conclusion:
This experiment successfully demonstrated the use of LoRa technology for transmitting
humidity and temperature data from a DHT11 sensor connected to a transmitter ESP32 to a
receiver ESP32. The implementation showcased LoRa's capability for long-range
communication, using Chirp Spread Spectrum (CSS) modulation to ensure robust and
interference-resistant data transmission. The low power consumption characteristic of LoRa
enables prolonged operation on small batteries, making it ideal for remote IoT applications.
The technology's suitability for low data rate transmission was evident, as it efficiently handled
the small data packets from the sensor readings. Additionally, LoRa’s operation in the
unlicensed ISM bands allows for wide application without regulatory constraints. The
experiment's successful setup and data display on OLED screens confirmed LoRa's potential
for reliable, long-range, and low-power communication, highlighting its practicality for real-
world IoT deployments.
Applications:
• Agricultural Monitoring
• Smart Cities
134 | P a g e
• Disaster Management
• Wildlife Tracking
• Industrial Automation
• Remote Weather Stations
• Smart Home Systems
135 | P a g e
Experiment. No: 27
Title: Data Transmission using FSO
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
Introduction:
FSO or Free Space Optical communication is a line-of-sight (LoS) communication that uses a
laser beam through the free space to establish a communication link for several kilometres with
high-data rates. FSO has its potential solutions for the bottleneck and spectrum scarcity issues
since it does not require band licences unlike Traditional RF communication. Deployment of
addressed.
Since the laser beam propagates through the atmosphere (free space), it is expected to
experienceattenuation, which affects the received signal reliability.
The following experiment is conducted on a simple UART based FSO Transceiver where
Working Principle:
Transmitter:
UART Data is sent via the ESP32 Tx2 Pin to the Laser Transmitter Circuit in the IOT kit. This
signal is then amplified and used to drive the Laser diode on the side of the IOT Kit
Receiver:
The Transmitting laser is aligned with the receiver phototransistor. The Signal received by the
laser is then amplified and sent to the Rx2 Pin of the ESP32 in the IoT kit.
136 | P a g e
Block Diagram:
ESP 32 ESP 32
+ +
Photodiode LDR
Circuit Diagram:
Procedure:
• Take 2 IOT Development kits assign one as Transmitter and another as Receiver
• Upload the Transmitter code to the Transmitter IoT Kit and observe as the laser lights
up
• Power the receiver IoT kit and observe that the led on the receiver circuitry is off. If not
adjust the potentiometer on the receiver circuitry until the LED is off
137 | P a g e
• Now align the laser with the receiver phototransistor. We know that the setup is aligned
properly by observing if the Receiver circuit LED Turns on brightly
• Now upload the Receiver Code to the Receiver IOT Kit.
• Open the serial monitor and make sure the baud rate matches
• If data is not received check the laser alignment and adjust the potentiometer on the
receiver circuit
• Adjustment and alignment tips
o The Led on the receiver circuit must only light up if the laser light is incident
on the phototransistor.
o To get best results aim for the lowest point on the potentiometer where the led
almost turns off with laser beam incident on the phototransistor and then slowly
increase it.
o The potentiometer adjustment changes with different distances and baud rates
so adjustment is very important!
o Align the laser and then adjust for correct data transmission.
Code:
Transmitter Code:
#include <HardwareSerial.h>
HardwareSerial SerialPort(2);
void setup()
{
Serial.begin(1200, SERIAL_8N1,16, 17);
pinMode(2, OUTPUT);
}
void loop()
{
Serial.write("54");
Serial.println("Data Sent");
digitalWrite(2,HIGH);
delay(1000);
digitalWrite(2,LOW);
}
Receiver Code:
#include <HardwareSerial.h>
HardwareSerial SerialPort(0);
const unsigned int MAX_MESSAGE_LENGTH = 12;
//Create a place to hold the incoming message
138 | P a g e
char message[MAX_MESSAGE_LENGTH];
void Uartread()
{
//Check to see if anything is available in the serial receive buffer
while (Serial2.available() > 0)
{
static unsigned int message_pos = 0;
//Read the next available byte in the serial receive buffer
char inByte = Serial2.read();
//Message coming in (check not terminating character) and guard for over
message size
if ( inByte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1) )
{
//Add the incoming byte to our message
message[message_pos] = inByte;
message_pos++;
}
//Full message received...
else
{
//Add null character to string
message[message_pos] = '\0';
Output:
The message sent from the transmitter IoT kit i.e., “54” should be printed on the serial monitor
at the receiver side. Similarly, you can check by varying the message.
Conclusion:
This experiment successfully demonstrates the implementation of Free Space Optical (FSO)
communication using built-in transceivers in IoT kits. By establishing a line-of-sight
communication link, data was transmitted and received effectively through the atmosphere
using a laser beam. The procedure highlighted the importance of precise alignment and
potentiometer adjustment to ensure reliable signal reception. The successful bidirectional data
139 | P a g e
transmission underscores the potential of FSO technology as a viable alternative to traditional
RF communication, offering high data rates without the need for band licenses. Despite
challenges such as atmospheric attenuation, FSO presents a promising solution for addressing
bottleneck and spectrum scarcity issues in communication systems.
Applications:
• Short-Range Data Transfer
• Infrared Remote Controls
• Learning Optoelectronics
• Digital Communication Protocols
• Wireless Sensor Networks
• Internet of Things (IoT)
• Secure Communication
140 | P a g e
Experiment. No: 28
Title: Upload Sensor Data in SQLITE Database
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
• SQLite Data base
Introduction:
In this experiment, we aim to upload DHT11 sensor data into an SQLite database named
"Skdas" using an ESP32 microcontroller and Arduino IDE. The database will contain a table
named "DHT_11," where live sensor readings of temperature and humidity will be stored in
their respective columns. This setup facilitates real-time data logging, ensuring that the
collected environmental data can be accessed and analyzed for future use. By systematically
archiving these readings, we can monitor trends, make informed decisions, and potentially
identify patterns related to temperature and humidity changes over time.
Block Diagram:
Circuit Diagram:
141 | P a g e
Figure: Circuit Connections.
Pin Connections Table:
ESP32 DHT11
3.3V VCC
GND GND
GPIO 27 DATA
Procedure:
142 | P a g e
• Ensure the baud rate of the serial monitor matches the one declared in the code.
• Verify the output in serial monitor and check the data in the database table.
• Save and close the program when finished.
Code:
#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
// WiFi credentials
const char* ssid = "1011";
const char* password = "244466666";
// Server details
const char* serverName = "http://103.211.202.111/backend/main.py";
const char* username = "guest";
const char* userpassword = "guest";
const char* db_name = "Skdas";
const char* table_name = "DHT_11";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
// Connect to WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
143 | P a g e
String encoded_command = "";
for (int i = 0; i < command.length(); i++) {
char c = command.charAt(i);
if (c == ' ') {
encoded_command += "%20";
} else if (c == ',') {
encoded_command += "%2C";
} else if (c == '(') {
encoded_command += "%28";
} else if (c == ')') {
encoded_command += "%29";
} else {
encoded_command += c;
}
}
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
if (httpResponseCode == 200) {
Serial.println("Data sent successfully!");
} else {
Serial.println("Failed to send data");
}
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("Error in WiFi connection");
}
144 | P a g e
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if any reads failed and exit early (to try again).
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.println(" %");
sendData(temperature, humidity);
delay(5000); // Send data every 5 seconds
}
Output:
145 | P a g e
Figure: Output at SQLite Data base in DHT_11 Table
Conclusion:
Applications:
• Environmental Monitoring
• Smart Agriculture
• Building Automation
• Research and Development
• Healthcare Monitoring.
146 | P a g e
Experiment. No: 29
Title: Retrieve Sensor Data from SQLITE Database
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
• SQLite Data base
Introduction:
Block Diagram:
147 | P a g e
Circuit Diagram:
Procedure:
Code:
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// WiFi credentials
const char* ssid = "1011";
const char* password = "244466666";
// Server details
148 | P a g e
const char* serverName = "http://103.211.202.111/backend/main.py";
const char* username = "guest";
const char* userpassword = "guest";
const char* db_name = "Skdas";
const char* table_name = "DHT_11";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
// Connect to WiFi
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
149 | P a g e
return encodedString;
}
void retrieveData() {
// Construct the SQL command to retrieve the last 5 entries
String command = "SELECT Temperature, Humidity FROM DHT_11 ORDER BY rowid
DESC LIMIT 4";
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println("Raw Response:");
Serial.println(response);
if (!error) {
JsonArray results = doc.as<JsonArray>();
for (JsonObject row : results) {
float temperature = row["Temperature"];
float humidity = row["Humidity"];
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.println(" %");
}
} else {
150 | P a g e
Serial.println("Failed to parse JSON response");
}
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("Error in WiFi connection");
}
}
void loop() {
retrieveData(); // Retrieve and display the last 4 entries
delay(10000); // Retrieve data every 10 seconds
}
Output:
Figure: Output at Serial Monitor Data Retrieved from the data base.
151 | P a g e
Conclusion:
In conclusion, retrieving sensor data from the SQLite database "Skdas" allows us to
analyse historical temperature and humidity readings. This archived data provides valuable
insights for planning future actions, optimizing resource management, and improving
environmental monitoring strategies.
Applications:
• Trend Analysis
• Fault Diagnosis
• Energy Efficiency
• Regulatory Compliance
• Predictive Maintenance
152 | P a g e
Experiment. No: 30
Title: Remote LED Control using ESP32 / IOT Development Board Web Server
Components Used:
Hardware Used:
• DOIT ESP32 Dev Kit V1Module
• Relay Module
Software Used:
• Arduino IDE
Introduction:
This experiment involves setting up a web server on an ESP32 microcontroller to
remotely control an LED. The server provides a login interface, allowing authenticated users
to control the LED status (ON/OFF) through a web interface. The setup demonstrates basic
web server functionalities, HTML and CSS for interface design, and the use of HTTP methods
for handling user actions.
Block Diagram:
Circuit Diagram:
153 | P a g e
Pin Connections Table:
ESP32 LED
LED Pin 17
GND GND
Procedure:
• Set up Arduino IDE and ensure libraries `WiFi.h` and `WebServer.h` are installed.
• Connect the ESP32 to the appropriate WiFi network for internet access.
• Verify the circuit setup for controlling an LED or other actuators as needed.
• Define WiFi credentials for network connection and initialize an `ESP32WebServer`
instance on port 80.
• Define HTML pages (`loginPage`, `controlPage`, `incorrectCredentialsPage`) as strings
for user interface.
• Style HTML pages with basic CSS for a user-friendly interface.
• Connect ESP32 to WiFi network using defined credentials in the setup function.
• Define handlers for URL paths ("/", "/login", "/control", "/status") to manage client
requests.
• Start the web server to begin serving pages and handling client interactions.
• Continuously handle client requests using `server.handleClient()` in the loop function.
• Implement `handleRoot()`, `handleLogin()`, `handleControl()`, and `handleStatus()`
functions to manage page rendering and user interactions.
• Ensure the code compiles without errors and upload it to the ESP32.
• Ensure the baud rate of the serial monitor matches the one declared in the code.
• Check Wi-Fi connectivity by verifying the IP address printed in the serial monitor.
• Confirm the web server serves the login page ("/") and test login functionality with
correct and incorrect credentials.
• Test LED control functionality on the control page to verify if the LED turns ON/OFF as
expected.
• Validate dynamic status updates on the control page using AJAX requests for real-time
updates.
• Analyse system behaviour through thorough testing, ensuring consistent responses from
the ESP32.
154 | P a g e
• Optimize performance and user experience by adjusting code and configurations as
necessary.
• Verify the overall functionality of the ESP32-based web server for controlling devices
and monitoring status updates.
• Save and close the Arduino IDE program once testing and validation are complete.
Code:
#include <WiFi.h>
#include <WebServer.h>
155 | P a g e
.button { padding: 15px 30px; border: 1px solid ccc; border-radius: 4px;
background-color: rgba(0, 123, 255, 0.5); color: white; cursor: pointer;
transition: background-color 0.3s; margin: 10px; }\
.button:hover { background-color: rgba(0, 123, 255, 0.7); }\
</style>\
<script>\
function updateLEDStatus() {\
var xhr = new XMLHttpRequest();\
xhr.open('GET', '/status', true);\
xhr.onreadystatechange = function () {\
if (xhr.readyState == 4 && xhr.status == 200) {\
document.getElementById('led-status').innerText = xhr.responseText;\
}\
};\
xhr.send();\
}\
setInterval(updateLEDStatus, 100);\
</script>\
</head>\
<body onload='updateLEDStatus()'>\
<h1>NATIONAL INSTITUTE OF TECHNOLOGY , ROURKELA</h1>\
<div id='led-status'>Loading...</div>\
<form action='/control' method='post'>\
<input type='submit' name='LED' value='ON' class='button'>\
<input type='submit' name='LED' value='OFF' class='button'>\
</form>\
</body>\
</html>";
156 | P a g e
const char* correctPassword = "password";
if (server.method() == HTTP_POST) {
String username = server.arg("username");
String password = server.arg("password");
if (ledState == "ON") {
digitalWrite(ledpin, HIGH);
server.send(200, "text/html", controlPage);
} else if (ledState == "OFF") {
digitalWrite(ledpin, LOW);
server.send(200, "text/html", controlPage);
} else {
server.send(400, "text/html", "<html><body>Bad Request</body></html>");
}
} else {
server.send(405, "text/html", "<html><body>Method Not
Allowed</body></html>");
}
}
157 | P a g e
server.send(200, "text/plain", "LED is ON");
} else {
server.send(200, "text/plain", "LED is OFF");
}
}
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, LOW);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.on("/login", handleLogin);
server.on("/control", handleControl);
server.on("/status", handleStatus);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}
Output:
Serial Monitor Output –
20:45:23.536 -> Connecting......
20:45:30.488 -> Connected to WiFi
20:45:30.519 -> IP Address: 192.168.80.80
20:45:30.558 -> HTTP server started
Figure: Serial Monitor Output when the ESP32 connects to an WiFi server
158 | P a g e
Conclusion:
This experiment demonstrates a simple yet functional implementation of a web server
on the ESP32 to control an LED. The use of HTML, CSS, and JavaScript provides a user-
friendly interface, while the ESP32 handles server-side logic and hardware control. This setup
can be extended to include additional sensors and actuators for more complex IoT applications.
Applications:
• Home Automation
• Smart Agriculture
• Industrial Automation
• Security Systems
• Environmental Monitoring
• Educational Projects
• Smart Offices
• Health and Fitness
• Automotive Applications
• Remote Diagnostics
159 | P a g e
Experiment. No: 31
Title: Development of weather station.
Components Used:
Hardware Used:
• DOIT ES32 Devkit V1 Module
• GSMA7672s
• BMP085(Barometric Sensor)
• DHT11 (Temperature and Humidity Sensor)
• 0.96” OLED Display
Software Used:
• Arduino IDE
Introduction:
This project involves setting up an ESP32 microcontroller to monitor and log
environmental data using various sensors. The primary sensors used are a DHT11 for
temperature and humidity measurements, and an Adafruit BMP180 for barometric pressure
readings. Additionally, an OLED display is utilized to provide real-time feedback of the sensor
readings. The collected data is then transmitted to ThingSpeak, a cloud-based IoT analytics
platform, for remote monitoring and analysis.
Block Diagram:
160 | P a g e
Circuit Diagram:
BMP180 ESP32
VCC 3.3V
GND GND
SCL GPIO 22
SDA GPIO 21
161 | P a g e
Procedure:
• Install Arduino IDE: Download and install the Arduino IDE from the [official Arduino
website](https://www.arduino.cc/en/software) and open it after installation.
• Set up ThingSpeak: Go to the [ThingSpeak website](https://thingspeak.com/) and create
an account if needed, log in, click on Channels > My Channels > New Channel, enter a
name and description (optional), enable the necessary fields for your data, and save the
channel.
• Include necessary libraries: Include libraries for WiFi, HTTP client, DHT sensor,
BMP180 sensor, and OLED display in the code.
• Configure WiFi and ThingSpeak: Define WiFi credentials (SSID and password) and
define ThingSpeak channel ID and API key.
• Initialize components: Initialize the serial monitor for debugging, initialize the DHT11
sensor, initialize the BMP180 sensor, initialize the OLED display, initialize the WiFi
connection and wait until connected.
• Read sensor data: Read temperature and humidity from the DHT11 sensor and read
pressure from the BMP180 sensor.
• Display data on OLED: Clear the OLED display and print the sensor data (temperature,
pressure, humidity) on the OLED screen.
• Send data to ThingSpeak: Construct the URL for the ThingSpeak update request and send
the HTTP GET request to the ThingSpeak server with the sensor data.
• Repeat the process: Wait for a specified period (e.g., 20 seconds) before repeating the
process to read, display, and send new data
Code:
#include <Wire.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <Adafruit_BMP085.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// WiFi credentials
const char* ssid = "ssid";
const char* password = "password";
// ThingsSpeak settings
const char* server = "api.thingspeak.com";
const char* apiKey = "apikey";
162 | P a g e
const int channelID = channelid;
// DHT11 settings
#define DHTPIN 27
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// BMP180 settings
Adafruit_BMP085 bmp;
// OLED settings
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" connected");
// Initialize DHT11
dht.begin();
// Initialize BMP180
if (!bmp.begin()) {
Serial.println("Could not find a valid BMP180 sensor, check wiring!");
while (1) {}
}
// Initialize OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for
128x64
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(SSD1306_WHITE); // Draw white text
display.setCursor(0, 0); // Start at top-left corner
display.print("Initializing...");
display.display();
}
void loop() {
// Read data from DHT11
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
163 | P a g e
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Read data from BMP180
float pressure = bmp.readPressure() / 100.0F; // hPa
// Print data to serial monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" *C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("Pressure: ");
Serial.print(pressure);
Serial.println(" hPa");
// Update OLED display
display.clearDisplay();
display.setCursor(0, 0);
display.print("Temperature: ");
display.print(temperature);
display.println(" *C");
display.print("Humidity: ");
display.print(humidity);
display.println(" %");
display.print("Pressure: ");
display.print(pressure);
display.println(" hPa");
display.display();
// Send data to ThingsSpeak
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String("http://") + server + "/update?api_key=" + apiKey +
"&field1=" + String(temperature) + "&field2=" + String(humidity) + "&field3="
+ String(pressure);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println("Data sent to ThingsSpeak: " + payload);
} else {
Serial.println("Error in sending data to ThingsSpeak");
}
http.end();
}
// Wait 20 seconds to send next data
delay(20000);
}
164 | P a g e
Output:
Conclusion:
This project successfully demonstrates the integration of an ESP32 microcontroller
with DHT11 and BMP180 sensors for comprehensive environmental monitoring. By
displaying real-time data on an OLED screen and transmitting it to ThingSpeak, the system
offers both local and remote access to temperature, humidity, and barometric pressure readings.
This setup not only provides immediate visual feedback but also facilitates long-term data
analysis through cloud storage. The successful implementation highlights the potential of IoT
165 | P a g e
technologies in enhancing environmental monitoring, making data-driven decisions, and
improving resource management. As IoT technologies continue to evolve, such systems will
become even more effective and accessible, contributing to more informed and sustainable
practices.
Applications:
• Home weather station display
• Indoor climate monitoring system
• Temperature and humidity monitor for a greenhouse
• Environmental monitoring in a server room or data center
• Personalized weather display for a smart mirror
• Educational project for teaching about sensors and displays
166 | P a g e
Experiment. No: 32
Title: IMU Data Monitoring using Arduino, HTML, and Node.js
Components Used:
Hardware Used:
Software Used:
• Arduino IDE
• HTML
• Node.js
Introduction:
This project demonstrates a system for monitoring Inertial Measurement Unit (IMU)
data using an MPU9250 sensor connected to an Arduino. The data is sent to a local server and
displayed on a web page. Additionally, the data is also sent to ThingSpeak for remote
monitoring. The system uses Arduino for data collection, a Node.js server for data handling,
and an HTML page for displaying the data.
The MPU9250 sensor is an IMU that measures acceleration, gyroscopic rotation, and
magnetic field in three axes. The data from this sensor can be used in various applications such
as motion tracking, gesture detection, and orientation measurement. Arduino is used to
interface with the MPU9250 and send the data to a server. The server, built with Node.js,
handles the data and makes it available for visualization on a web page. ThingSpeak is used
for remote monitoring and data storage.
167 | P a g e
Block Diagram:
Circuit Diagram:
168 | P a g e
Pin Connections Table:
IMU (MPU9250) ESP32
VCC 3.3V
GND GND
SCL GPIO 22
SDA GPIO 21
INT GND
FSYNC GND
Procedure:
o your-project/
o ├── public/
o │ └── index.html
o └── server.js
o npm init -y
o body-parser axios ws
o npm install ws
• Place the updated HTML file into the public directory. Fig3.b
• Run the server: In the folder right click and open terminal then type -
o node server.js
browser.
169 | P a g e
Software Implementation:
170 | P a g e
Code:
ESP 32 Code:
#include <Wire.h>
#include <MPU9250_asukiaaa.h>
#include <WiFi.h>
#include <HTTPClient.h>
MPU9250_asukiaaa myIMU;
void setup() {
Serial.begin(115200);
Wire.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
myIMU.setWire(&Wire);
myIMU.beginAccel();
myIMU.beginGyro();
myIMU.beginMag();
}
void loop() {
myIMU.accelUpdate();
myIMU.gyroUpdate();
myIMU.magUpdate();
171 | P a g e
",\"gyroX\":" + String(gyroX) + ",\"gyroY\":" +
String(gyroY) + ",\"gyroZ\":" + String(gyroZ) + "}";
if (WiFi.status() == WL_CONNECTED) {
HTTPClient httpLocal;
httpLocal.begin(serverName);
httpLocal.addHeader("Content-Type", "application/json");
int httpResponseCodeLocal = httpLocal.POST(postDataLocal);
if (httpResponseCodeLocal > 0) {
Serial.print("Local server response code: ");
Serial.println(httpResponseCodeLocal);
} else {
Serial.print("Error on sending data to local server: ");
Serial.println(httpResponseCodeLocal);
}
httpLocal.end();
} else {
Serial.println("WiFi not connected");
}
httpThingSpeak.begin(url);
int httpResponseCodeThingSpeak = httpThingSpeak.GET();
if (httpResponseCodeThingSpeak == 200) {
Serial.println("Data sent to ThingSpeak");
} else {
Serial.print("Error on sending data to ThingSpeak: ");
Serial.println(httpResponseCodeThingSpeak);
}
httpThingSpeak.end();
}
delay(100);
}
172 | P a g e
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sensor Data</title>
<script>
document.addEventListener('DOMContentLoaded', () => {
const ws = new WebSocket('ws://localhost:3000');
ws.onmessage = event => {
const data = JSON.parse(event.data);
document.getElementById('accelX').innerText = data.accelX;
document.getElementById('accelY').innerText = data.accelY;
document.getElementById('accelZ').innerText = data.accelZ;
document.getElementById('gyroX').innerText = data.gyroX;
document.getElementById('gyroY').innerText = data.gyroY;
document.getElementById('gyroZ').innerText = data.gyroZ;
};
ws.onopen = () => {
console.log('WebSocket connection opened');
};
ws.onclose = () => {
console.log('WebSocket connection closed');
};
ws.onerror = error => {
console.error('WebSocket error:', error);
};
});
</script>
</head>
173 | P a g e
<body>
<h1>Sensor Data</h1>
<div>
<p>Accel X: <span id="accelX"></span></p>
<p>Accel Y: <span id="accelY"></span></p>
<p>Accel Z: <span id="accelZ"></span></p>
<p>Gyro X: <span id="gyroX"></span></p>
<p>Gyro Y: <span id="gyroY"></span></p>
<p>Gyro Z: <span id="gyroZ"></span></p>
</div>
</body>
</html>
Node.js Code:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const axios = require('axios');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const port = 3000;
174 | P a g e
let sensorData = {};
// WebSocket connection
wss.on('connection', ws => {
console.log('Client connected');
ws.on('close', () => {
console.log('Client disconnected');
});
});
175 | P a g e
try {
const response = await axios.get(thingSpeakUrl, {
params: {
field1: sensorData.accelX,
field2: sensorData.accelY,
field3: sensorData.accelZ,
field4: sensorData.gyroX,
field5: sensorData.gyroY,
field6: sensorData.gyroZ,
}
});
console.log('Data sent to ThingSpeak:', response.data);
} catch (error) {
console.error('Error sending data to ThingSpeak:', error);
}
// Broadcast the received data to all WebSocket clients
broadcastData(sensorData);
res.sendStatus(200);
});
Protocols Used:
JSON (JavaScript Object Notation): JSON is an open standard file format and data
interchange format that uses human-readable text to store and transmit data objects consisting
of attribute–value pairs and arrays (or other serializable values). In this project, JSON is used
to format the IMU data for transmission between the Arduino and the server, and between the
server and ThingSpeak.
Output:
Figure: 7 Server Showing realtime data and updating every 1000ms or 1 seconds
Figure 8. Node.js server started and values are being updated and displayed
177 | P a g e
Figure 9.a Acceleration x-axis field in ThingSpeak
178 | P a g e
Figure 10.a Gyroscopic Acceleration x-axis field in ThingSpeak
179 | P a g e
• Figures 7 and 8 showing the server displaying real-time data and updating every
1000ms (1 second)
• Figures 9.a to 9.c showing the acceleration data fields (x, y, z) in ThingSpeak
• Figures 10.a to 10.c showing the gyroscopic data fields (x, y, z) in ThingSpeak
Conclusion:
This project successfully demonstrates how to monitor IMU data using an Arduino, a
local Node.js server, and an HTML interface. The data is also sent to ThingSpeak for remote
monitoring. This system can be used in various applications requiring real-time motion tracking
and environmental monitoring.
Applications:
180 | P a g e
Experiment. No: 33
Title: Relay toggling using ThingSpeak
Components Used:
Hardware Used:
• ESP32
• LED
• Resistor
Software Used:
• Arduino IDE
• ThingSpeak
Introduction:
In this experiment, you will learn how to control a relay module remotely using
an ESP32 microcontroller and the ThingSpeak cloud platform. The ESP32,
known for its built-in Wi-Fi and Bluetooth capabilities, will be programmed to
monitor a ThingSpeak channel for commands to toggle the relay on or off.
ThingSpeak serves as the cloud-based intermediary, enabling you to send
commands from anywhere using a web browser or mobile device. When the
ESP32 receives a command via ThingSpeak, it activates or deactivates the relay,
allowing you to control appliances like lights or fans remotely. This experiment
demonstrates the basics of IoT (Internet of Things) applications, providing a
practical introduction to home automation and remote device management.
Block Diagram:
Circuit Diagram:
Pin Connections Table
181 | P a g e
Procedure:
• Install Arduino IDE and set it up to ESP32 environment.
• Install ThingSpeak Library and WiFi.h library.
• Create a ThingSpeak account and login into ThingSpeak (https://www.thingspeak.com)
• Create a new channel in ThingSpeak with name “LED ON OFF” and one field names
“LED”.
182 | P a g e
Figure 4. Creating a widget
• Select the target hardware from the Tools->Board menu
• Now, upload the code given below after few necessary changes are done.
1. Change SSID and PASSWORD for internet connection you are using
2. Change channel number, WriteAPI and ReadAPI keys from channel you created.
3. Change the LED Pin number according to your circuit.
Code:
#include <WiFi.h>
#include "ThingSpeak.h"
183 | P a g e
int number = 0;
int ledPin = 13;
void setup() {
Serial.begin(9600);
while (! Serial) {
;
}
pinMode(13,OUTPUT);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, pass);
Serial.print(".");
delay(5000);
}
Serial.println("\nConnected.");
}
number = ThingSpeak.readLongField(myChannelNumber, 1, myReadAPIKey);
if(number == 1){
digitalWrite(13, LOW);
} else {
digitalWrite(13, HIGH);
}
int x = ThingSpeak.writeField(myChannelNumber, 1, digitalRead(13),
myWriteAPIKey);
if(x == 200){
Serial.println("Update successful");
}
else{
Serial.println("Error"+String(x));
}
delay(15000);
}
184 | P a g e
Output:
185 | P a g e
Conclusion:
In this experiment, we successfully demonstrated data transmission using Wi-Fi to ThingSpeak
by controlling an LED with an ESP32 microcontroller. The setup involved configuring the
Arduino IDE for ESP32, setting up a ThingSpeak channel, and creating a widget to monitor
the LED status. The provided code allowed the ESP32 to connect to a Wi-Fi network, read
control signals from the ThingSpeak channel, and adjust the LED state accordingly.
Additionally, the code updated the ThingSpeak channel with the current LED state every 20
seconds, ensuring real-time monitoring and control. This experiment highlights the practicality
and ease of integrating IoT devices with cloud-based platforms for remote monitoring and
control applications.
186 | P a g e