0% found this document useful (0 votes)
41 views

IoT_Applications_Practical_Approach_final

The document outlines practical experiments related to IoT applications using the ESP32 microcontroller and Arduino IDE. It includes a detailed index of experiments ranging from basic LED control to advanced sensor data reading and transmission techniques. Each experiment provides components used, procedures, code examples, and applications, facilitating hands-on learning in IoT development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

IoT_Applications_Practical_Approach_final

The document outlines practical experiments related to IoT applications using the ESP32 microcontroller and Arduino IDE. It includes a detailed index of experiments ranging from basic LED control to advanced sensor data reading and transmission techniques. Each experiment provides components used, procedures, code examples, and applications, facilitating hands-on learning in IoT development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 186

IoT and it’s Applications: A Practical

Approach

First Edition

Santos Kumar Das

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

33. 33 Relay toggling using ThingSpeak 181-186

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:

• Go to Tools > Board > Boards Manager.

Install ESP32 Platform:

• In the Boards Manager window, type esp32 into the search bar.

• Locate esp32 by Express if Systems and click the Install button.

5|Page
Select Your ESP32 Board:

• Once the installation is complete, go to Tools > Board.

• Scroll down to the "ESP32 Arduino" section and select your specific ESP32 board (e.g.,
"ESP32 Dev Module").

6|Page
Install the Drivers:

• Go to the Silicon Labs CP210x driver download page.


Link for drivers
• Select the appropriate driver for your operating system
• Download the driver package in zip
• Extract the download files.
• Then go to device manager in your PC
• Select the port shown their and update the port to your PC .

Select the Correct Port:

• Go to Tools > Port.

• Their select the available port

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:

Pin Connections: No connections Required

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);

// check if the pushbutton is pressed. If it is, the buttonState is HIGH:


if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}

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:

• DOIT ESP32 DevKit V1Module


• DHT11 Module

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:

Figure: Block diagram of the overall system

12 | P a g e
Circuit Diagram:

Figure: Circuit of DHT 11and ESP32

Pin Connections Table:


DHT11 ESP32
GND GND
VCC 3.3V
DATA GPIO 27

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"

// Define the pin where the DHT11 is connected


#define DHTPIN 27

// Define the type of sensor in use


#define DHTTYPE DHT11

// Initialize DHT sensor


DHT dht(DHTPIN, DHTTYPE);

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);

// Reading temperature or humidity takes about 250 milliseconds!


float humidity = dht.readHumidity();
float 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;
}
// 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:

Figure: Output at Serial Monitor

Figure: indicating ESP32 and DHT11 sensor

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:

• Home Automation Systems


• Weather Stations

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:

Figure: Block diagram of the overall system

Circuit Diagram:

Figure: Circuit of BMP 180 and ESP32

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>

// Create an instance of the sensor


Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified (10085);

void setup () {
Serial.begin(115200);
Serial.println("BMP180 Sensor Test");

// Initialize the sensor


if (! bmp.begin()) {
Serial.print("Could not find a valid BMP180 sensor, check wiring!");
while (1) {}
}
}
void loop () {
sensors_event_t event;
bmp.getEvent(&event);

17 | P a g e
if (event.pressure) {
// Display the pressure in hPa
Serial.print("Pressure: ");
Serial.print(event.pressure);
Serial.println(" hPa");

// Calculate and display altitude


float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;
Serial.print("Altitude: ");
Serial.print(bmp.pressureToAltitude(seaLevelPressure, event.pressure));
Serial.println(" m");
// Calculate and display temperature
float temperature;
bmp.getTemperature(&temperature);
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" C");
} else {
Serial.println("Sensor error");
}
Delay (2000);
}

Output:

Figure: Output in Serial Monitor

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:

• Weather Monitoring Systems


• Environmental Data Logging
• Altitude Estimation

19 | P a g e
Experiment. No: 06
Title: Reading IMU Sensor data and display it on Serial Monitor

Components Used:
Hardware Used:

• DOIT ESP32 DevKit V1Module


• IMU(MPU9250) Module

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:

Figure: Block diagram of the overall system

Circuit Diagram:

Figure: Circuit of MPU9250 and ESP32


20 | P a g e
Pin Connections Table:
IMU (MPU9250) ESP32
GND GND
VCC 3.3V
SCL GPIO 22
SDA GPIO 21
FSYNC GND
INT GND

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();

Serial.print("Accel X: "); Serial.print(accelX); Serial.print(" m/s^2, ");


Serial.print("Y: "); Serial.print(accelY); Serial.print(" m/s^2, ");
Serial.print("Z: "); Serial.print(accelZ); Serial.println(" m/s^2");

Serial.print("Gyro X: "); Serial.print(gyroX); Serial.print(" rad/s, ");


Serial.print("Y: "); Serial.print(gyroY); Serial.print(" rad/s, ");
Serial.print("Z: "); Serial.print(gyroZ); Serial.println(" rad/s");
delay (1000);
}
Output:

Figure: Output in Serial Monitor

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:

1. DOIT ESP32 DevKit V1Module


2. OLED’96 Display

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:

Figure: Block diagram of the overall system

23 | P a g e
Circuit Diagram:

Figure: Circuit of .96” OLED DISPLAY and ESP32

Pin Connections Table:

.96” OLED DISPLAY ESP32


GND GND
VCC 3.3V
SCL GPIO 22
SDA GPIO 21
Procedure:

• Open the Arduino IDE.


• Paste the code and download the required libraries (Adafruit_GFX, Adafruit_SSD1306,
WiFi) from the Library Manager.
• Compile the code.
• Upload the code to the microcontroller.
• Ensure the baud rate of the serial monitor matches the one declared in the code.
• Type Enter text into the serial monitor and press "Enter" to display it on the OLED
screen.
• Save and close the program when finished.

Code:

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

#define SCREEN_WIDTH 128 // OLED display width, in pixels


