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

Lab Manual PDF

This document provides instructions for an experiment on controlling GPIO pins using NodeMCU. It describes installing the NodeMCU board in Arduino IDE, connecting an LED to a GPIO pin of NodeMCU, writing code to blink the LED, and successfully running the code. Precautions for working with circuits are also outlined. The objectives are to set up the ESP8266 development board and do GPIO programming using the Arduino IDE. An example of writing code to measure air quality using a sensor connected to a GPIO pin is also given.

Uploaded by

Mohan Mk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Lab Manual PDF

This document provides instructions for an experiment on controlling GPIO pins using NodeMCU. It describes installing the NodeMCU board in Arduino IDE, connecting an LED to a GPIO pin of NodeMCU, writing code to blink the LED, and successfully running the code. Precautions for working with circuits are also outlined. The objectives are to set up the ESP8266 development board and do GPIO programming using the Arduino IDE. An example of writing code to measure air quality using a sensor connected to a GPIO pin is also given.

Uploaded by

Mohan Mk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

21IE2047 PROJECT BASED LEARNING 2

PROJECT BASED LEARNING 2

21IEC2047
A.Y: 2022 –23

Semester: 2-2

DEPARTMENT OF ELECTRONICS AND


COMMUNICATION ENGINEERING
Vaddeswaram, Guntur District

1
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Index of Experiments

Page
S. No. Name of the Experiment Marks Faculty Sign
No.
3
1. Controlling the GPIO pins in NodeMCU

10
2. Harmful gas monitoring using NodeMCU and ThingSpeak

17
Barometric Pressure monitoring using NodeMCU and
3.
ThingSpeak
25
Setting the Date and Time in DS3231 RTC module using
4.
NodeMCU
29
Designing Weather station by HTTP GET REQUEST-
5.
RESPONSE using NodeMCU
35
6. Communication between Two NodeMCU using ESPNOW

44
7. Controlling the GPIO pins in ESP32

58
8. Controlling the GPIO pins in ESP32 using Touch Inputs

63
9. Barometric Pressure monitoring using ESP32

67
Monitoring the Accelerometer and Gyroscope Data in WEB
10.
Server using ESP32
11. 78
Controlling the Servo Motor using ESP32

12. 81
Observation of Hall Effect value and Temperature from ESP32

2
Koneru Lakshmaiah Education Foundation
2022-23 EVEN SEMESTER LAB CONTINUOUS EVALUATION

S No: Date Experiment Pre-


Title Lab In Lab
(5M) Post Viva-
Total Sign of
-Lab voce
Logic Execu Result Analysis (50M) Faculty
(5M) (5M)
(10M) tion (10M) (5M)
(10M)

Koneru Lakshmaiah Education Foundation


2

3
21IE2047 PROJECT BASED LEARNING 2

3
2022-23 EVEN SEMESTER PROJECT CONTINUOUS EVALUATION

S No: Date Project Title Abst Project Work Rep Viva- Total Sign of
ract ort voce (50M) Faculty
(5M) (5M) (5M)

Logic Execut Result Analysis


(10M) ion (10M) (5M)

Koneru Lakshmaiah Education Foundation


(10M)
21IE2047 PROJECT BASED LEARNING 2

4
21IE2047 PROJECT BASED LEARNING 2

Expt No.: 1 Date:


Controlling the GPIO pins in NodeMCU
AIM
To setup ESP 8266 and GPIO Programming using Arduino IDE Programming.

SOFTWARES USED
1. ESP8266 BOARD (Arduino IDE)

APPARATUS/ COMPONENTS REQUIRED


1. ESP8266
2. Connecting Cable
3. Connecting Wires
4. Bread Board
DESCRIPTION: NODEMCU INSTALLATION PROCEDURE
Installing NodeMcu Add-on in Arduino IDE
1. Make sure you are using Arduino IDE version 1.7 or higher.
2. Add additional URL for board manager. Go to File >> Preferences and paste below
url in Additional Board Manager URL’s
http://arduino.esp8266.com/stable/package_esp8266com_index.json

5
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

6
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

3. Search the word ESP8266 in Boards>boards manager from Tools menu. Then
install ESP8266 boards. After complete installation, you will see the
INSTALLED label on ESP8266 boards.
4. Open the Boards Manager. Go to Tools > Board > Boards Manager…

5. Search for ESP8266 and press install button

7
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Installing ESP8266
After these above steps, you can see ESP8266 based boards such as NodeMCU in your
Arduino IDE boards list, and you can choose your desired board to upload the code.

6. Go to Tools>>Boards>> select NodeMCU (If you don’t find NodeMCU, check your
installation is ok)
7. Select proper Com port
8. Upload blink example and check is it working. on board LED uses GPIO2

8
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

NodeMCU board is visible


PRE-LAB SESSION
1. What type of cable should be used for ESP8266?
Ans.
2. Specify ROM size of ESP8266?
Ans.
3. Mention the software which is to be installed in the laptop for ESP8266 board?
Ans.
4. What is the operating voltage of the GPIO pins in ESP8266?
Ans.

GPIO PROGRAMMING
How to write Air Quality measurement using ESP8266 ?

9
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

1. Connect Sensors any GPIO Pin (GPIO 1) as per the Circuit Diagram
2. Connect 1K or 470Ω Resistor for current limiting Purpose.

CODING/ PROGRAM

int LED_BUILTIN = 1;

void setup()
{

10
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

pinMode (LED_BUILTIN, OUTPUT);

}
void loop()
{
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}

PRECAUTIONS
1. Use insulation tools while you connect the Circuit.
2. Wear Good Insulating Shoes.
3. Avoid contacting circuits with wet hands or wet materials.
4. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
5. Be careful while connecting any actuators in 230V AC Mains.

RESULT
We successfully setup ESP8266 along with LED blinking Program using Arduino IDE .

INFERENCES/ANALYSIS

POST-LAB ASSIGNMENTS

1. How many GPIO pins are available in the ESP8266?


Ans.
2. Mention the number of ADCs available in ESP8266?
Ans.
3. How many USB ports are available in the ESP8266?

11
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Ans.
4. Mention the number of micro usb ports available in ESP8266?
Ans.
5. How many PWM pins are available in the ESP8266?
Ans.
6. List out the GND pins available in the ESP8266?.
Ans.
7. List out the +3.3 V pins available in the ESP8266.
Ans.
8. List out the +5V pins available in the ESP8266
Ans.

12
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Expt No.: 2 Date:


Harmful gas monitoring using NodeMCU and ThingSpeak
AIM
To MQ135 interface with ESP8266 and THINGSPEAK using Arduino IDE
Programming.