#define SCREEN_HEIGHT 64 // OLED display height, in pixels

24 | P a g e
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
// Initialize Serial communication
Serial.begin(115200);

// Initialize OLED display


if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}

// Clear the buffer


display.clearDisplay();
display.display();
}

void loop() {
if (Serial.available() > 0) {
String input = Serial.readStringUntil('\n');

// Clear the display buffer


display.clearDisplay();

// Set text size, color and cursor position


display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);

// Display the input from the serial monitor


Serial.println(input);
display.println(input);
display.display();
}
}
Output:

Figure: Output at Serial Monitor

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:

Figure: Block diagram of the overall system

Circuit Diagram:

Figure: Circuit diagram

27 | P a g e
Pin Connections Table
ESP32 DHT11
3.3V VCC
GND GND
GPIO 27 DATA

.96” OLED DISPLAY ESP32


GND GND
VCC 3.3V
SCL GPIO 22
SDA GPIO 21

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);

#define SCREEN_WIDTH 128


#define SCREEN_HEIGHT 64
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define SCREEN_ADDRESS 0x3C

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);

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


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

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:

Figure: Output at Serial Monitor

Figure: Output at Kit

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:

• BMP180 Barometric Pressure Sensor Module


• ESP32 Development Board
• 0.96’’ OLED Display

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:

Figure: Block diagram of the overall system

32 | P a g e
Circuit Diagram:

Figure: Circuit Connections

Pin Connections Table

BMP180 ESP32
VCC 3.3V
GND GND
SCL GPIO 22
SDA GPIO 21

.96” OLED DISPLAY ESP32


GND GND
VCC 3.3V
SCL GPIO 22
SDA GPIO 21
Procedure:
• Connect BMP180 and OLED to ESP32 using specified GPIO pins.
• Set up Arduino IDE and install required libraries.
• Select the appropriate board and port in Arduino IDE.
• Verify and upload the provided code to the ESP32.
• Open the Serial Monitor and set the baud rate to 115200.
• Ensure BMP180 and OLED display initialize correctly.
• Observe sensor data on Serial Monitor and OLED display.
• Record pressure, altitude, and temperature readings.
• Analyze the recorded data for consistency and accuracy.

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>

Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

#define SCREEN_WIDTH 128


#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define SCREEN_ADDRESS 0x3C

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");

display.display(); // Show the display buffer on the screen

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:

Figure: Output at Serial Monitor

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:

• Weather Monitoring Stations


• Flight Altitude Measurement
• Environmental Research

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:

Figure: Block diagram of the overall system

37 | P a g e
Circuit Diagram:

Figure: Circuit Connections

Pin Connections Table:


IMU (MPU9250) ESP32
VCC 3.3V
GND GND
SCL GPIO 22
SDA GPIO 21
INT GND
FSYNC GND

.96” OLED DISPLAY ESP32


GND GND
VCC 3.3V
SCL GPIO 22
SDA GPIO 21

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>

#define SCREEN_WIDTH 128


#define SCREEN_HEIGHT 64

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);


MPU9250_asukiaaa myIMU;

void setup () {
Serial.begin(115200);
Wire.begin();

// Initialize IMU
myIMU.setWire(&Wire);
myIMU.beginAccel();
myIMU.beginGyro();

// Initialize OLED display


if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.display();
delay(2000); // Pause for 2 seconds

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:

Figure: Output readings of IMU sensor on OLED Display.

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:

Figure: Block diagram of the overall system

42 | P a g e
Circuit Diagram:

Figure: Circuit Diagram

Pin Connections Table


RELAY ESP32
RELAY TRIGGER PIN GPIO 13

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>

int relayPin = 13;


bool LED = false;
void setup() {
Serial.begin(9600);
pinMode(relayPin, OUTPUT);
}
void loop() {
LED = !LED;
digitalWrite(relayPin, LED ? HIGH : LOW);
Serial.print("LED Status:");
Serial.println(LED ? "ON" : "OFF");
delay(5000);
}

Output:

Figure: Output in Serial Monitor

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:

Figure: Block diagram of the overall system

46 | P a g e
Circuit Diagram:

Figure: Circuit Diagram

Pin Connections Table


ESP32 LM386
3.3V VDD
GND GND
GPIO25 IN

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);
}

// Adjust the volume


if (Serial.available()) {
int newVolume = Serial.parseInt();
if (newVolume >= 0 && newVolume <= 255) {
maxDutyCycle = newVolume;
Serial.print("Volume set to: ");
Serial.println(maxDutyCycle);
} else {
Serial.println("Invalid volume. Enter a value between 0 and 255.");
}
}
}

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:

• DOIT ESP32 DevKit V1Module


• DHT11 Module
• Audio Amplifier Module (LM386)

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:

Figure: Block diagram of the overall system

50 | P a g e
Circuit Diagram:

Pin Connections Table:

AUDIO AMPLIFIER MODULE ESP32


VCC 5V
IN GPIO 25
GND GND
GND GND

DHT11 ESP32
GND GND
VCC 3.3V
DATA GPIO 27

Procedure:

• Install Arduino IDE and set up the environment for ESP32.


• Connect Data pin of DHT11 sensor to GPIO27 of ESP32.
• Connect INPU pin of LM386 sensor to GPIO25 of ESP32.
• Install `DHT.h`, `Adafruit_Sensor.h`, and `DHT_U.h` libraries in the Arduino IDE.
51 | P a g e
• Use the provided code to find out the temperature of the surroundings using DHT11
sensor and to activate the alarm when the temperature reaches above the threshold that
we set.
• 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 <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>

#define DHTPIN 27 // Pin where the DHT11 is connected


#define DHTTYPE DHT11 // DHT 11
#define ALARM_PIN 25 // Pin where the LM386 amplifier is connected
#define TEMP_THRESHOLD 30 // Temperature threshold for the alarm