SOFTWARES USED
ESP8266 BOARD (Arduino IDE)
APPARATUS/ COMPONENTS REQUIRED

1. ESP8266
2. MQ 135 sensor
3. Connecting Cables
4. DC 5V, 1A Power Adaptor

THEORY:
The MQ-135 Gas sensor can detect gases like Ammonia (NH3), sulfur (S), Benzene (C6H6),
CO2, and other harmful gases and smoke. Similar to other MQ series gas sensor, this sensor
also has a digital and analog output pin. When the level of these gases go beyond a threshold
limit in the air the digital pin goes high. This threshold value can be set by using the on-board
potentiometer. The analog output pin, outputs an analog voltage which can be used to
approximate the level of these gases in the atmosphere.
The MQ135 air quality sensor module operates at 5V and consumes around 150mA. It requires
some pre-heating before it could actually give accurate results.
Details of MQ135 Sensor
The MQ135 is one of the popular gas sensors from the MQ series of sensors that are commonly
used in air quality control equipment. It operates from 2.5V to 5.0V and can provide both digital
and analog output. The pinouts and important components on an MQ135 Module is marked
below

13
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

DESCRIPTION:
Circuit Diagram & Connections
Make a connection as per the circuit diagram below. Connect the VCC pin of MQ135 to Vin
of NodeMCU and GND to GND. Connect analog pin A0 of MQ135 to Analog pin A0 of
NodeMCU.

14
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Setting Thingspeak & Getting API Key:


1. Go to https://thingspeak.com/ and create an account, Then login and click on Channels

Create a new Channel by clicking on the New Channel button and entering relevant
information. This is the minimum required:

Check the boxes next to Fields 1. Enter these channel setting values:
Name: Gas Level Monitoring
Field 1: Gas
Click Save Channel at the bottom of the settings.
You now see these tabs:
o Private View: This tab displays information about your channel that only you
can see.
o Public View: If you choose to make your channel publicly available, use this
tab to display selected fields and channel visualizations.
o Channel Settings: This tab shows all the channel options you set at creation.
You can edit, clear, or delete the channel from this tab.
o Sharing: This tab shows channel sharing options. You can set a channel as
private, shared with everyone (public), or shared with specific users.
o API Keys: This tab displays your channel API keys. Use the keys to read from
and write to your channel.
o Data Import/Export: This tab enables you to import and export channel data.

15
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Then go to API keys copy and paste this key to a separate notepad file. You will need it later
while programming.

16
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

PRE-LAB SESSION
1. What type of cable should be used for ESP8266?
Ans.
2. Specify ROM size of ESP8266?
Ans.
3. Mention the software which is to be installed in the laptop for ESP8266 board?
Ans.
4. What is the operating voltage of the GPIO pins in ESP8266?
Ans.