DHT dht (DHTPIN, DHTTYPE);

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();

// Check if any reads failed


if (isnan(temp)) {
Serial.println("Failed to read from DHT sensor!");
return;

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:

Figure: Output in Serial Monitor

53 | P a g e
Figure: Indicating ESP32, DHT11 sensor and LM386 sensor

Conclusion:

The integration of high-temperature alarm systems represents a proactive approach to


managing the risks associated with rising temperatures. These systems not only provide
immediate alerts that can prevent disasters but also contribute to long-term safety and
sustainability in various sectors. As technology continues to advance, the effectiveness and
accessibility of these systems are likely to improve, offering even greater protection against the
challenges posed by extreme heat. Investing in and adopting high-temperature alarm systems
is a crucial step towards ensuring a safer, more resilient future in the face of climate change.

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:

Figure: Block diagram of the overall system

55 | P a g e
Circuit Diagram:

Figure: Circuit Connections


Pin Connections Table:
IMU (MPU9250) ESP32
VCC 3.3V
GND GND
SCL GPIO 22
SDA GPIO 21
INT GND
FSYNC GND

AUDIO AMPLIFIER MODULE ESP32


VCC 5V
IN GPIO 25
GND GND
GND GND

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;

const float threshold = 5; // Adjusted low threshold value for detecting


movement
const int beepPin = 25; // Pin connected to LM386 IN
bool alarmActivated = false;
unsigned long lastMovementTime = 0;

void setup() {
Serial.begin(115200);
Wire.begin();

myIMU.setWire(&Wire);
myIMU.beginAccel();
myIMU.beginGyro();

pinMode(beepPin, OUTPUT); // Set the beep pin as output


digitalWrite(beepPin, LOW); // Ensure beep pin is initially low
}

void loop() {
}
myIMU.accelUpdate();

57 | P a g e
float accelX = myIMU.accelX();
float accelY = myIMU.accelY();
float accelZ = myIMU.accelZ();

// Calculate magnitude of acceleration vector


float accelMagnitude = sqrt(accelX * accelX + accelY * accelY + accelZ *
accelZ);

// Check if magnitude exceeds threshold


if (accelMagnitude > threshold) {
Serial.println("Movement detected!");
tone(beepPin, 1000); // Generate a beep sound immediately
lastMovementTime = millis(); // Record the time of the movement detection
alarmActivated = true;
Serial.println("ALARM activated!");
} else {
noTone(beepPin); // Turn off beep sound if below threshold
}

delay(10); // Small delay to stabilize readings (optional)


}

Output:

Figure: Output in Serial Monitor

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:

Figure: Block diagram of the overall system

Circuit Diagram:

Figure: 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

Micro SD card module ESP32


3V3 3.3V
CS GPIO 4
MOSI GPIO 23
CLK GPIO 18
MISO GPIO 19
GND GND

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>

#define SCREEN_WIDTH 128


#define SCREEN_HEIGHT 64
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C
#define CS_PIN 5

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

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);

File myFile = SD.open("/hex.txt");