CODE/ PROGRAM
#include <ESP8266WiFi.h>
String apiKey = "Write API key from ThingSpeak"; // Enter your Write API key from
ThingSpeak
const char *ssid = "your wifi ssid"; // replace with your wifi ssid and wpa2 key
const char *pass = "Your Password";
const char* server = "api.thingspeak.com";
WiFiClient client;
void setup()
{
Serial.begin(115200);
delay(10);
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop()
{

17
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

float h = analogRead(A0);
if (isnan(h))
{
Serial.println("Failed to read from MQ-135 sensor!");
return;
}

if (client.connect(server, 80)) // "184.106.153.149" or api.thingspeak.com


{
String postStr = apiKey;
postStr += "&field1=";
postStr += String(h/1023*100);
postStr += "r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
Serial.print("Gas Level: ");
Serial.println(h/1023*100);
Serial.println("Data Send to Thingspeak");
}
delay(500);
client.stop();
Serial.println("Waiting...");

// thingspeak needs minimum 15 sec delay between updates.


delay(1500);
}

PRECAUTIONS
1. Use insulation tools while you connect the Circuit.
2. Wear Good Insulating Shoes.
3. Avoid contacting circuits with wet hands or wet materials.
4. Maintain a work space clear of extraneous material such as books, papers, and clothes.

18
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

5. Be careful while connecting any actuators in 230V AC Mains.

Results

INFERENCES/ANALYSIS

POST-LAB ASSIGNMENTS

1. How does MQ135 gas sensor work?


Ans.
2. Mention the number of ADCs available in ESP8266?
Ans.
3. How many pins are available in the MQ135?
Ans.
4. What are the gases can be detected by MQ135?
Ans.

19
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Expt No No.: 3 Date:


Barometric Pressure monitoring using NodeMCU and ThingSpeak
AIM
To BMP180 interface with ESP8266 and post the data in to THINGSPEAK cloud

SOFTWARES USED
ESP8266 BOARD (Arduino IDE)
APPARATUS/ COMPONENTS REQUIRED

1. ESP8266
2. BMP180 PressureSensor
3. Connecting Cables
4. DC 5V, 1A Power Adaptor

THEORY:
This precision sensor from Bosch is the best low-cost sensing solution for measuring
barometric pressure and temperature. Because pressure changes with altitude you can also use
it as an altimeter! The sensor is soldered onto a PCB with a 3.3V regulator, I2C level shifter
and pull-up resistors on the I2C pins.

The BMP180 is the next-generation of sensors from Bosch, and replaces the BMP085. The
good news is that it is completely identical to the BMP085 in terms of firmware/software - you
can use our BMP085 tutorial and any example code/libraries as a drop-in replacement. The
XCLR pin is not physically present on the BMP180 so if you need to know that data is ready
you will need to query the I2C bus.

This board is 5V compliant - a 3.3V regulator and a i2c level shifter circuit is included so you
can use this sensor safely with 5V logic and power.

Using the sensor is easy. For example, if you're using an Arduino, simply connect the VIN pin
to the 5V voltage pin, GND to ground, SCL to I2C Clock (Analog 5) and SDA to I2C Data
(Analog 4). Then download our BMP085/BMP180 Arduino library and example code for
temperature, pressure and altitude calculation. Install the library, and load the example sketch.
Immediately you'll have precision temperature, pressure and altitude data.

20
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

HARDWARE CONNECTION:

INSTALL THE NECESSARY LIBRARY FILE:

1. Download the BMP180 ZIP library from https://github.com/Joserta/arduino_BMP180.

21
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

2. Open Arduino IDE. Then go to and select Sketch->Include Library->Add .ZIP Library.

22
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

3. Choose arduino_BMP180-master.zip file and click to Open.

CODE/PROGRAM:-

#include <ESP8266WiFi.h>
#include <SFE_BMP180.h>
#include <SPI.h>
#include <Wire.h>

// You will need to create an SFE_BMP180 object, here called "pressure":


SFE_BMP180 pressure;

#define ALTITUDE 24.0 // Altitude of SparkFun's HQ in Boulder, CO. in meters


String apiKey = "your apiKey"; // Enter your Write API key from ThingSpeak
const char *ssid = "your name"; // replace with your wifi ssid and wpa2 key
const char *pass = " your password";
const char* server = "api.thingspeak.com";
WiFiClient client;

void setup()
{
Serial.begin(115200); // open serial port, set the baud rate to 9600 bps
delay(10);
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

Serial.println("REBOOT");

// Initialize the sensor (it is important to get calibration values stored on the device).

if (pressure.begin())
{

23
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Serial.println("BMP180 init success");

}
else
{
// Oops, something went wrong, this is usually a connection problem,
// see the comments at the top of this sketch for the proper connections.

Serial.println("BMP180 init fail\n\n");


while(1); // Pause forever.
}
}

void loop()
{
char status;
double T,P,p0,a;

// Loop here getting pressure readings every 10 seconds.

// If you want sea-level-compensated pressure, as used in weather reports,


// you will need to know the altitude at which your measurements are taken.
// We're using a constant called ALTITUDE in this sketch:
Serial.println();
Serial.print("provided altitude: ");
Serial.print(ALTITUDE,0);
Serial.print(" meters, ");
Serial.print(ALTITUDE*3.28084,0);
Serial.println(" feet");

// If you want to measure altitude, and not pressure, you will instead need
// to provide a known baseline pressure. This is shown at the end of the sketch.

// You must first get a temperature measurement to perform a pressure reading.

// Start a temperature measurement:


// If request is successful, the number of ms to wait is returned.
// If request is unsuccessful, 0 is returned.
status = pressure.startTemperature();
if (status != 0)
{

24
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

// Wait for the measurement to complete:


delay(status);

// Retrieve the completed temperature measurement:


// Note that the measurement is stored in the variable T.
// Function returns 1 if successful, 0 if failure.

status = pressure.getTemperature(T);
if (status != 0)
{
// Print out the measurement:
Serial.print("temperature: ");
Serial.print(T,2);
Serial.print(" deg C, ");
Serial.print((9.0/5.0)*T+32.0,2);
Serial.println(" deg F");

// Start a pressure measurement:


// The parameter is the oversampling setting, from 0 to 3 (highest res, longest wait).
// If request is successful, the number of ms to wait is returned.
// If request is unsuccessful, 0 is returned.

status = pressure.startPressure(3);
if (status != 0)
{
// Wait for the measurement to complete:
delay(status);

// Retrieve the completed pressure measurement:


// Note that the measurement is stored in the variable P.
// Note also that the function requires the previous temperature measurement (T).
// (If temperature is stable, you can do one temperature measurement for a number of
pressure measurements.)
// Function returns 1 if successful, 0 if failure.

status = pressure.getPressure(P,T);
if (status != 0)
{
// Print out the measurement:
Serial.print("absolute pressure: ");
Serial.print(P,2);

25
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Serial.print(" mb, ");


Serial.print(P*0.0295333727,2);
Serial.println(" inHg");
// The pressuresensor returns abolute pressure, which varies with altitude.
// To remove the effects of altitude, use the sealevel function and your current altitude.
// This number is commonly used in weather reports.
// Parameters: P = absolute pressure in mb, ALTITUDE = current altitude in m.
// Result: p0 = sea-level compensated pressure in mb

p0 = pressure.sealevel(P,ALTITUDE); // we're at 1655 meters (Boulder, CO)


Serial.print("relative (sea-level) pressure: ");
Serial.print(p0,2);
Serial.print(" mb, ");
Serial.print(p0*0.0295333727,2);
Serial.println(" inHg");

// On the other hand, if you want to determine your altitude from the pressure reading,
// use the altitude function along with a baseline pressure (sea-level or other).
// Parameters: P = absolute pressure in mb, p0 = baseline pressure in mb.
// Result: a = altitude in m.

a = pressure.altitude(P,p0);
Serial.print("computed altitude: ");
Serial.print(a,0);
Serial.print(" meters, ");
Serial.print(a*3.28084,0);
Serial.println(" feet");

}
else Serial.println("error retrieving pressure measurement\n");
}
else Serial.println("error starting pressure measurement\n");
}
else Serial.println("error retrieving temperature measurement\n");
}
else Serial.println("error starting temperature measurement\n");

if (client.connect(server, 80)) // "184.106.153.149" or api.thingspeak.com


{
String postStr = apiKey;

26
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

postStr += "&field1=";
postStr += String(T,2);
postStr += "&field2=";
postStr += String(P*0.0295333727,2);
postStr += "&field3=";
postStr += String(p0*0.0295333727,2);
postStr += "&field4=";
postStr += String(a,0);
postStr += "\r\n\r\n\r\n\r\n";

client.print("POST /update HTTP/1.1\n");


client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);

Serial.println("");
Serial.println("Data Send to Thingspeak");
}
client.stop();
Serial.println("Waiting...");
Serial.println("");
Serial.println("*************************************************");
delay(5000); // Pause for 5 seconds.
}

PRECAUTIONS
1. Use insulation tools while you connect the Circuit.
2. Wear Good Insulating Shoes.
3. Avoid contacting circuits with wet hands or wet materials.
4. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
5. Be careful while connecting any actuators in 230V AC Mains.

Results

27
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

INFERENCES/ANALYSIS

28
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Expt No No.: 4 Date:


Setting the Date and Time in DS3231 RTC module using NodeMCU
AIM
To interface DS3231 with ESP8266

SOFTWARES USED
ESP8266 BOARD (Arduino IDE)
APPARATUS/ COMPONENTS REQUIRED

1. ESP8266
2. DS3231 RTC Module
3. Connecting Cables
4. DC 5V, 1A Power Adaptor