if (myFile) {
String hexNumber = "";
while (myFile.available()) {
hexNumber += (char)myFile.read();

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:

• Displaying diagnostic or configuration data stored in hexadecimal format.

• To display the reading of sensor data on OLED.

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:

• ESP32 Development Board


• DHT11 Temperature and Humidity Sensor
• MICROSD CARD MODULE
• SD Card

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:

Figure: Block diagram of the overall system

65 | P a g e
Circuit Diagram:

Figure: Circuit Diagram


Pin Connections Table:

MICROSD CARD ESP32


MODULE
3V3 3.3V
CS GPIO 4
MOSI GPIO 23
CLK GPIO 18
MISO GPIO 19
GND GND

Procedure:

• Connect the DHT11 sensor to the ESP32.


• Connect the SD card module to the ESP32 as per the pin diagram.
• Install the required libraries in the Arduino IDE:
o DHT
o SD
• Create an Arduino sketch to read data from the DHT11 sensor and write to the SD card.
• Create an HTML page to interact with the ESP32.
• Open the Arduino IDE.
• Install the required libraries: DHT, SD, WiFi.
• Connect the ESP32, DHT11 sensor, and SD card module as per the pin diagram.
66 | P a g e
• Copy the provided Arduino sketch into the Arduino IDE.
• Update the WiFi credentials in the code (ssid and password).
• Upload the code to the ESP32.
• After uploading, open a serial monitor to get the IP address of the ESP32.
• Open a web browser and enter the IP address.
• Click the "Read & Write Data" button to read data from the DHT11 sensor and write it
to the SD card. The result will be displayed on the web page.

Code:

Arduino (AmpServer.ino):

#include <SD.h>
#include <SPI.h>
#include <WiFi.h>
#include <DHT.h>

#define DHTPIN 4
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

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:

• Environmental monitoring systems.


• Data logging for weather stations.

69 | P a g e
Experiment. No: 17
Title: Display Sensor Data on Mobile Application using Bluetooth

Components Used:

Hardware Used:

• ESP32 Development Board


• DHT11 Temperature and Humidity Sensor

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:

Figure: Block diagram of the overall system

70 | P a g e
Circuit Diagram:

Figure: Circuit Diagram


Pin Connections Table
ESP32 DHT11
3.3V VCC
GND GND
GPIO 27 DATA

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

DHT dht(dhtPin, DHTTYPE);


BluetoothSerial SerialBT;

void setup() {
Serial.begin(115200);
SerialBT.begin("DHT11");
dht.begin();
}

void loop() {

float temperature = dht.readTemperature(); // Read temperature value in


float humidity = dht.readHumidity(); // Read humidity value

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:

Figure: Temperature and Humidity displayed on Serial Monitor

Figure: Temperature and Humidity displayed on Bluetooth Terminal Mobile Application

Conclusion:

In this experiment, we successfully interfaced a DHT11 sensor with an ESP32 microcontroller


and transmitted temperature and humidity data via Bluetooth to a mobile application. This
setup allows for effective remote monitoring of environmental conditions.

Applications:

• Home automation systems for climate control.


• Remote weather monitoring stations.
• Smart agriculture for monitoring greenhouse conditions.

73 | P a g e
Experiment. No: 18
Title: Relay control using Blynk IoT mobile app/Web app

Components Used:

Hardware Used:

1. DOIT ESP32 Dev Kit V1Module


2. Relay
3. LED - Bulb

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:

Figure: Block diagram of the overall system

74 | P a g e
Circuit Diagram:

Figure: Circuit Diagram

Pin Connections Table

RELAY ESP32
RELAY TRIGGER PIN GPIO 13
VCC 3.3V
GND GND

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.

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".

• Go to the "Web Dashboard" section to create an interface.


• From the Widget Box on the left, drag the switch 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., 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.

• 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.

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>

// Your WiFi credentials.


char ssid[] = "1011";
char pass[] = "244466666";

// Blynk Auth Token


char auth[] = "uTodbIY3sZKdL9ENxUnCAs-M-eKvGOfS";

// Relay pin
#define RELAY_PIN 13

void setup() {
// Debug console
Serial.begin(115200);

// Set relay pin as output


pinMode(RELAY_PIN, OUTPUT);

// Print WiFi connection attempt


Serial.println("Connecting to WiFi...");

// Initialize WiFi connection


WiFi.begin(ssid, pass);

// Wait for connection

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);

// Attempt to connect to Blynk server


if (Blynk.connect()) {
Serial.println("Connected to Blynk server");
} else {
Serial.println("Failed to connect to Blynk server");
}
}

// 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:

Figure: LED ON controlled using Blynk IoT Mobile Application

Figure: LED ON controlled using Blynk IoT Mobile Application

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:

Figure: Block diagram of overall system

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) + " &#8451;</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:

Figure: Output of the DHT 11 sensor readings displaying on ESP 32 Web-Server.

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:

• DOIT ESP32 DevKit V1Module


• DHT11 Temperature Sensor Module

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:

Figure: Block diagram of the overall system

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:

• DOIT ESP32 Dev Kit V1Module


• OLED’96 Display

Software Used:

• Arduino IDE
• Thing Speak

Introduction:

In this experiment, we aim to integrate an ESP32-based system with the ThingSpeak


cloud platform to monitor and display environmental data such as temperature, pressure, and
humidity. By leveraging the capabilities of WiFi connectivity and OLED display technology,
we create a real-time data acquisition and visualization system.

Block Diagram:

Figure: Block diagram of the overall system

93 | P a g e
Circuit Diagram:

Figure: Circuit of .96” OLED DISPLAY and ESP32

Pin Connections Table:


.96” OLED DISPLAY ESP32
GND GND
VCC 3.3V
SCL GPIO 22
SDA GPIO 21

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";

// OLED display settings


#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64,
0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// Initialize WiFi client


WiFiClient client;

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

// Initialize OLED display


if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.display();
delay(2000); // Pause for 2 seconds
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);

// Connect to WiFi
Serial.print("Connecting to WiFi...");

95 | P a g e
display.print("Connecting to WiFi...");
display.display();
WiFi.begin(ssid, password);

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


delay(500);
Serial.print(".");
display.print(".");
display.display();
}
Serial.println(" Connected to WiFi!");
display.println(" Connected to WiFi!");
display.display();

// 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);

// Make the GET request


HTTPClient http;
http.begin(client, url);
int httpCode = http.GET();
// Check the HTTP status code
if (httpCode > 0) {
Serial.printf("HTTP GET request successful, code: %d\n", httpCode);
// Parse the JSON response
String payload = http.getString();
Serial.print("Response: ");
Serial.println(payload);
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, payload);
if (error) {
Serial.print("Failed to parse JSON: ");
Serial.println(error.c_str());
display.clearDisplay();
display.setCursor(0, 0);
display.print("Failed to parse JSON:");
display.print(error.c_str());
display.display();
} else {
// Extract field values

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

Figure: Block diagram of the overall system

100 | P a g e
Circuit Diagram

Pin Connections Table:


.96” OLED DISPLAY ESP32
GND GND
VCC 3.3V
SCL GPIO 22
SDA GPIO 21

4G/GSM MODEM ESP32

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>

// OLED display parameters


#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// Create a hardware serial instance for the GSM module


HardwareSerial gsmSerial(2); // Using UART2 (TX2 = GPIO17, RX2 = GPIO16)

const int baudRate = 115200; // Baud rate for GSM module

void setup() {
// Start serial communication with the GSM module
gsmSerial.begin(baudRate, SERIAL_8N1, 32, 33); // RX = GPIO16, TX = GPIO17

// Start serial communication with the Serial Monitor

102 | P a g e
Serial.begin(115200);

// Initialize the OLED display


if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.display();
delay(2000);
display.clearDisplay();

// Display initial message on OLED


display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println(F("GSM AT Command Tester"));
display.display();

// Display available commands on Serial Monitor


Serial.println(F("GSM AT Command Tester"));
Serial.println(F("Available commands:"));
Serial.println(F("1. AT"));
Serial.println(F("2. AT+CMGF=1"));
Serial.println(F("3. AT+CSCS=\"GSM\""));
Serial.println(F("4. AT+CSQ"));
Serial.println(F("5. AT+CREG?"));
Serial.println(F("6. Custom AT Command"));
Serial.println(F("Type your command and press Enter:"));
}

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());
}

// Wait a bit before checking again


delay(500);
}

bool sendATCommand(const char* command) {


// Send command to GSM module
gsmSerial.println(command);
delay(100);

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();

// Wait for response


unsigned long startTime = millis();
while (millis() - startTime < 2000) { // 2 seconds timeout
if (gsmSerial.available()) {
String response = gsmSerial.readString();

// Display response on Serial Monitor and OLED


Serial.println("Response:");
Serial.println(response);
display.setCursor(0, 20);
display.println(F("Response:"));
display.println(response);
display.display();

// Check if the response contains "OK"


if (response.indexOf("OK") != -1) {
return true; // Command succeeded
}
break;
}
}

// Display timeout or failure message


Serial.println("Command failed or timed out");
display.setCursor(0, 40);
display.println(F("Command failed or timed out"));
display.display();

return false; // Command failed


}
}

104 | P a g e
Output:

Figure 1. Serial Monitor Displaying the commands

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:

Figure: Block Diagram of the overall system

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

.96” OLED DISPLAY ESP32


GND GND
VCC 3.3V
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>

// OLED display parameters


#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// DHT11 parameters
#define DHTPIN 27

109 | P a g e
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// BMP180 instance
Adafruit_BMP085 bmp;

// Create a hardware serial instance for the GSM module


HardwareSerial gsmSerial(2); // Using UART2 (TX2 = GPIO17, RX2 = GPIO16)

const int baudRate = 115200; // Baud rate for GSM module


const char phone_number[] = "+916305942020"; // Replace with the recipient's
phone number
char message[160]; // Buffer for the SMS message

void setup() {
// Start serial communication with the GSM module
gsmSerial.begin(baudRate, SERIAL_8N1, 32, 33); // RX = GPIO16, TX = GPIO17

// Start serial communication with the Serial Monitor


Serial.begin(115200);

// Initialize the OLED display


if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.display();
delay(2000);
display.clearDisplay();

// Initialize the DHT11 sensor


dht.begin();

// Initialize the BMP180 sensor


if (!bmp.begin()) {
Serial.println(F("Could not find a valid BMP085 sensor, check wiring!"));
while (1) {}
}

// Wait for the GSM module to initialize


delay(3000);

// Send initialization commands to the GSM module


if (!sendATCommand("AT")) return;
if (!sendATCommand("AT+CMGF=1")) return; // Set SMS to Text Mode
if (!sendATCommand("AT+CSCS=\"GSM\"")) return; // Set character set to GSM

// Display initial message

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;

// Check if any reads failed


if (isnan(temperature) || isnan(humidity)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Display sensor values on the OLED
display.clearDisplay();
display.setCursor(0, 0);
display.println(F("Sensor Readings:"));
display.print(F("Temp: "));
display.print(temperature);
display.println(F(" C"));
display.print(F("Humidity: "));
display.print(humidity);
display.println(F(" %"));
display.print(F("Pressure: "));
display.print(pressure);
display.println(F(" hPa"));
display.display();

// Prepare the SMS message


snprintf(message, sizeof(message), "Temp: %.1f C\nHumidity: %.1f
%%\nPressure: %.2f hPa", temperature, humidity, pressure);

// Send the SMS


sendSMS(phone_number, message);

// Wait before sending the next reading


delay(60000); // Send every 60 seconds
}

bool sendATCommand(const char* command) {


gsmSerial.println(command);
delay(100);
unsigned long startTime = millis();

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);

gsmSerial.write(26); // Ctrl+Z to send the message


delay(100);

unsigned long startTime = millis();


while (millis() - startTime < 5000) { // 5 seconds timeout
if (gsmSerial.available()) {
String response = gsmSerial.readString();
Serial.println(response);
if (response.indexOf("OK") != -1 || response.indexOf("+CMGS:") != -1) {
Serial.println("SMS sent successfully");
return;
}
}
}
Serial.println("Failed to send SMS");
}

112 | P a g e
Output:

Figure: Serial Monitor Displaying the sensor values

Figure 3. Message sent through GSM module to mobile phone

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:

Figure: Block diagram of the overall system

115 | P a g e
Circuit Diagram:

Figure: Circuit Connections.


Pin Connections Table:
4G/GSM ESP32
MODEM
GND GND
VCC 5V
GND GND
TXD GPIO 32 (RX)
RXD GPIO 33 (TX)
V-INT 3.3V

IMU (MPU9250) ESP32


VCC 3.3V
GND GND
SCL GPIO 22
SDA GPIO 21
INT GND
FSYNC GND

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;

const float threshold = 5; // Adjusted low threshold value for detecting


movement

// GSM module parameters


HardwareSerial gsmSerial(2); // Using UART2 (TX2 = GPIO33, RX2 = GPIO32)
const int baudRate = 115200; // Baud rate for GSM module
const char phone_number[] = "+917386766599"; // Replace with the recipient's
phone number
char message[] = "Emergency Accident Alert"; // SMS message to send

bool smsSent = false; // Flag to track if SMS has been sent


unsigned long lastSMSTime = 0; // Track the last time an SMS was sent

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();

// Initialize GSM module


gsmSerial.begin(baudRate, SERIAL_8N1, 32, 33); // RX = GPIO32, TX = GPIO33
delay(3000); // Wait for GSM module to initialize

// Initialize GSM module with necessary AT commands


if (!sendATCommand("AT", 5000)) return;
if (!sendATCommand("AT+CMGF=1", 5000)) return;
if (!sendATCommand("AT+CSCS=\"GSM\"", 5000)) return;

Serial.println("GSM module initialized successfully");


}

void loop() {
myIMU.accelUpdate();
float accelX = myIMU.accelX();
float accelY = myIMU.accelY();
float accelZ = myIMU.accelZ();

float accelMagnitude = sqrt(accelX * accelX + accelY * accelY + accelZ *


accelZ);

unsigned long currentTime = millis();


if (accelMagnitude > threshold && (currentTime - lastSMSTime > 30000)) {
Serial.println("Movement detected!");
if (sendSMS(phone_number, message)) {
lastSMSTime = currentTime;
smsSent = true;
}
}

delay(10); // Small delay


}

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
}