THEORY:
DS3231 RTC is a Precise Real-Time Clock Module with 32Kbit EEPROM and a built-in 10-
bit temperature sensor having a resolution of 0.25C. The DS3231 RTC module Precise Real-
Time Clock Module is a low-cost, extremely accurate I²C real-time clock (RTC) with an
integrated temperature-compensated crystal oscillator (TCXO) and crystal. The device
incorporates a battery input and maintains accurate timekeeping when the main power to the
device is interrupted. The integration of the crystal resonator enhances the long-term accuracy
of the device as well as reduces the piece-part count in a manufacturing line. The ds3231
Arduino is available in commercial and industrial temperature ranges and is offered in a 16-
pin, 300-mil SO package.
Features:
1. Two Time-of-Day Alarms.
2. Digital Temp Sensor Output.
3. Register for Aging Trim.
4. DS 3231 RTC with 2032 Battery Holder.
5. Highly Accurate RTC Completely Manages All Timekeeping Functions.
6. Real-Time Clock Counts Seconds, Minutes, Hours, Date of the Month, Month, Day of
the Week, and Year, with Leap-Year Compensation Valid Up to 2100.
7. Configurable I2C device Address for AT24C32 using SMD jumpers on PCB (A0, A1,
A2).
8. Programmable Square-Wave Output Signal.
9. Battery-Backup Input for Continuous Timekeeping.
10. Low Power Operation Extends Battery-Backup Run Time.

29
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

HARDWARE CONNECTION:

CODE/PROGRAM:-

#include "Arduino.h"
#include "uRTCLib.h"
// uRTCLib rtc;
uRTCLib rtc(0x68);
void setup() {
Serial.begin(9600);
Serial.println("Serial OK");
#ifdef ARDUINO_ARCH_ESP8266
URTCLIB_WIRE.begin(4, 5);
URTCLIB_WIRE.begin();

30
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

#endif
rtc.set(0, 50, 13, 6, 21, 1, 22);
//RTCLib::set(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth,
byte month, byte year)
}

void loop() {
rtc.refresh();
Serial.print("RTC DateTime: ");
Serial.print(rtc.year());
Serial.print('/');
Serial.print(rtc.month());
Serial.print('/');
Serial.print(rtc.day());
Serial.print(' ');
Serial.print(rtc.hour());
Serial.print(':');
Serial.print(rtc.minute());
Serial.print(':');
Serial.print(rtc.second());
Serial.print(" DOW: ");
Serial.print(rtc.dayOfWeek());
Serial.print(" - Temp: ");
Serial.print(rtc.temp()/100);
Serial.println();
delay(1000);
}
PRECAUTIONS
1. Use insulation tools while you connect the Circuit.
2. Wear Good Insulating Shoes.
3. Avoid contacting circuits with wet hands or wet materials.
4. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
5. Be careful while connecting any actuators in 230V AC Mains.

Results
CHECK THE RESULT IN SERIAL MONITOR WITH 115200 BAUDRATE.

31
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

INFERENCES/ANALYSIS

32
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

ExptNo No.: 5 Date:


Weather station by HTTP GET REQUEST-RESPONSE using NodeMCU
AIM
To Designing Weather station by HTTP GET REQUEST-RESPONSE using
NodeMCU

SOFTWARES USED
ESP8266 BOARD (Arduino IDE)
APPARATUS/ COMPONENTS REQUIRED

1. ESP8266
2. Connecting Cables
3. DC 5V, 1A Power Adaptor

THEORY:
The Hypertext Transfer Protocol (HTTP) is designed to enable communications between
clients and servers. HTTP works as a request-response protocol between a client and server.
Each Hypertext Transfer Protocol (HTTP) message is either a request or a response. A server
listens on a connection for a request, parses each message received, interprets the message
semantics in relation to the identified request target, and responds to that request with one or
more response messages. A client constructs request messages to communicate specific
intentions, examines received responses to see if the intentions were carried out, and determines
how to interpret the results. A web browser may be the client, and an application on a computer
that hosts a web site may be the server.
Example: A client (browser) submits an HTTP request to the server; then the server returns a
response to the client. The response contains status information about the request and may also
contain the requested content
Two commonly used methods for a request-response between a client and server are: GET and
POST.
▪ GET – Requests data from a specified resource
▪ POST – Submits data to be processed to a specified resource

33
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

HARDWARE CONNECTION:

OpenWeather platform is a set of elegant and widely recognisable APIs. Powered by


convolutional machine learning solutions, it is capable of delivering all the weather information
necessary for decision-making for any location on the globe to start using our APIs, please sign
up here https://home.openweathermap.org/users/sign_in

34
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

35
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

CODE/PROGRAM:-

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <Arduino_JSON.h>

const char* ssid = "YOUR SSID";


const char* password = "YOUR PASSWRD";

// Your Domain name with URL path or IP address with path


String openWeatherMapApiKey = "YOUR URL PATH";
// Example:
//String openWeatherMapApiKey = "bd939aa3d23ff33d3c8f5dd1dd4";

// Replace with your country code and city


String city = "Vijayawada";
String countryCode = "IN";

// THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES


// For a final application, check the API call limits per hour/minute to avoid getting
blocked/banned
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 10 seconds (10000)
unsigned long timerDelay = 10000;

String jsonBuffer;

void setup() {

36
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Serial.begin(115200);

WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());

Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before


publishing the first reading.");
}

void loop() {
// Send an HTTP GET request
if ((millis() - lastTime) > timerDelay) {
// Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," +
countryCode + "&APPID=" + openWeatherMapApiKey;

jsonBuffer = httpGETRequest(serverPath.c_str());
Serial.println(jsonBuffer);
JSONVar myObject = JSON.parse(jsonBuffer);

// JSON.typeof(jsonVar) can be used to get the type of the var


if (JSON.typeof(myObject) == "undefined") {
Serial.println("Parsing input failed!");
return;
}

Serial.print("JSON object = ");


Serial.println(myObject);
Serial.print("Temperature: ");
Serial.println(myObject["main"]["temp"]);
Serial.print("Pressure: ");
Serial.println(myObject["main"]["pressure"]);
Serial.print("Humidity: ");

37
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Serial.println(myObject["main"]["humidity"]);
Serial.print("Wind Speed: ");
Serial.println(myObject["wind"]["speed"]);
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}

String httpGETRequest(const char* serverName) {


WiFiClient client;
HTTPClient http;

// Your IP address with path or Domain name with URL path


http.begin(client, serverName);

// Send HTTP POST request


int httpResponseCode = http.GET();

String payload = "{}";

if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();

return payload;
}
PRECAUTIONS
6. Use insulation tools while you connect the Circuit.
7. Wear Good Insulating Shoes.
8. Avoid contacting circuits with wet hands or wet materials.

38
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

9. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
10. Be careful while connecting any actuators in 230V AC Mains.

Results

INFERENCES/ANALYSIS

39
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

ExptNo No.: 6 Date:


Communication between Two NodeMCU using ESPNOW
AIM
To establish a two-way communication between two ESP8266 NodeMCU boards
using ESP-NOW communication protocol. As an example, two ESP8266 boards will exchange
DHT sensor readings. We’ll use Arduino IDE.

SOFTWARES USED
2. ESP8266 BOARD (Arduino IDE)

APPARATUS/ COMPONENTS REQUIRED

1. 2x ESP8266 development board (read ESP8266 development boards comparison)


2. 2x DHT22 or DHT11 Temperature and Humidity Sensor
3. 2x 4.7k Ohm Resistor
4. 2x Breadboard
5. Jumper wires

THEORY:

ESP-NOW is a connectionless communication protocol developed by Espressif that features


short packet transmission. This protocol enables multiple devices to talk to each other without
using Wi-Fi.
This is a fast communication protocol that can be used to exchange small messages (up to 250
bytes) between ESP32 boards. ESP-NOW is very versatile and you can have one-way or two-
way communication in different arrangements.

40
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

HARDWARE CONNECTION:

▪ In this project we’ll have two ESP8266 boards. Each board is connected to a DHT
sensor;
▪ Each board gets temperature and humidity readings from their corresponding sensors;
▪ Each board sends its readings to the other board via ESP-NOW;
▪ When a board receives the readings, it prints them on the Serial Monitor. You can
connect an OLED display to visualize the readings, for example.
▪ When a message is sent, a message is printed indicating if the packet was successfully
delivered or not.
▪ Each board needs to know the other board MAC address in order to send the message.
In this example, we’re using a two-way communication between two boards, but you can add
more boards to this setup, and having all boards communicating with each other.

Installing DHT Libraries


To read from the DHT sensor, we’ll use the DHT library from Adafruit. To use this library
you also need to install the Adafruit Unified Sensor library. Follow the next steps to install
those libraries.
1. Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries. The

41
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Library Manager should open.


2. Search for “DHT” on the Search box and install the DHT library from Adafruit.

3) After installing the DHT library from Adafruit, type “Adafruit Unified Sensor” in
the search box. Scroll all the way down to find the library and install it.

42
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

43
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

CODE/PROGRAM:-

#include <ESP8266WiFi.h>
#include <espnow.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
// REPLACE WITH THE MAC Address of your receiver
uint8_t broadcastAddress[] = {0xCC, 0x50, 0xE3, 0x56, 0xA6, 0x62};
// Digital pin connected to the DHT sensor
#define DHTPIN 5
// Uncomment the type of sensor in use:
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)

44
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

DHT dht(DHTPIN, DHTTYPE);


// Define variables to store DHT readings to be sent
float temperature;
float humidity;

// Define variables to store incoming readings


float incomingTemp;
float incomingHum;

// Updates DHT readings every 10 seconds


const long interval = 10000;
unsigned long previousMillis = 0; // will store last time DHT was updated

// Variable to store if sending data was successful


String success;

//Structure example to send data


//Must match the receiver structure
typedef struct struct_message {
float temp;
float hum;
} struct_message;

// Create a struct_message called DHTReadings to hold sensor readings


struct_message DHTReadings;

// Create a struct_message to hold incoming sensor readings


struct_message incomingReadings;

// Callback when data is sent


void OnDataSent(uint8_t *mac_addr, uint8_t sendStatus) {
Serial.print("Last Packet Send Status: ");
if (sendStatus == 0){
Serial.println("Delivery success");
}
else{
Serial.println("Delivery fail");
}
}

// Callback when data is received

45
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

void OnDataRecv(uint8_t * mac, uint8_t *incomingData, uint8_t len) {


memcpy(&incomingReadings, incomingData, sizeof(incomingReadings));
Serial.print("Bytes received: ");
Serial.println(len);
incomingTemp = incomingReadings.temp;
incomingHum = incomingReadings.hum;
}

void getReadings(){
// Read Temperature
temperature = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
//float t = dht.readTemperature(true);
if (isnan(temperature)){
Serial.println("Failed to read from DHT");
temperature = 0.0;
}
humidity = dht.readHumidity();
if (isnan(humidity)){
Serial.println("Failed to read from DHT");
humidity = 0.0;
}
}

void printIncomingReadings(){
// Display Readings in Serial Monitor
Serial.println("INCOMING READINGS");
Serial.print("Temperature: ");
Serial.print(incomingTemp);
Serial.println(" ºC");
Serial.print("Humidity: ");
Serial.print(incomingHum);
Serial.println(" %");
}

void setup() {
// Init Serial Monitor
Serial.begin(115200);

// Init DHT sensor


dht.begin();

46
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

// Set device as a Wi-Fi Station


WiFi.mode(WIFI_STA);
WiFi.disconnect();

// Init ESP-NOW
if (esp_now_init() != 0) {
Serial.println("Error initializing ESP-NOW");
return;
}

// Set ESP-NOW Role


esp_now_set_self_role(ESP_NOW_ROLE_COMBO);

// Once ESPNow is successfully Init, we will register for Send CB to


// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);

// Register peer
esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_COMBO, 1, NULL, 0);

// Register for a callback function that will be called when data is received
esp_now_register_recv_cb(OnDataRecv);
}

void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you updated the DHT values
previousMillis = currentMillis;

//Get DHT readings


getReadings();

//Set values to send


DHTReadings.temp = temperature;
DHTReadings.hum = humidity;

// Send message via ESP-NOW


esp_now_send(broadcastAddress, (uint8_t *) &DHTReadings, sizeof(DHTReadings));

47
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

// Print incoming readings


printIncomingReadings();
}
}

To get MAC Address


#include <ESP8266WiFi.h>