bool sendSMS(const char* number, const char* text) {


Serial.println("Sending SMS...");
gsmSerial.print("AT+CMGS=\"");
gsmSerial.print(number);
gsmSerial.println("\"");
delay(100);

if (!waitForResponse(">", 5000)) { // Wait for '>' prompt


Serial.println("Failed to get '>' prompt");
return false;
}

gsmSerial.print(text);
delay(100);

gsmSerial.write(26); // Ctrl+Z to send the message


delay(100);

if (waitForResponse("OK", 10000)) { // Wait for OK response


Serial.println("SMS sent successfully");
return true;
} else {
Serial.println("Failed to send SMS");
return false;
}
}

bool waitForResponse(const char* expectedResponse, unsigned long timeout) {

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:

Figure: Accident SMS Alert to the defined number.

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.

Technical Aspects of LoRa

Chirp Spread Spectrum (CSS)

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.

Key Features of LoRa

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:

Figure: Block diagram of the overall system

Circuit Diagram:

Figure: 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>

const int csPin = 5;


const int resetPin = 14;
const int irqPin = 2;

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:

Figure: Output at Serial Monitor

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:

Figure 1. Block diagram of the overall system

127 | P a g e
Circuit Diagram:

Figure: Transmitter side Circuit Diagram

Figure: Receiver side Circuit Diagram

Pin Connections Table


LORA BOARD (868MHZ) ESP32
GND GND
MISO GPIO 19
MOSI GPIO 23
SCK GPIO 18

128 | P a g e
NSS GPIO 5
RST GPIO 14
DIO0 GPIO 2
GND 3.3V

HUMIDITY AND TEMPERATURE ESP32


SENSOR (DHT11)
GND GND
DATA GPIO 27
VCC 3.3V

.96” OLED DISPLAY ESP32


GND GND
VCC 3.3V
SCL GPIO 22
SDA GPIO 21

Procedure:

• Open Arduino IDE and setup environment to ESP32.


• Navigate to "Sketch" > "Include Library" > "Manage Libraries," and install the following
libraries: LoRa, Adafruit_SSD1306, Adafruit_GFX, DHT.
• Connect the DHT11 sensor to the first ESP32 (Transmitter) according to the pin
connections table.
• Connect the LoRa module to both ESP32 modules (Transmitter and Receiver) according
to the pin connections table.
• Connect the OLED display to both ESP32 modules according to the pin connections table.
• Copy the provided transmitter code into the Arduino IDE.
• Select the correct board (DOIT ESP32 DevKit V1) and port, then upload the code to the
transmitter ESP32.
• Copy the provided receiver code into the Arduino IDE.
• Select the correct board (DOIT ESP32 DevKit V1) and port, then upload the code to the
receiver ESP32.
• Open the Serial Monitor from the Arduino IDE to observe the initialization messages.

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>

const int csPin = 5;


const int resetPin = 14;
const int irqPin = 2;

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

#define SCREEN_WIDTH 128


#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define SCREEN_ADDRESS 0x3C

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);

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


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

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);

String packet = "Humidity: " + String(h) + "% || " + "Temperature: "+


String(t) + "C | " + String(f)+ "F ";

LoRa.beginPacket();
LoRa.print(packet);
LoRa.endPacket();

Serial.print("Sent packet: ");


Serial.println(packet);

delay(2000);
}

Receiver Side:
#include <SPI.h>
#include <LoRa.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128


#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define SCREEN_ADDRESS 0x3C
const int csPin = 5;
const int resetPin = 14;
const int irqPin = 2;

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);

if (!LoRa.begin(868E6)) { // Set frequency to 868 MHz (change if necessary)


Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {

display.setCursor(0, 0);
int packetSize = LoRa.parsePacket();
if (packetSize) {

Serial.print("Received packet: ");


display.print("Received packet: ");
String received = "";

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:

Figure: Output in Serial Monitor of Arduino IDE

Receiver Side:

Figure: Output in Serial Monitor of Arduino IDE

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:

• 2x IOT Development Kit

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

FSO communication seems to be promising; however, significant challenges need to be

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

bidirectional data transmission can be performed.

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

Figure: Block Diagram of the FSO Data Transmission.

Circuit Diagram:

Figure 1.1 Transmitter of FSO Figure 1.2 Receiver of FSO

Pin Connections Table

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';

//Print the message (or do other things)


Serial.println(message);

//Reset for the next 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:

• DOIT ESP32 Dev Kit V1Module


• DHT11 Temperature Sensor Module

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:

Figure: Block diagram of the overall system

Circuit Diagram:

141 | P a g e
Figure: Circuit Connections.
Pin Connections Table:
ESP32 DHT11
3.3V VCC
GND GND
GPIO 27 DATA
Procedure:

• Log in to the data base.


• Create a table named DHT_11 using the command in the input box at the top left corner:
create table Table_Name (Column_name_1, Column_name_2, , , , , Column_name_n)
• Open the Arduino Ide.
• Paste the code and download the required libraries (HTTPClient, DHT, WiFi) from
Library Manager.
• Verify the pin connections of the Hardware used.
• Modify the necessary credentials such as, SSID, Password, serverName, username,
userpassword, db name, table name, if required.
• Compile the code.
• Upload the code to the ESP32.

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"

#define DHTPIN 27 // Define the pin where the DHT11 is connected


#define DHTTYPE DHT11 // Define the type of DHT sensor

DHT dht(DHTPIN, DHTTYPE);

// 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");

dht.begin(); // Initialize the DHT sensor


}

void sendData(float temperature, float humidity) {


// Construct the SQL command
String command = "insert into DHT_11 (Temperature, Humidity) values(";
command += String(temperature) + ", " + String(humidity);
command += ")";

// Encode the command

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;
}
}

// Construct the request URL


String requestUrl = serverName;
requestUrl += "?username=" + String(username);
requestUrl += "&password=" + String(userpassword);
requestUrl += "&func=execute_command";
requestUrl += "&db_name=" + String(db_name);
requestUrl += "&table_name=" + String(table_name);
requestUrl += "&command=" + encoded_command;

// Send the HTTP GET request


if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(requestUrl);
int httpResponseCode = http.GET();

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:

Figure: Output at Serial Monitor

145 | P a g e
Figure: Output at SQLite Data base in DHT_11 Table

Conclusion:

In conclusion, uploading DHT11 sensor data to an SQLite database named "Skdas"


ensures reliable storage of temperature and humidity readings. This setup facilitates real-time
data logging and future analysis, enhancing our ability to monitor environmental conditions
systematically.

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:

• DOIT ESP32 DevKit V1Module

Software Used:

• Arduino IDE
• SQLite Data base

Introduction:

In this experiment, we focus on retrieving previously uploaded sensor data from an


SQLite database named "Skdas." The database contains a table named "DHT_11," which holds
historical temperature and humidity readings collected by a DHT11 sensor. Using an ESP32
microcontroller and Arduino IDE, we will access and extract this stored data, enabling us to
analyze past environmental conditions. By retrieving and examining these archived sensor
readings, we can gain valuable insights, track trends, and make data-driven decisions based on
historical temperature and humidity patterns. This information can be crucial for planning
future actions, optimizing resource management, and improving overall environmental
monitoring strategies.

Block Diagram:

Figure: Block diagram of the overall system

147 | P a g e
Circuit Diagram:

Pin Connections: No connections Required

Procedure:

• Log in to the data base.


• Open the table in the databse.
• Open the Arduino Ide.
• Paste the code and download the required libraries (HTTPClient, WiFi, ArduinoJson)
from Library Manager.
• Modify the necessary credentials such as, SSID, Password, serverName, username,
userpassword, db name, table name, 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 database table.
• Save and close the program when finished.

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");
}

String urlEncode(const String &str) {


String encodedString = "";
char c;
char code0;
char code1;
char code2;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (c == ' ') {
encodedString += '+';
} else if (isalnum(c)) {
encodedString += c;
} else {
code1 = (c & 0xf) + '0';
if ((c & 0xf) > 9) {
code1 = (c & 0xf) - 10 + 'A';
}
c = (c >> 4) & 0xf;
code0 = c + '0';
if (c > 9) {
code0 = c - 10 + 'A';
}
code2 = '\0';
encodedString += '%';
encodedString += code0;
encodedString += code1;
}
yield();
}

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";

// Encode the command


String encoded_command = urlEncode(command);

// Construct the request URL


String requestUrl = serverName;
requestUrl += "?username=" + String(username);
requestUrl += "&password=" + String(userpassword);
requestUrl += "&func=execute_command";
requestUrl += "&db_name=" + String(db_name);
requestUrl += "&table_name=" + String(table_name);
requestUrl += "&command=" + encoded_command;

// Send the HTTP GET request


if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(requestUrl);
int httpResponseCode = http.GET();

if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println("Raw Response:");
Serial.println(response);

// Attempt to parse JSON response


StaticJsonDocument<1024> doc;
DeserializationError error = deserializeJson(doc, 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: Data in SQLite Data base DHT_11 Table.

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:

Figure: Block diagram of the overall system.

Circuit Diagram:

Figure: Circuit Connections.

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>

int ledpin = 17;


const char* ssid = "OnePlus";
const char* password = "719622Aa";
WebServer server(80);
String loginPage = "<html>\
<head>\
<style>\
body { font-family: Arial, sans-serif; text-align: center; background-
color: f2f2f2; }\
h1 { color: 333; }\
form { display: inline-block; margin-top: 20px; }\
input[type='text'], input[type='password'] { padding: 10px; margin: 10px;
border: 1px solid ccc; border-radius: 4px; width: 200px; }\
input[type='submit'] { padding: 10px 20px; border: 1px solid ccc; border-
radius: 4px; background-color: rgba(0, 123, 255, 0.5); color: white; cursor:
pointer; transition: background-color 0.3s; }\
input[type='submit']:hover { background-color: rgba(0, 123, 255, 0.7); }\
</style>\
</head>\
<body>\
<h1>Login</h1>\
<form action='/login' method='post'>\
<input type='text' name='username' placeholder='Username'><br>\
<input type='password' name='password' placeholder='Password'><br>\
<input type='submit' value='Login'>\
</form>\
</body>\
</html>";

String controlPage = "<html>\


<head>\
<style>\
body { font-family: Arial, sans-serif; text-align: center; background-
color: f2f2f2; }\
h1 { color: 333; }\

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>";

String incorrectCredentialsPage = "<html>\


<head>\
<style>\
body { font-family: Arial, sans-serif; text-align: center; background-
color: f2f2f2; }\
h1 { color: 333; }\
a { color: 007BFF; text-decoration: none; }\
a:hover { text-decoration: underline; }\
</style>\
</head>\
<body>\
<h1>Login Failed</h1>\
<p>Invalid username or password. Please try again.</p>\
<a href='/'>Go back to login</a>\
</body>\
</html>";

// Correct username and password


const char* correctUsername = "admin";

156 | P a g e
const char* correctPassword = "password";

// Handle the root path, display the login page


void handleRoot() {
server.send(200, "text/html", loginPage);
}

// Handle the login action