void setup(){

Serial.begin(115200);

Serial.println();

Serial.print("ESP Board MAC Address: ");

Serial.println(WiFi.macAddress());

void loop()

After uploading the code, press the RST/EN button, and the MAC address should be
displayed on the Serial Monitor.

PRECAUTIONS
11. Use insulation tools while you connect the Circuit.
12. Wear Good Insulating Shoes.
13. Avoid contacting circuits with wet hands or wet materials.
14. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
15. Be careful while connecting any actuators in 230V AC Mains.

Results

48
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

INFERENCES/ANALYSIS

49
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Expt No.:7 Date:


ESP 32 SETUP & Controlling the GPIO pins in ESP32
AIM
To setup ESP32 and GPIO Programming using Arduino IDE Programming.

SOFTWARES USED
ESP32 BOARD (Arduino IDE)
APPARATUS/ COMPONENTS REQUIRED

1. ESP32
2. Connecting Cable
3. DC 5V, 1A Power Adaptor
4. Connecting Wires
5. Bread Board

DESCRIPTION: ESP32 INSTALLATION PROCEDURE


Installing ESP32 Add-on in Arduino IDE
To install the ESP32 board in your Arduino IDE, follow these next instructions:
1. In your Arduino IDE, go to File> Preferences

50
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

2. Enter https://dl.espressif.com/dl/package_esp32_index.json into the “Additional


Board Manager URLs” field as shown in the figure below. Then, click the “OK” button:

51
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Note: if you already have the ESP8266 boards URL, you can separate the URLs with
a comma as follows:
https://dl.espressif.com/dl/package_esp32_index.json,
http://arduino.esp8266.com/stable/package_esp8266com_index.json
3. Open the Boards Manager. Go to Tools > Board > Boards Manager…

52
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

4. Search for ESP32 and press install button for the “ESP32 by Espressif Systems“:

53
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

5. That’s it. It should be installed after a few seconds.

Testing the Installation

54
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Plug the ESP32 board to your computer. With your Arduino IDE open, follow these
steps:
1. Select your Board in Tools > Board menu (in my case it’s the DOIT ESP32
DEVKIT V1)

2. Select the Port (if you don’t see the COM Port in your Arduino IDE, you need to
install the CP210x USB to UART Bridge VCP Drivers):

55
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

3. Open the following example under File > Examples > WiFi (ESP32) > WiFiScan

56
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

4. A new sketch opens in your Arduino IDE:

57
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

5. Press the Upload button in the Arduino IDE. Wait a few seconds while the code
compiles and uploads to your board.

6. If everything went as expected, you should see a “Done uploading.” message.

58
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

7. Open the Arduino IDE Serial Monitor at a baud rate of 115200:

8. Press the ESP32 on-board Enable button and you should see the networks available
near your ESP32:

59
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Troubleshooting
If you try to upload a new sketch to your ESP32 and you get this error message “A fatal
error occurred: Failed to connect to ESP32: Timed out… Connecting…“. It means that your
ESP32 is not in flashing/uploading mode.
Having the right board name and COM por selected, follow these steps:
▪ Hold-down the “BOOT” button in your ESP32 board

60
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

▪ Press the “Upload” button in the Arduino IDE to upload your sketch:

▪ After you see the “Connecting….” message in your Arduino IDE, release the finger
from the “BOOT” button:

61
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

▪ After that, you should see the “Done uploading” message


That’s it. Your ESP32 should have the new sketch running. Press the “ENABLE”
button to restart the ESP32 and run the new uploaded sketch.
You’ll also have to repeat that button sequence every time you want to upload a new
sketch. But if you want to solve this issue once for all without the need to press
the BOOT button

PRE-LAB SESSION
1. What type of cable should be used for ESP32?
Ans.
2. Specify ROM size of ESP32?
Ans.
3. Mention the software which is to be installed in the laptop for ESP32 board?
Ans.
4. What is the operating voltage of the GPIO pins in ESP32?
Ans.

GPIO PROGRAMMING
How to write Air Quality measurement using ESP32 ?

62
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

3. ConnectSensors any GPIO Pin (GPIO 4) as per the Circuit Diagram


4. Connect 1K or 470Ω Resistor for current limiting Purpose.

CODE/ PROGRAM

int LED_BUILTIN = 2;
void setup()
{
pinMode (LED_BUILTIN, OUTPUT);
}
void loop()
{
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}

PRECAUTIONS
1. Use insulation tools while you connect the Circuit.
2. Wear Good Insulating Shoes.
3. Avoid contacting circuits with wet hands or wet materials.
4. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
5. Be careful while connecting any actuators in 230V AC Mains.

RESULT

63
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

We successfully setup ESP32 along with LED blinking Program using ArduinoIDE .

INFERENCES/ANALYSIS
POST-LAB ASSIGNMENTS

1. How many GPIO pins are available in the ESP32?


Ans.
2. Mention the number of ADCs available in ESP32?
Ans.
3. How many USB ports are available in the ESP32?
Ans.
4. Mention the number of micro usb ports available in ESP32?
Ans.
5. How many PWM pins are available in the ESP32?
Ans.
6. List out the GND pins available in the ESP32?.
Ans.
7. List out the +3.3 V pins available in the ESP32.
Ans.
8. List out the +5V pins available in the ESP32
Ans.

64
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

ExptNo.:8 Date:
Controlling the GPIO pins in ESP32 using Touch Inputs
AIM
To MPU6050 interface with ESP32 and WEBSERVER using Arduino IDE
Programming.

SOFTWARES USED

ESP32 BOARD (Arduino IDE)

APPARATUS/ COMPONENTS REQUIRED

1. ESP32
2. Connecting Cable
3. DC 5V, 1A Power Adaptor

DESCRIPTION:

Troubleshooting
If you try to upload a new sketch to your ESP32 and you get this error message “A fatal
error occurred: Failed to connect to ESP32: Timed out… Connecting…“. It means that your
ESP32 is not in flashing/uploading mode.
Having the right board name and COM por selected, follow these steps:
▪ Hold-down the “BOOT” button in your ESP32 board

65
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

▪ Press the “Upload” button in the Arduino IDE to upload your sketch:

▪ After you see the “Connecting….” message in your Arduino IDE, release the finger
from the “BOOT” button:

66
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

▪ After that, you should see the “Done uploading” message


That’s it. Your ESP32 should have the new sketch running. Press the “ENABLE”
button to restart the ESP32 and run the new uploaded sketch.
You’ll also have to repeat that button sequence every time you want to upload a new
sketch. But if you want to solve this issue once for all without the need to press
the BOOT button

PRE-LAB SESSION
1. What type of cable should be used for ESP32?
Ans.
2. Specify ROM size of ESP32?
Ans.
3. Mention the software which is to be installed in the laptop for ESP32 board?
Ans.
4. What is the operating voltage of the GPIO pins in ESP32?
Ans.

Circuit Diagram:-

67
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

CODE/ PROGRAM
// set pin numbers
const int touchPin = 4;
const int ledPin = 16;

// change with your threshold value


const int threshold = 20;
// variable for storing the touch pin value
int touchValue;

void setup(){
Serial.begin(115200);
delay(1000); // give me time to bring up serial monitor
// initialize the LED pin as an output:
pinMode (ledPin, OUTPUT);

68
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

void loop(){
// read the state of the pushbutton value:
touchValue = touchRead(touchPin);
Serial.print(touchValue);
// check if the touchValue is below the threshold
// if it is, set ledPin to HIGH
if(touchValue< threshold){
// turn LED on
digitalWrite(ledPin, HIGH);
Serial.println(" - LED on");
}
else{
// turn LED off
digitalWrite(ledPin, LOW);
Serial.println(" - LED off");
}
delay(500);
}
PRECAUTIONS
1. Use insulation tools while you connect the Circuit.
2. Wear Good Insulating Shoes.
3. Avoid contacting circuits with wet hands or wet materials.
4. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
5. Be careful while connecting any actuators in 230V AC Mains.

Results

69
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

INFERENCES/ANALYSIS

70
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

ExptNo.:9 Date:
Barometric Pressure monitoring using ESP32
AIM
To interface pressure sensor BMP085 to ESP32 using Arduino IDE Programming.

SOFTWARES USED
ESP32 BOARD (Arduino IDE)
APPARATUS/ COMPONENTS REQUIRED

1. ESP32
2. Pressure sensor BMP085
3. DC 5V, 1A Power Adaptor
4. Connecting Wires
5. Bread Board

DESCRIPTION:
HARDWARE CONNECTION:

71
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

INSTALL THE NECESSARY LIBRARY FILE:

CODE/PRPGRAM:

72
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

#include <Adafruit_BMP085.h>
Adafruit_BMP085 bmp;;
void setup()
{
Serial.begin(115200);
if (!bmp.begin())
{
Serial.println("BMP180 Sensor not found ! ! !");
while (1)
{

}
}
}

void loop()
{
Serial.print("Temperature = ");
Serial.print(bmp.readTemperature());
Serial.println(" *C");

Serial.print("Pressure = ");
Serial.print(bmp.readPressure());
Serial.println(" Pa");

73
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

// Calculate altitude assuming 'standard' barometric


// pressure of 1013.25 millibar = 101325 Pascal
Serial.print("Altitude = ");
Serial.print(bmp.readAltitude());
Serial.println(" meters");

Serial.print("Pressure at sealevel (calculated) = ");


Serial.print(bmp.readSealevelPressure());
Serial.println(" Pa");

// you can get a more precise measurement of altitude


// if you know the current sea level pressure which will
// vary with weather and such. If it is 1015 millibars
// that is equal to 101500 Pascals.
Serial.print("Real altitude = ");
Serial.print(bmp.readAltitude(102000));
Serial.println(" meters");

Serial.println();
delay(5000);

}
PRECAUTIONS

74
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

1. Use insulation tools while you connect the Circuit.


2. Wear Good Insulating Shoes.
3. Avoid contacting circuits with wet hands or wet materials.
4. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
5. Be careful while connecting any actuators in 230V AC Mains.

RESULT
CHECK THE RESULT IN SERIAL MONITOR WITH 115200 BAUDRATE.

INFERENCES/ANALYSIS

75
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

ExptNo.:10 Date:
Monitoring the Accelerometer and Gyroscope Data in WEB Server using
ESP32
AIM
To MPU6050 interface with ESP32 and WEBSERVER using Arduino IDE
Programming.

SOFTWARES USED

ESP32 BOARD (Arduino IDE)

APPARATUS/ COMPONENTS REQUIRED

1. ESP32
2. MPU6050 sensor
3. Connecting Cable
4. DC 5V, 1A Power Adaptor

DESCRIPTION:

Troubleshooting
If you try to upload a new sketch to your ESP32 and you get this error message “A fatal
error occurred: Failed to connect to ESP32: Timed out… Connecting…“. It means that your
ESP32 is not in flashing/uploading mode.
Having the right board name and COM por selected, follow these steps:
▪ Hold-down the “BOOT” button in your ESP32 board

76
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

▪ Press the “Upload” button in the Arduino IDE to upload your sketch:

▪ After you see the “Connecting….” message in your Arduino IDE, release the finger
from the “BOOT” button:

77
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

▪ After that, you should see the “Done uploading” message


That’s it. Your ESP32 should have the new sketch running. Press the “ENABLE”
button to restart the ESP32 and run the new uploaded sketch.
You’ll also have to repeat that button sequence every time you want to upload a new
sketch. But if you want to solve this issue once for all without the need to press
the BOOT button

Necessary Library Files to install

78
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

79
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

PRE-LAB SESSION
1. What type of cable should be used for ESP32?
Ans.
2. Specify ROM size of ESP32?
Ans.
3. Mention the software which is to be installed in the laptop for ESP32 board?
Ans.
4. What is the operating voltage of the GPIO pins in ESP32?
Ans.

CODING/ PROGRAM

80
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

#include <Wire.h>
#include <WiFi.h>
const int MPU_addr=0x68; // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
// WiFi network info.
const char *ssid= "LAPTOP-HC0UUVHJ 4795"; // Enter your WiFi Name
const char *pass = "U}1723v4"; // Enter your WiFi Password
WiFiServerserver(80);
void setup(){
Serial.begin(115200);
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.println("Wrote to IMU");
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print("."); // print ... till not connected
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address is : ");
Serial.println(WiFi.localIP());

81
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

server.begin();
Serial.println("Server started");
}
void loop(){
mpu_read();
WiFiClient client = server.available();
if (client)
{
Serial.println("new client");
String currentLine = ""; //Storing the incoming data in the string
while (client.connected())
{
if (client.available()) //if there is some client data available
{
char c = client.read(); // read a byte
if (c == '\n') // check for newline character,
{
if (currentLine.length() == 0) //if line is blank it means its the end of the client
HTTP request
{
client.print("<html><title> ESP32 WebServer</title></html>");
client.print("<body bgcolor=\"#E6E6FA\"><h1 style=\"text-align: center; color: blue\">
ESP32 WebServer</h1>");
client.print("<p style=\"text-align: left; color: red; font-size:150% \">Accelerometer Values:
");
client.print("<p style=\"text-align: left; font-size:150% \">AcX: ");
client.print(AcX);
client.print("<br/>AcY: ");

82
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

client.print(AcY);
client.print("<br/>AcZ: ");
client.print(AcZ);
client.print("<p style=\"text-align: left; color: red; font-size:150% \">Gyroscope Values: ");
client.print("<p style=\"text-align: left; font-size:150% \">GyX: ");
client.print(GyX);
client.print("<br/>GyY: ");
client.print(GyY);
client.print("<br/>GyZ: ");
client.print(GyZ);
client.print("</p></body>");
break; // break out of the while loop:
}
else
{ // if you got a newline, then clear currentLine:
currentLine = "";
}
}
else if (c != '\r')
{ // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
}
}
void mpu_read(){
Wire.beginTransmission(MPU_addr);

83
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)


Wire.endTransmission(false);
Wire.requestFrom(MPU_addr,14,true); // request a total of 14 registers
AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C
(ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E
(ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
//Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Serial.print("Accelerometer Values: \n");
Serial.print("AcX: ");
Serial.print(AcX);
Serial.print("\nAcY: ");
Serial.print(AcY);
Serial.print("\nAcZ: ");
Serial.print(AcZ);
//Serial.print("\nTemperature: " );
Serial.print(Tmp);
Serial.print("\nGyroscope Values: \n");
Serial.print("GyX: ");
Serial.print(GyX);
Serial.print("\nGyY: ");
Serial.print(GyY);
Serial.print("\nGyZ: ");
Serial.print(GyZ);

84
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Serial.print("\n");
delay(3000);
}
PRECAUTIONS
1. Use insulation tools while you connect the Circuit.
2. Wear Good Insulating Shoes.
3. Avoid contacting circuits with wet hands or wet materials.
4. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
5. Be careful while connecting any actuators in 230V AC Mains.

Results

85
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

86
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

INFERENCES/ANALYSIS

87
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

ExptNo No.: 11 Date:

Interfacing Servo motor to ESP32


AIM
To interface Servo Motor with ESP8266

SOFTWARES USED
ESP32 BOARD (Arduino IDE)
APPARATUS/ COMPONENTS REQUIRED

1. ESP32
2. Servo Motor
3. DC 5V, 1A Power Adaptor
4. Connecting Wires
5. Bread Board

THEORY:
A servomotor (or servo motor) is a simple electric motor, controlled with the help of
servomechanism. If the motor as a controlled device, associated with servomechanism is DC
motor, then it is commonly known as a DC Servo Motor. If AC operates the controlled motor,
it is known as a AC Servo Motor.Low Power Operation Extends Battery-Backup Run Time. A
servomotor is a linear actuator or rotary actuator that allows for precise control of linear or
angular position, acceleration, and velocity. It consists of a motor coupled to a sensor for
position feedback. It also requires a relatively sophisticated controller, often a dedicated
module designed specifically for use with servomotors.
There are some special types of applications of an electric motor where the rotation of the
motor is required for just a certain angle. For these applications, we require some special types
of motor with some special arrangement which makes the motor rotate a certain angle for a
given electrical input (signal) The servo motor is usually a simple DC motor controlled for
specific angular rotation with the help of additional servomechanism (a typical closed-loop
feedback control system). Nowadays, servo systems are used widely in industrial applications.
Servo motor applications are also commonly seen in remote-controlled toy cars for controlling
the direction of motion, and it is also very widely used as the motor which moves the tray of a
CD or DVD player. Besides these, there are hundreds of servo motor applications we see in
our daily life.

88
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

HARDWARE CONNECTION:

89
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

CODE/PROGRAM:-

#define COUNT_LOW 0
#define COUNT_HIGH 8888

#define TIMER_WIDTH 16

#include "esp32-hal-ledc.h"

void setup() {
Serial.begin(9600);
ledcSetup(1, 50, TIMER_WIDTH); // channel 1, 50 Hz, 16-bit width
ledcAttachPin(14, 1); // GPIO 14 assigned to channel 1
}

void loop() {
for (int i=COUNT_LOW ; i < COUNT_HIGH ; i=i+100)
{
ledcWrite(1, i); // sweep servo 1
Serial.print(1,i);
delay(50);
}

for (int i=COUNT_HIGH ; i > COUNT_LOW ; i=i-100)


{
ledcWrite(1, i); // sweep servo 1
Serial.print(1,i);
delay(50);
}
}
PRECAUTIONS
16. Use insulation tools while you connect the Circuit.
17. Wear Good Insulating Shoes.
18. Avoid contacting circuits with wet hands or wet materials.
19. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
20. Be careful while connecting any actuators in 230V AC Mains.

90
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

RESULT

INFERENCES/ANALYSIS

91
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

ExptNo No.: 12 Date:


Hall Effect value and Temperature from ESP32
AIM
To Observation of Hall Effect value and Temperature from ESP32

SOFTWARES USED

ESP32 BOARD (Arduino IDE)

APPARATUS/ COMPONENTS REQUIRED

1. ESP32
2. DC 5V, 1A Power Adaptor
3. Connecting Wires
4. Bread Board

THEORY:
A hall effect sensor can detect variations in the magnetic field in its surroundings. The greater
the magnetic field, the greater the sensor’s output voltage

The hall effect sensor can be combined with a threshold detection to act as a switch, for
example. Additionally, hall effect sensors are mainly used to:
▪ Detect proximity;
▪ Calculate positioning;
▪ Count the number of revolutions of a wheel;
▪ Detect a door closing;

92
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

HARDWARE CONNECTION:

There is no external sensor connections for this experiment, because there is inbuilt Hall
effect sensor and Temperature Sensor.

CODE/PROGRAM:-

#ifdef __cplusplus
extern "C" {
#endif
uint8_t temprature_sens_read();
#ifdef __cplusplus
}
#endif
uint8_t temprature_sens_read();
#include <WiFi.h>
String apiKey = "Write API key"; // Enter your Write API key from ThingSpeak
const char *ssid = "wifi ssid"; // replace with your wifi ssid and wpa2
key
const char *pass = "wpa2 key";
const char* server = "api.thingspeak.com";
WiFiClient client;
void setup()
{
Serial.begin(115200);
delay(10);
Serial.println("Connecting to ");

93
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

}
void loop()
{

int h = 0;
float t =0;

h = hallRead();
t = ((temprature_sens_read()-32)/1.8); //changing temperature parameter to celsius
if (client.connect(server,80)) // "184.106.153.149" or
api.thingspeak.com
{

String postStr = apiKey;


postStr +="&field1=";
postStr += String(h);
postStr += "&field2=";
postStr += String(t);
postStr += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");


client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);

Serial.print("Hall: ");

94
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

Serial.println(h);
Serial.print("Temperature:");
Serial.print(t);
Serial.println(" C");

Serial.println("%. Send to Thingspeak.");


}
client.stop();
Serial.println("Waiting...");
delay(10000);
}
PRECAUTIONS

1. Use insulation tools while you connect the Circuit.


2. Wear Good Insulating Shoes.
3. Avoid contacting circuits with wet hands or wet materials.
4. Maintain a work space clear of extraneous material such as books, papers, and
clothes.
5. Be careful while connecting any actuators in 230V AC Mains.

Result

95
Koneru Lakshmaiah Education Foundation
21IE2047 PROJECT BASED LEARNING 2

INFERENCES/ANALYSIS

96
Koneru Lakshmaiah Education Foundation

You might also like