void handleLogin() {

if (server.method() == HTTP_POST) {
String username = server.arg("username");
String password = server.arg("password");

if (username == correctUsername && password == correctPassword) {


server.send(200, "text/html", controlPage);
} else {
server.send(401, "text/html", incorrectCredentialsPage);
}
} else {
server.send(405, "text/html", "<html><body>Method Not
Allowed</body></html>");
}
}

// Handle the control action, turn the LED on or off


void handleControl() {
if (server.method() == HTTP_POST) {
String ledState = server.arg("LED");

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>");
}
}

// Handle the status request, send the current LED status


void handleStatus() {
if (digitalRead(ledpin) == HIGH) {

157 | P a g e
server.send(200, "text/plain", "LED is ON");
} else {
server.send(200, "text/plain", "LED is OFF");
}
}

// Setup the ESP32


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

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:

Figure: Block Diagram of overall system.

160 | P a g e
Circuit Diagram:

Figure: Circuit Connections

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

.96” OLED DISPLAY ESP32


GND GND
VCC 3.3V
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();

// Check if any reads failed

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:

Figure: Sensor readings on OLED Display.

Figure: Output at Thing Speak server

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:

• DOIT ESP32 DevKit V1Module


• IMU(MPU9250) Module

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:

Figure: Block diagram of System of connections used in the code.

Circuit Diagram:

Figure: Circuit Connections.

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:

• Set up your project directory structure:

o your-project/

o ├── public/

o │ └── index.html

o └── server.js

• Install necessary npm packages:

o npm init -y

o npm install express body-parser axios

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

• Access the HTML page by navigating to http://localhost:3000 in your web

browser.

169 | P a g e
Software Implementation:

Figure: Arrangement of server.js file to start the server.

Figure: Arrangement of index.html

Figure Software Implementation using Arduino IDE 2.3.2

170 | P a g e
Code:
ESP 32 Code:
#include <Wire.h>
#include <MPU9250_asukiaaa.h>
#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "OnePlus";


const char* password = "719622Aa";
const char* serverName = "http://192.168.21.105:3000/data"; // Replace with
your server's IP and port
const char* apiKey = "L4ZA2L24TO09SB81";

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();

float accelX = myIMU.accelX();


float accelY = myIMU.accelY();
float accelZ = myIMU.accelZ();

float gyroX = myIMU.gyroX();


float gyroY = myIMU.gyroY();
float gyroZ = myIMU.gyroZ();

// Send data to local server


String postDataLocal = "{\"accelX\":" + String(accelX) + ",\"accelY\":" +
String(accelY) + ",\"accelZ\":" + String(accelZ) +

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");
}

// Send data to ThingSpeak


if (WiFi.status() == WL_CONNECTED) {
HTTPClient httpThingSpeak;
String url = "http://api.thingspeak.com/update?api_key=" + String(apiKey)
+
"&field1=" + String(accelX) + "&field2=" + String(accelY) +
"&field3=" + String(accelZ) +
"&field4=" + String(gyroX) + "&field5=" + String(gyroY) +
"&field6=" + String(gyroZ);

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;

// ThingSpeak API information


const apiKey = 'L4ZA2L24TO09SB81';
const thingSpeakUrl = `http://api.thingspeak.com/update?api_key=${apiKey}`;

// Middleware to parse JSON data


app.use(bodyParser.json());

// Serve the static HTML file


app.use(express.static(path.join(__dirname, 'public')));

174 | P a g e
let sensorData = {};

// Create an HTTP server


const server = http.createServer(app);

// Create a WebSocket server


const wss = new WebSocket.Server({ server });

// WebSocket connection
wss.on('connection', ws => {
console.log('Client connected');

ws.on('close', () => {
console.log('Client disconnected');
});
});

// Function to broadcast data to all connected clients


const broadcastData = data => {
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
});

// Endpoint to receive data from the Arduino
app.post('/data', async (req, res) => {
sensorData = req.body;
console.log('Received data:', sensorData);

// Send data to ThingSpeak

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);
});

// Endpoint to serve sensor data to the client


app.get('/sensorData', (req, res) => {
res.json(sensorData);
});
// Start the server
server.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

Protocols Used:

I2C (Inter-Integrated Circuit): I2C is a synchronous, multi-master, multi-slave, packet-


switched, single-ended, serial communication bus. In this project, I2C is used for
176 | P a g e
communication between the Arduino and the MPU9250 sensor. The Arduino uses the I2C
protocol to read data from the sensor by sending and receiving data packets over two lines:
SDA (data line) and SCL (clock line).

HTTP (HyperText Transfer Protocol): HTTP is an application protocol for distributed,


collaborative, hypermedia information systems. It is the foundation of data communication on
the World Wide Web. In this project, HTTP is used to send IMU data from the Arduino to the
local server and to ThingSpeak. The data is formatted as JSON and transmitted via HTTP POST
requests.

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

Figure 9.b Acceleration y-axis field in ThingSpeak

Figure 9.c Acceleration z-axis field in ThingSpeak

178 | P a g e
Figure 10.a Gyroscopic Acceleration x-axis field in ThingSpeak

Figure 10.b Gyroscopic Acceleration y-axis field in ThingSpeak

Figure 10.c Gyroscopic Acceleration z-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:

• Web Development Education


• Prototyping IoT Dashboards
• Local Network Tools
• Data Visualization
• Interactive Web Applications
• API Testing
• Home Automation Systems
• Learning Platform Development
• Rapid Prototyping

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:

Figure 1: Block Diagram of overall System

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”.

Figure 2. Creating a ThingSpeak Channel


• Now select “Add Widgets” (in private view)> Lamp Indicator and fill out the settings
required.

Figure 3. Details of channel created

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.

Figure 5. API Keys for a channel

Code:
#include <WiFi.h>
#include "ThingSpeak.h"

char ssid[] = "Your Network Name"; // your network SSID (name)


char pass[] = "Your Network Password"; // your network password
WiFiClient client;

unsigned long myChannelNumber = 2564037;


const char * myWriteAPIKey = "O5NH1VLFF19SUOGV";
const char * myReadAPIKey = "UD89JJRKKA6ETTS1";

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:

Figure 6. Output displayed on ThingSpeak Channel.

Figure 7. Output in ThingSpeak when the LED is ON

Figure 8. Output in ThingSpeak when the LED is OFF

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.

Applications: Home Automation, Remote Control

186 | P a g e

You might also like