Hello readers, I hope you all are doing great. In this tutorial, we will learn how to access Firebase (a real-time database) to store and read values or data with ESP32.
It is Google’s mobile application development platform that can be used to can access, monitor and control ESP32 from anywhere in the world with its (firebase) real-time database.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
Firebase real-time database is a development platform provided by Google which included multiple services to manage and authenticate data.
Firebase is basically a mobile and web app development platform I as works great with Android APIs) that includes features like firebase cloud, real-time data and Firebase authentication etc.
As per Firebase’s official documentation (https://firebase.google.com/docs/database), whenever a user creates a cross-platform application like with Android, or Apple, JavaScript SDKs, all the clients share a single.
Fig. 1 Firebase Real-time database and ESP32
The main features of the Firebase Real-time database are:
The IoT or Internet of Things is the interconnection of physical objects or devices with sensors and software accessing capabilities to communicate data or information over the internet.
To build an IoT network, we need an interface medium that can fetch, control, and communicate data between sender and receiver electronics devices or servers.
Firebase real-time database provides a platform to store data collected from sensors at the level device. Firebase works great with Android APIs.
Firebase is particularly useful in data-intensive Internet of things (IoT) applications to store from sensors and synch that data between users in real-time. For simplicity or better understanding we can say that it is a cloud service provided by Google for real-time collaborative apps.
The steps involved in creating a Firebase project are:
Fig. 2 Get started
Fig. 3 Create a project
Fig. 4 project name
Fig. 5 Enabling Google Analytics
Fig. 6 Project Created successfully
As per the official firebase documentation at: https://firebase.google.com/docs/auth , the identity of a user is required by most online services or mobile applications or we can say , it handles authentication process and logging in (in this tutorial, the ESP32). Getting to know the identity of a user enables an application to save user data securely in the cloud and provide a consistent personalized service across all of the customer's devices (android phones, computers, applications etc).
Fig. 7 Authentication
Fig. 8 Select authentication method
Next thing is creating a real-time database for the project.
Fig. 9 Real-time database
Fig. 10 Creating database
Fig. 11
Fig. 12 select location
Fig. 13 Accessing project API key
We are using Arduino IDE to compile and upload code into the ESP32 module. You must have the ESP32 board manager installed on your Arduino IDE to program the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. The link is given below:
https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html
Steps to add the necessary libraries in Arduino IDE:
Fig. 14 manage libraries
Fig. 15 Install Firebase ESP Client Library
//--add necessary header files
#include <WiFi.h>
#include <Firebase_ESP_Client.h>
#include "addons/TokenHelper.h" //Provide the token generation process info.
#include "addons/RTDBHelper.h" //Provide the real-time database payload printing info and other helper functions.
// Insert your network credentials
#define WIFI_SSID "replace this with your netwrok SSID"
#define WIFI_PASSWORD "replace this with your wi-fi password"
// Insert Firebase project API Key
#define API_KEY "replace this with your API key"
// ----Insert real-time database URL
#define DATABASE_URL "replace this with your project URL"
//----Define Firebase Data object
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
int value = 10;
bool signupSuccess = false;
unsigned long sendDataPrevMillis = 0;
void setup()
{
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(100);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP() );
Serial.println();
// Assign the api key ( required)
config.api_key = API_KEY;
// Assign the RTDB URL ( required)
config.database_url = DATABASE_URL;
// Sign up status
if (Firebase.signUp(&config, &auth, "", ""))
{
Serial.println("ok");
signupSuccess = true;
}
else{
Serial.printf("%s\n", config.signer.signupError.message.c_str());
}
/* Assign the callback function for the long running token generation task */
config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h
Firebase.begin(&config, & auth);
Firebase.reconnectWiFi( true);
}
void loop()
{
if (Firebase.ready() && signupSuccess && (millis() - sendDataPrevMillis >
10000 || sendDataPrevMillis == 0))
{
sendDataPrevMillis = millis();
if (Firebase.RTDB.setInt(&fbdo, "test/int", value))
{
Serial.println("PASSED");
Serial.println("PATH: " + fbdo.dataPath());
Serial.println("TYPE: " + fbdo.dataType());
}
else
{
Serial.println("FAILED");
Serial.println("REASON: " + fbdo.errorReason());
}
value++;
}
}
Before uploading the code in ESP32 board there are some changes you need to make which includes:
Fig. 16 Header files
Fig. 17 Helper libraries
Fig. 18 Insert API key
Fig. 19 RTDB URL
Fig. 20 Firebase Data Objects
Fig. 21 Enter Network credentials
Fig. 22 variable declaration
Fig. 23 Initialize wifi module
Fig. 24 Fetch/obtain the IP address
Fig. 25 configuring API key
Fig. 26 configuring database URL
Fig. 27 sign up status
Fig. 28
Fig. 29 Loop() function
Fig. 30 Select development board and COM port
Fig. 31 Result 1
Fig. 32 Result 2
This concludes the tutorial. I hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.
Hello readers, I hope you all are doing great. In this tutorial, we will learn how to interface the BMP280 sensor with the ES32 module to get temperature, pressure and altitude readings. Later, in this tutorial, we will also discuss how to upload these sensor readings to a web server.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
BMP280 or Barometric pressure sensor is a module used to measure temperature pressure and altitude. The small size and low power consumption feature of this sensor makes it feasible for battery-powered devices, GPS modules and mobile applications etc.
Fig. 1 BMP280 Sensor
The BMP280 is the product of BOSCH which is based on Bosch’s proven Piezo-resistive pressure sensor technology featured with high accuracy, long term stability, linearity and high EMC robustness.
BMP280 is the successor of the BMP180 sensor and offers high performance in all the areas that require precise temperature and pressure measurements.
Emerging applications like fitness, indoor navigation, GPS refinement requires relative accuracy and BMP280 is perfect for such applications. Very low TCO (Temperature coefficient of Offset ) makes this module preferable over other available modules for temperature measurements.
We can also use a DHT11/DHT22 sensor for temperature and humidity measurements but the BMP280 sensor provides better accuracy (i.e., 0.01°C) than DHT sensors.
There are two methods of interfacing BMP280 sensor with ESP32 module:
In the bMP280 Sensor module, there are six interfacing pins including VCC and GND.
Fig. Interfacing BMP280 and ESP32
We are using the I2C protocol for interfacing the two (ESP and BMP280) so only SCL and SDA pins will be used with power pins for interfacing. The SDO and CSB pins will be used only if you are using the SPI protocol for interfacing.
Table 1
We are using Arduino IDE to compile and upload code into the ESP32 module. You must have ESP32 board manager installed on your Arduino IDE to program the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. The link is given below:
https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html
Steps to add the necessary libraries in Arduino IDE:
Fig. 2 manage libraries
Fig. 3 Install library
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(115200);
Serial.println("\nI2C Scanner");
}
void loop()
{
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for(address = 1; address < 127; address++ )
{
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
{
Serial.print("0");
}
Serial.println(address,HEX);
nDevices++;
}
else if (error==4)
{
Serial.print("Unknow error at address 0x");
if (address<16) {
Serial.print("0");
}
Serial.println(address,HEX);
}
}
if (nDevices == 0) {
Serial.println("No I2C devices found\n");
}
else {
Serial.println("done\n");
}
delay(5000);
}
#include <Wire.h>
#include <Adafruit_BMP280.h>
#define BMP_SDA 21
#define BMP_SCL 22
Adafruit_BMP280 bmp280;
void setup()
{
Serial.begin(115200);
Serial.println("Initializing BMP280");
boolean status = bmp280.begin(0x76);
if (!status)
{
Serial.println("Not connected");
}
}
void loop()
{
float temp = bmp280.readTemperature();
Serial.print("temperature: ");
Serial.print(temp);
Serial.println("*C");
float altitude = bmp280.readAltitude(1011.18);
Serial.print("Altitude: ");
Serial.print(altitude);
Serial.println("m");
float pressure = (bmp280.readPressure()/100);
Serial.print("Pressure: ");
Serial.print(pressure);
Serial.println("hPa");
Serial.println(" ");
delay(1000);
}
Fig. 6
Fig. 7
Fig. 8
Fig. 9
Fig. 10 Select development board and COM port
Fig. 11 Serial monitor output
Most of the industries and organizations these days are shifting to the efficient ways of operating things and the IoT internet of things is one of them.
Internet of Things is a system of multiple inter-related computing devices. The factor ‘thing’ in IoT is designated to an entity capable of communicating data over a network (IOT), which can be a digital machine, sensor, human being, animals etc.
Each component that is included in IoT network is assigned with an unique identity called UID and the ability to communicate data over IoT network without any external human or computer intervention.
Fig. 12 IoT
ThingSpeak is an open data platform for the Internet of Things applications. It is a MathWorks web service that allows users to send sensor readings and data to the cloud. We can also visualize and act on the data (calculate the data) that is sent to ThingSpeak by the devices. The information can be saved in both private and public channels.
ThingSpeak is frequently used for IoT prototyping and proof-of-concept devices that require data analysis.
Downloading and installing the required Library file:
https://github.com/mathworks/thingspeak-arduino
Fig. 13 Adding ThingSpeak library
To check whether the library is successfully added or not:
Fig. 14
Fig, 15 Arduino IDE Library manager
Fig. 16 Getting started for free
Fig. 17 Create new account
Fig. 18 MathWorks Sign in
Fig. 19 New Channel
Fig. 20 Creating channel and respective fields
Fig. 21 save the channel
Fig. 22 Field Chart Edit
// ------style guard ----
#ifdef __cplusplus
extern "C"
{
#endif
uint8_t temprature_sens_read();
#ifdef __cplusplus
}
#endif
uint8_t temprature_sens_read();
// ------header files----
#include <WiFi.h>
#include "ThingSpeak.h"
#include <Wire.h>
#include <Adafruit_BMP280.h>
#define BMP_SDA 21
#define BMP_SCL 22
Adafruit_BMP280 bmp280;
// -----netwrok credentials
const char* ssid = "public"; // your network SSID (name)
const char* password = "ESP32@123"; // your network password
WiFiClient client;
// -----ThingSpeak channel details
unsigned long myChannelNumber = 4;
const char * myWriteAPIKey = "9R3JZEVBG73YE8BY";
// ----- Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 1000;
void setup()
{
Serial.begin(115200); // Initialize serial
Serial.println("Initializing BMP280");
boolean status = bmp280.begin(0x76);
if (!status)
{
Serial.println("Not connected");
}
//Initialize Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(100);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
// Initialize ThingSpeak
ThingSpeak.begin(client);
}
void loop()
{
if ((millis() - lastTime) > timerDelay )
{
float temp = bmp280.readTemperature(); //temperature measurement
Serial.print("temperature: ");
Serial.print(temp);
Serial.println("*C");
float altitude = bmp280.readAltitude(1011.18); //altitude measurement
Serial.print("Altitude: ");
Serial.print(altitude);
Serial.println("m");
float pressure = (bmp280.readPressure()/100); //pressure measurement
Serial.print("Pressure: ");
Serial.print(pressure);
Serial.println("hPa");
Serial.println(" ");
ThingSpeak.setField(1, temp );
ThingSpeak.setField(2, altitude);
ThingSpeak.setField(3, pressure);
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeFields(myChannelNumber,
myWriteAPIKey );
if(x == 200)
{
Serial.println("Channel update successful." );
}
else
{
Serial.println("Problem updating channel. HTTP error code " + String(x) );
}
lastTime = millis();
}
}
We are describing only the ThingSpeak server part as the BMP280 and ESP32 interfacing part has already been discussed in the above code description.
Fig. 23 Style guard
Fig. 24 Libraries
Fig. 25
Fig. 26
Fig. 27
Fig. 28
Fig. 29
Fig. 30
Fig. 31
Fig. 32 Sensor readings
Fig. 33 setting respective Fields
Fig. 34
Fig. 35
Fig. 36 ThingSpeak server
Fig. 37 Sensor readings on the Serial monitor
This concludes the tutorial. I hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.
Hello readers, I hope you all are doing great.
ESP32 is a powerful chip for Internet of Things applications. This tutorial is also based on one of the ESP32 applications in the field of IoT.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
In this tutorial, we will learn how to update LCD display with new data or input using a web server created with ESP32.
Fig. 1
To achieve the target, we will be using an HTML (Hypertext Markup Language) form to provide web input and then update the text displayed on LCD. The values or input received from the webserver will be further stored inside a variable in the code for further use (to display on LCD).
We have already posted a tutorial on LCD (Liquid Crystal Display) interfacing with ESP32. In that tutorial, we demonstrated how to display the hard-coded data (in the ESP32 module) on LCD.
A web server is computer software and hardware that accepts requests and responds to those requests using HTTP (Hypertext transfer protocol) or HTTPS (HTTP Secure) (HTTP is a network protocol for delivering online content to client user agents).
The ESP32 standalone web server is mobile-enabled and can be accessed from any device with a browser on the local network. B. Mobile phones, computers, laptops, tablets. However, all the devices must be connected to the same WiFi network to which the ESP32 is connected.
There are basically two ways to connect the ESP32 to a 16 * 2 LCD display.
Connecting an LCD display without an I2C adapter is cheap, but this method requires more connection cables and is complicated to implement. On the other hand, using an I2C adapter reduces complexity but increases cost. In this tutorial, you will connect the ESP32 directly without using an I2C adapter.
Table: 1
Fig. 2: ESP32 and 16*2 LCD interfacing
For more details on interfacing 16*2 LCD with ESP32, follow our previous tutorial at www.theengineeringprojects.com
We are using Arduino IDE to compile and upload code into ESP32 module. You must have ESP32 board manager installed on your Arduino IDE to program ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. The link is given below:
https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html
ESP32 board manager doesn’t come with inbuilt libraries to create an asynchronous web server. So we need to download the library file from external sources and then add into Arduino IDE.
We need to install two library files:
Once you have successfully downloaded the required libraries, next step it to install or add these libraries in Arduino IDE.
To add the libraries in Arduino IDE, go to Sketch >> Include Library >> Add .zip library and then select the downloaded library files.
Fig. 3: adding necessary libraries
#include < WiFi.h >
#include < AsyncTCP.h >
#include < ESPAsyncWebServer.h >
#include < LiquidCrystal.h > // LCD header file
LiquidCrystal lcd (22, 23, 5, 18, 19, 21 );
AsyncWebServer server ( 80 );
// Enter your netwrok credentials
const char* ssid = "replace this with netwrok SSID";
const char* password = "replace this with Password";
const char* PARAM_INPUT_1 = "data_field1";
const char* PARAM_INPUT_2 = "data_field2";
// HTML web page to handle data input fields
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML> <html> <head>
<title> ESP Input Form </title>
<meta name = " viewport" content="width=device-width, initial-scale=1 ">
<style>
html{ font-family: Times New Roman; display: inline-block; text-align: justify;}
</style>
</head> <body>
<form action="/get">
Data_field1: <input type="text" name="data_field1" >
<input type="submit" value="Post ">
</form> <br>
<form action="/get">
Data_field2: <input type="text" name="data_field2">
<input type="submit" value="Post">
</form><br>
</body></html>)rawliteral";
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed!");
return;
}
Serial.println();
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
//===set LCD
lcd.begin(16, 2);
lcd.clear();
lcd.setCursor(1,0);
server.onNotFound(notFound);
server.begin();
// Send web page with input fields to client
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send_P(200, "text/html", index_html);
});
server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
String inputParam;
// GET input1 value
if (request->hasParam(PARAM_INPUT_1))
{
inputMessage = request->getParam(PARAM_INPUT_1)->value();
inputParam = PARAM_INPUT_1;
}
// GET input2 value
else if (request->hasParam(PARAM_INPUT_2))
{
inputMessage = request->getParam(PARAM_INPUT_2)->value();
inputParam = PARAM_INPUT_2;
}
else
{
inputMessage = " No message sent";
inputParam = " none";
}
Serial.println ( inputMessage );
delay( 1000);
lcd.clear();
lcd.print( inputMessage);
request-> send (200, "text/html", " HTTP GET request sent to ESP32("
+ inputParam + "): " + inputMessage +
"<br><a href=\"/\"> Back to Home Page </a>");
});
}
void loop( )
{
}
Fig. 4: Adding header files
Fig. 5: LCD data and control pins
Fig. 6: server port
Fig. 7: Enter Network credentials
Fig. 8
Fig. 9: HTML web page
Fig. 10: HTML form for data input
Fig. 11: Post button.
Fig. 12
Fig. 13: Fetch/obtain the IP adrress
Fig. 14: Set 16*2 LCD
Fig. 15: Initialize the server
Fig. 16: Send web page to client
Fig. 17
Fig. read the input from HTML form
Fig. 18
Fig. 19
Fig. 20
Fig. 21: Select development board and COM port
Fig. 22: web Page
Fig. 23: Enter the Input to ESP32
Fig. 24: Input Updated
Fig. 25: IP address and Web Input on serial monitor.
Fig. 26: String input received from Web server, printed on LCD
This concludes the tutorial. We hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.
Hello readers, I hope you all are doing great. In this tutorial, we will learn how to update a webpage using Server-Sent Events and the ESP32 web server.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
It is a server push technology that enables the client devices to receive automatic updates from a server over HTTP (Hypertext Transfer Protocol) connection. SSE also describes how the server can initiate data transmission towards the client once an initial connection with the client has been established.
We have already posted a tutorial on how to implement Web socket protocol with ESP32 which is also a protocol used to notify events to a web client. Both the Server-Sent Events (SSE) and Web-Socket technologies seem to be quite similar but they are not.
The major difference between the two is that SSE is unidirectional, where the web client can only receive the updates from the ESP32 but it can’t send updates back to ESP32. On the other hand, the Web-socket protocol is bi-directional where both the web client and ESP32 can send and receive updates/events.
Fig. 1 Server-Sent event
The Server-Sent Event process initiates with an HTTP request from the web client or web page to the ESP32 web server. After that, the ESP32 is ready to send updates or events to the web client as they happen. But the web client can’t send any response or data to the ESP32 server after the initial handshake takes place.
Server-sent event technology can be used to communicate an event, GPIO states or to send sensor readings to the web client, whenever a new reading is observed.
For demonstration purpose, we are using a DHT11 sensor with the ESP32 module. ESP32 web server will display two things i.e., temperature and humidity observed using the DHT11 sensor. So, whenever a new reading is being observed, the ESP32 sends the reading to the Web Client over Server-sent events. After receiving the latest sensor reading the client updates the web page data.
Fig. 2 DHT11 sensor
DHT11 is a humidity and temperature sensor that measures its surrounding environment. It measures the temperature and humidity in a given area. It is made up of an NTC (negative temperature co-efficient) temperature sensor and a resistive humidity sensor. It also has an 8-bit microcontroller. The microcontroller is in charge of ADC (analog to digital conversion) and provides a digital output over the single wire protocol.
The DHT11 sensor can measure humidity from 20% to 90% with +-5 percent accuracy (RH or relative humidity) and temperature from 0 degrees Celsius to 50 degrees Celsius with +-2C accuracy.
DHT11 sensors can also be used to build a wired sensor network with a cable length of up to 20 meters.
Table 1
Note: Connect a 10K resistor between data and power (+5V) pin of DHT11 sensor module.
Fig. 3 ESP32 and DHT11 connections/wiring
We are using Arduino IDE to compile and upload code into the ESP32 module. You must have ESP32 board manager installed on your Arduino IDE to program the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. The link is given below:
https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html
Fig. 4 manage libraries
Fig. 5 Install DHT sensor library
ESP32 board manager doesn’t come with inbuilt libraries to create an asynchronous web server. So we need to download the library file from external sources and then add into Arduino IDE.
We need to install two library files:
Once you have successfully downloaded the required libraries, next step it to install or add these libraries in Arduino IDE.
To add the libraries in Arduino IDE, go to Sketch >> Include Library >> Add .zip library and then select the downloaded library files.
Fig. 6 adding necessary libraries
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "DHT.h"
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
// Initializing the DHT11 sensor.
DHT dht(DHTPIN, DHTTYPE);
// Replace with your network credentials
const char* ssid = "SSID";
const char* password = "password";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// Create an Event Source on /events
AsyncEventSource events("/events");
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 20000; //20 sec timer delay
//==== Creating web page
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<title>SSE with ESP32 Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="icon" href="data:,">
<style>
html {font-family: Times New Roman; display: inline-block; text-align: justify;}
p { font-size: 1.2rem;}
body { margin: 0;}
.topnav { overflow: hidden; background-color: blue; color: white; font-size: 1rem; }
.content { padding: 20px; }
.card { background-color: #ADD8E6; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5); }
.cards { max-width: 600px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
.reading { font-size: 1.4rem; }
</style>
</head>
<body>
<div class="topnav">
<h1>Server-Sent Events </h1>
<h2> DHT11 Sensor Data </h2>
</div>
<div class="content">
<div class="cards">
<div class="card">
<p> DHT11 Temperature</p><p><span class="reading"><span id="temp">%TEMPERATURE%</span> °C</span></p>
</div>
<div class="card">
<p> DHT11 Humidity</p><p><span class="reading"><span id="hum">%HUMIDITY%</span> %</span></p>
</div>
</div>
</div>
<script>
if (!!window.EventSource)
{
var source = new EventSource('/events');
source.addEventListener('open', function(e)
{
console.log("Events Connected");
}, false);
source.addEventListener('error', function(e)
{
if (e.target.readyState != EventSource.OPEN)
{
console.log("Events Disconnected");
}
}, false);
source.addEventListener('message', function(e)
{
console.log("message", e.data);
}, false);
source.addEventListener('temperature', function(e)
{
console.log("temperature", e.data);
document.getElementById("temp").innerHTML = e.data;
}, false);
source.addEventListener('humidity', function(e)
{
console.log("humidity", e.data);
document.getElementById("hum").innerHTML = e.data;
}, false);
}
</script>
</body>
</html>)rawliteral";
void setup() {
Serial.begin(115200); //initialize serial monitor
//===set and initialize Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print('.');
delay(1000);
}
Serial.print("IP Address: ");
Serial.println(WiFi.localIP()); // print the IP address
//====Initialize DHT11 sensor
dht.begin();
//====Handle Web Server
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html);
});
// Handle Web Server Events
events.onConnect([](AsyncEventSourceClient *client)
{
if(client->lastId())
{
Serial.printf("Client reconnected! Last message ID that it got is: %u\n",
client->lastId());
}
// send event with message "hello!", id current millis
// and set reconnect delay to 1 second
client->send("hello!", NULL, millis(), 10000);
});
server.addHandler(&events);
server.begin();
}
void loop()
{
delay(2000);
float humidity = dht.readHumidity();
// Read temperature as Celsius (the default)
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature))
{
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
if ((millis() - lastTime) > timerDelay)
{
// Send Events to the Web Server with the Sensor Readings
events.send("ping",NULL,millis());
events.send(String(temperature).c_str(),"temperature",millis());
events.send(String(humidity).c_str(),"humidity",millis());
Serial.print(F("Humidity(%): "));
Serial.println(humidity);
Serial.print(F("Temp.: "));
Serial.print(temperature);
Serial.println(F("°C "));
}
}
Fig. 7 Header files
Fig. 8 Global declarations
Fig. 9
Fig. 10 Enter Network credentials
Fig. 11 Server port
Fig. 12 Event source
Fig. 13 Timer Variables
Fig. 14
Fig. 15
Fig. 16
Fig. 17
Fig. 18
Fig. 19
Fig. 20
Fig. 21 Fetch/obtain the IP address
Fig. 22 Initialize DHT sensor
Fig. 23
Fig. 24 Handling server events
Fig. 24 initializing web server
Fig. 25
Fig. 26 If error occurs while reading data from DHT11
Fig. 27 Sending events to the server
Fig. 28 Print Sensor data on the Serial monitor
Fig. 29 Select development board and COM port
Fig. 30
Fig. 31
This concludes the tutorial. I hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.
ESP32 module comes with multiple inbuilt features and peripheral interfacing capability is one of those features. ESP32 module also consists of an inbuilt temperature sensor, but that can only measure the temperature of the ESP32 core not the temperature of the surrounding environment. So it is required to use a peripheral sensor to measure the temperature of the surrounding environment like home, garden, office etc.
Hello readers. I hope you all are doing great. In this tutorial, we will learn how to interface DHT11 (temperature and humidity sensor) with the ESP32. Later in this tutorial, we will discuss how to share the sensor readings obtained from the DHT11 sensor to a web server.
Before moving towards the interfacing and programming part, let’s have a short introduction to the DHT11 sensor, its working and its connections.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
Fig. 1: DHT11 sensor
DHT11 is used to measure humidity and temperature from its surrounding. It monitors the ambient temperature and humidity of a given area. It consists of an NTC (negative temperature co-efficient) temperature sensor and a resistive type humidity sensor. It also consists of an 8-bit microcontroller. The microcontroller is responsible for performing ADC (analog to digital conversion) and provides a digital output over the single wire protocol.
DHT11 sensor can measure humidity from 20% to 90% with +-5% (RH or relative humidity) of accuracy and can measure the temperature in the range of 0 degrees Celsius to 50 degrees Celsius with +-2C of accuracy.
DHT11 sensors can also be used to implement a wired sensor system using a cable length of up to 20 meters.
There are two DHT modules (DHT11 and DHT22) available in the market to measure temperature and humidity. The purpose of both module are same but with different specifications. Like DHT22 sensor provides broader temperature and humidity sensitivity ranges. But DHT22 is costlier than DHT11. So you can prefer to use any of the module, as per your requirements.
Table: 1
Note: Connect a 10K resistor between data and power (+5V) pin of DHT11 sensor module.
Fig. 2: ESP32 and DHT11 connections/wiring
We are using Arduino IDE to compile and upload code into ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. Link is given below:
https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html
DHT11 sensor uses single wire protocol to communicate data which requires a precise timing. In order to interface DHT11 sensor with ESP32 module it is required to add necessary libraries. To install the DHT11 sensor library;
Fig. 3: manage libraries
Fig. 4: Install DHT sensor library
#include "DHT.h"
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
// Initializing the DHT11 sensor.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println(F("DHT test string!"));
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print(F("Humidity(%): "));
Serial.println(h);
Serial.print(F("Temp.: "));
Serial.print(t);
Serial.println(F("°C "));
Serial.print(F("Temp.: "));
Serial.print(f);
Serial.println(F("°F "));
Serial.print(F("Heat index: "));
Serial.println(hic);
Serial.println(" ");
Serial.print(F("°C "));
Serial.print(hif);
Serial.println(F("°F"));
}
Fig. 5: Add necessary libraries
Fig. 6: Global declarations
Fig. 7
Fig. 9
Fig. 10
Fig. 11
Fig. 12: Heat index
Fig. ESP32 and DHT11 interfacing
Fig. 13: Readings observed from DHT11 sensor
The IoT is the interconnection of physical objects or devices with sensors and software accessing capabilities to communicate data or information over the internet.
To build an IoT network, we need an interface medium that can fetch, control, and communicate data between sender and receiver electronics devices or servers.
Espressif Systems created the ESP32 Wi-Fi chip series. The ESP32 module is equipped with a 32-bit Tensilica microcontroller, 2.4GHz Wi-Fi connectivity, an antenna, memory, and power management modules, and much more. All of these built-in features of this ESP32 module make it ideal for IoT applications.
It is an open data platform for the Internet of Things (Internet of Things). ThingSpeak is a MathWorks web service that allows us to send sensor readings/data to the cloud. We can also visualise and act on the data (calculate the data) sent to ThingSpeak by the devices. Data can be stored in both private and public channels.
ThingSpeak is commonly used for internet of things prototyping and proof of concept systems requiring analytics.
Fig. 14: Getting started for free
Fig. 15: Create new account
Fig. 16: MathWorks Sign in
Fig. 17: New Channel
Fig. 18: Fill the channel details
Fig. 19: Field Chart Edit
https://github.com/mathworks/thingspeak-arduino
Fig. 20: Adding ThingSpeak library
To check whether the library is successfully added or not:
Fig. 21: manage libraries
Fig. 22: Arduino IDE Library manager.
//------style guard ----
#ifdef __cplusplus
extern "C" {
#endif
uint8_t temprature_sens_read();
#ifdef __cplusplus
}
#endif
uint8_t temprature_sens_read();
// ------header files----
#include <WiFi.h>
#include "DHT.h"
#include "ThingSpeak.h"
//-----netwrok credentials
char* ssid = "replace this with your SSID"; //enter SSID
char* passphrase = "replace this with your password"; // enter the password
WiFiServer server(80);
WiFiClient client;
//-----ThingSpeak channel details
unsigned long myChannelNumber = 3;
const char * myWriteAPIKey = "replace this with your API key";
//----- Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 1000;
//----DHT declarations
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
// Initializing the DHT11 sensor.
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
Serial.begin(115200); //Initialize serial
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, passphrase);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
//----nitialize dht11
dht.begin();
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop()
{
if ((millis() - lastTime) > timerDelay)
{
delay(2500);
// Reading temperature or humidity takes about 250 milliseconds!
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
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;
}
Serial.print("Temperature (ºC): ");
Serial.print(t);
Serial.println("ºC");
Serial.print("Humidity");
Serial.println(h);
ThingSpeak.setField(1, h);
ThingSpeak.setField(2, t);
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeFields(myChannelNumber,
myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
lastTime = millis();
}
}
Fig. 23: Libraries
Fig. 24
Fig. 25: server port
Fig. 26
Fig. 29
Fig. 30: connect to wifi
Fig.31: Fetch and print IP address
Fig. 32
Fig. 33
Fig. 34
Fig. 35
Fig. 36: Displaying humidity on thingSpeak server
Fig. 37: Displaying Temperature on ThingSpeak server
This concludes the tutorial. I hope you found this of some help and also hope to see you soon with new tutorial on ESP32.
The IoT is the interconnection of physical objects or devices with sensors and software accessing capabilities to communicate data or information over the internet.
To build an IoT network, we need an interface medium that can fetch, control, and communicate data between sender and receiver electronics devices or servers.
Espressif Systems created the ESP32 Wi-Fi chip series. The ESP32 module is equipped with a 32-bit Tensilica microcontroller, 2.4GHz Wi-Fi connectivity, an antenna, memory, and power management modules, and much more. All of these built-in features of this ESP32 module make it ideal for IoT applications.
Hello readers, I hope you all are doing great. In this tutorial, we will learn another application of ESP32 in the field of IoT (Internet of Things). We are using a PIR sensor to detect motion and an Email alert will be generated automatically whenever a motion is being detected.
Fig.1
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
The HCSR-501 sensor module is used with ESP32 to detect the motion. So whenever a motion is detected, the PIR sensor will generate a HIGH output signal which will act as an input to the ESP32 module. In the absence of motion, the output of the PIR sensor will remain LOW. If a HIGH input signal is generated from the PIR sensor module, the LED (either peripheral or inbuilt) will be turned ON and along with that, an Email will be generated to the receiver’s email address as per the program instructions.
Fig. 2 PIR Motion Sensor
PIR stands for Passive Infrared sensors. It detects heat energy in the surrounding environment using a pair of pyroelectric sensors. Both sensors are placed next to each other, and when motion is detected or the signal differential between the two sensors changes, the PIR motion sensor returns a LOW result (logic zero volts). It means that in the code, you must wait for the pin to go low. The desired function can be called when the pin goes low.
There are two potentiometers available in the HCSR-501 PIR motion sensor module. One of the potentiometers is to control the sensitivity to the IR radiations. Lower sensitivity indicates the presence of a moving leaf or a small mouse. The sensitivity can be changed depending on the installation location and project specifications.
The second potentiometer is to specify the duration for which the detection output should be active. It can be programmed to turn on for as few as a few seconds or as long as a few minutes.
PIR sensors are used in thermal sensing applications such as security and motion detection. They're commonly found in security alarms, motion detection alarms, and automatic lighting applications.
The simple mail transfer protocol (SMTP) is an internet standard for sending and receiving electronic mail (or email), with an SMTP server receiving emails from email clients.
SMTP is also used to establish server-to-server communication.
Gmail, Hotmail, Yahoo, and other email providers all have their own SMTP addresses and port numbers.
Fig. 3 SMTP
To send emails, the SMTP protocol, also known as the push protocol, is used, and IMAP, or Internet Message Access Protocol (or post office protocol or POP), is used to receive emails at the receiver end.
The SMTP protocol operates at the application layer of the TCP/IP protocol suite.
When the client wants to send emails, a TCP connection to the SMTP server is established, and emails are sent over the connection.
SMTP commands:
There are various email service providers available like, Gmail, Yahoo, Hotmail, Outlook etc. and each service provider have unique service parameters.
In this tutorial, we are using the Gmail or Google Mail service.
Gmail is the email service provided by Google and Gmail SMTP server is free to access and anyone can access this service, who has a Gmail account.
It is recommended to create a new email account for sending emails using ESP32 or ESP8266 modules.
If you are using your main (personal) email account (for sending emails) with ESP and by mistake something goes wrong in the ESP code or programming part, your email service provider can ban or disable your main (personal) email account.
In this tutorial we are using a Gmail account.
Follow the link to create a new Gmail account : https://accounts.google.com
Fig. 4 create new gmail account
To get access to this new Gmail account, you need to enable Allow less secure apps and this will make you able to send emails. The link is attached below:
https://myaccount.google.com/lesssecureapps?pli=1
Fig. 5 permission to less secure apps
Table 1
Fig. 6 ESP32 and HCSR-501 connections
We are using Arduino IDE to compile and upload code into ESP32 module. To know more about ESP32 basics, Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. Link is given below:
https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html
To enable the email service in ESP32 it is required to download the ESP-Mail-Client Library. This library makes the ESP32 able to send email over SMTP server.
Follow the steps to install the ESP-Mail-Client library:
https://github.com/mobizt/ESP-Mail-Client
Fig. 7 Adding ESP-Mail-Client Library
//To use send Email for Gmail to port 465 (SSL), less secure app option should be enabled. https://myaccount.google.com/lesssecureapps?pli=1
//----Add the header files
#include <WiFi.h>
#include <ESP_Mail_Client.h>
//-----define network credentials
#define WIFI_SSID "public"
#define WIFI_PASSWORD "ESP32@123"
//--add the Server address and port number with respect to a particular email service provider
#define SMTP_HOST "smtp.gmail.com"
#define SMTP_PORT esp_mail_smtp_port_587 //port 465 is not available for Outlook.com
//----The log in credentials
#define AUTHOR_EMAIL "techeesp697@gmail.com"
#define AUTHOR_PASSWORD "Tech@ESP123"
//----The SMTP Session object used for Email sending
SMTPSession smtp;
//---Declare the message class
SMTP_Message message;
//---Callback function to get the Email sending status
void smtpCallback(SMTP_Status status);
const char rootCACert[] PROGMEM = "-----BEGIN CERTIFICATE-----\n"
"-----END CERTIFICATE-----\n";
int inputPin = 4; // connect with pir sensor pin
int pir_output = 0; // variable to store the output of PIR output
void setup()
{
pinMode(inputPin, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
pir_output = digitalRead(inputPin);
Serial.println();
Serial.print("Connecting to AP");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(200);
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
/** Enable the debug via Serial port
* none debug or 0
* basic debug or 1
*
* Debug port can be changed via ESP_MAIL_DEFAULT_DEBUG_PORT in ESP_Mail_FS.h
*/
smtp.debug(1);
/* Set the callback function to get the sending results */
smtp.callback(smtpCallback);
/* Declare the session config data */
ESP_Mail_Session session;
/* Set the session config */
session.server.host_name = SMTP_HOST;
session.server.port = SMTP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
session.login.user_domain = "mydomain.net";
/* Set the NTP config time */
session.time.ntp_server = "pool.ntp.org,time.nist.gov";
session.time.gmt_offset = 3;
session.time.day_light_offset = 0;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Email Alert on Motion detection";
message.addRecipient("Anonymous",
"replace this with receiver email adderss");
String textMsg = "Motion Detected!!!!!";
message.text.content = textMsg;
message.text.charSet = "us-ascii";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/* Set the custom message header */
message.addHeader("Message-ID: <abcde.fghij@gmail.com>");
/* Connect to server with the session config */
if (!smtp.connect(&session))
return;
}
void loop()
{
if (pir_output == HIGH)
{
//----Start sending Email and close the session
if (!MailClient.sendMail(&smtp, &message))
Serial.println("Error sending Email, " + smtp.errorReason());
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("Motion detected!");
Serial.println("Email sent");
}
else {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("No Motion detected!");
}
delay(1000);
ESP_MAIL_PRINTF("Free Heap: %d\n", MailClient.getFreeHeap());
//to clear sending result log
smtp.sendingResult.clear();
}
/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Print the sending result */
if (status.success())
{
Serial.println("----------------");
ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());
ESP_MAIL_PRINTF("Message sent failled: %d\n", status.failedCount());
Serial.println("----------------\n");
struct tm dt;
for (size_t i = 0; i < smtp.sendingResult.size(); i++)
{
/* Get the result item */
SMTP_Result result = smtp.sendingResult.getItem(i);
time_t ts = (time_t)result.timestamp;
localtime_r(&ts, &dt);
ESP_MAIL_PRINTF("Message No: %d\n", i + 1);
ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");
ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec);
ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients);
ESP_MAIL_PRINTF("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
//You need to clear sending result as the memory usage will grow up as it keeps the status, timstamp and
//pointer to const char of recipients and subject that user assigned to the SMTP_Message object.
//Because of pointer to const char that stores instead of dynamic string, the subject and recipients value can be
//a garbage string (pointer points to undefind location) as SMTP_Message was declared as local variable or the value changed.
smtp.sendingResult.clear();
}
}
Note: The exact code cannot be used. As a result, before uploading the code, you must make some changes such as replacing the SSID and password with your network credentials, email address of sender and receiver, SMTP setting parameters for respective email service providers, and so on. We'll go over these details as well during the code description.
Fig. 8
Fig. 9
Fig. 10
Fig. 11
Fig. 12
Fig. 13
Fig. 14
Fig. 15
Fig. 16
Fig. 17 Variable for PIR sensor
Fig. 18
Fig. 19
Fig. 20
Fig. 21
Fig. 22
Fig. 23
Fig. 24
Fig. 25 ‘If motion detected’
Fig. 25 No motion detected
Fig. 26 Clear the email log
Fig. 27 select development board and COM port
Fig. 28 ESP32’s Inbuilt LED is turned ON when a motion is detected
Fig. 29 Serial monitor
Fig.30 received email on motion detection
This concludes the tutorial. We hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.
Hello readers, we hope you all are doing great. Welcome to the 1st lecture of Section 4 in the ESP32 Programming Series. In this section, we will interface the ESP32 module with common Embedded modules(i.e. LCD, Keypad, RTC etc.).
In today's tutorial, we will interface ESP32 with a 16x2 LCD and will display data using both Data Mode and I2C Mode. LCD is the most commonly used embedded module in IoT Projects. It is used to display different types of data i.e. sensor readings, warning messages, notifications etc.
Before going forward, let's first have a look at what is LCD and How it works:
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
LCD(Liquid Crystal Display) is a type of electronic display module that is used in a wide variety of applications and devices such as calculators, computers, mobile phones, TVs, etc. There are different types of LCDs available for commercial use. Today, we are going to use the most simple one i.e. 16x2 LCD, shown in the below figure:
This 16x2 LCD has 16 columns and 2 rows, so in total of 32 blocks to display characters. Each Block can display a single character at a time. We can display text in different styles on this LCD i.e. blinking, scrolling etc. Another variant of this LCD is 20x4 LCD and as the name suggests, it has 20 columns and 4 rows and so can display 80 characters at a time. The operating principle of both of these LCDs is quite similar. So, if you are working with a 20x4 LCD, you can still follow this tutorial.
Let's have a look at the LCD pinout:
Both 16x2 and 20x4 LCDs have 16 pins each, used to control 7 write on these LCDs. Among these 16 pins, we have:
LCD Pinout and its working is shown in the below table:
LCD Pinout |
||||
---|---|---|---|---|
Pin No. | Name | Working | ||
1 |
GND(Ground) |
Connected to Ground Terminal. |
||
2 |
Vcc(+5V) |
Connected to +5V. |
||
3 |
VE |
To Control the LCD Contrast. |
||
4 |
RS(Register Select) | If RS=0(GND), LCD operates in Data Mode and we can write characters on the LCD. |
||
If RS=1(+5V), LCD Command Mode gets activated and we can send commands to LCD i.e. erase, new line etc.. |
||||
5 |
R/W(Read & Write) | R/W=0(GND) enables the write operation on the LCD. (So, we normally keep this pin LOW, as we are interested in printing on the LCD). | ||
R/W=1(+5V) enables the read operation on the LCD. |
||||
6 |
EN(Enable) |
Enables the LCD to operate, so it should be kept HIGH. |
||
7 |
Data Pin 0 |
LCD has a total of 8 Data Pins(D0-D7) | ||
8 |
Data Pin 1 |
|||
9 |
Data Pin 2 |
|||
10 |
Data Pin 3 |
|||
11 |
Data Pin 4 |
|||
12 |
Data Pin 5 |
|||
13 |
Data Pin 6 |
|||
14 |
Data Pin 7 |
|||
15 |
LED+ |
Connected to +5V. Turn on the backlight LED. |
||
16 |
LED- |
Connected to GND. |
Now, let's interface the LCD with ESP32:
There are two methods to interface ESP32 with a 16x2 LCD:
In the Data Mode, we use the LCD Data Pins and send data serially, while in the I2C mode, we solder an I2C adapter with the LCD, which acts as a bridge and maps I2C data coming from the microcontroller to the Data Pins. Let's first interface ESP32 and LCD via Data Pins:
As we discussed earlier, LCD has 8 Data Pins used to communicate with the Microcontroller. There are two ways to send data from the Microcontroller to the LCD:
In complex projects, where you are dealing with multiple sensors & modules, its quite difficult to spare 8 Pins for LCD interfacing. So, normally 4-Pin method is preferred, which we are going to design next:
Here are the components required to interface LCD with ESP32:
Now, let's design the ESP32 LCD Circuit Diagram:
[Image]
As you can see in the above figure:
Here's our hardware setup for ESP32 LCD Interfacing:
[Image]
Now let's design the Programming Code to print a simple message on the LCD:
We are using Arduino IDE to compile and upload code in the ESP32 module. If you haven't installed it yet, please read How to Install ESP32 in Arduino IDE. Here's the code to print a message on the LCD:
#include
LiquidCrystal lcd(22,23,5,18,19,21);
void setup()
{
lcd.begin(16, 2);
lcd.clear();
// go to row 0 column 5, note that this is indexed at 0
lcd.setCursor(5,0);
lcd.print("ESP32");
// go to row 1 column 0, note that this is indexed at 0
lcd.setCursor(0,1);
lcd.print (" TheEnggProjects");
}
void loop()
{
}
#include
LiquidCrystal lcd(22,23,5,18,19,21);
In the Setup() Function:
lcd.begin(16, 2);
So, if you are using a 20x4 LCD, you should change its arguments to 20 and 4, as shown below:
lcd.begin(20, 4);
lcd.clear();
lcd.setCursor(5,0);
lcd.print("ESP32");
lcd.setCursor(0,1);
lcd.print (" TheEnggProjects");
As you can see, the LCD code is quite simple and I hope now you can easily print on the LCD. So, let's check the results:
Fig. 6
Sol. : Check the EN pin.
Fig. 7
This concludes the tutorial. We hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | 7-Segment Display | Amazon | Buy Now | |
2 | Arduino Uno | Amazon | Buy Now |
In this project, we will need two softwares first is the Arduino IDE which is used for Arduino programming. As we are going to make this project in simulation, we will use Proteus simulation software. Proteus is a simulation software for electronics projects. In this software, we can run the real time simulation of electronics circuits and debug them without damaging any real components.
And it is a good practice to make any circuit in the simulation first if we do that for the first time.
And Proteus has a very large database for electronics components but it lacks some new component libraries, for that we have to install some libraries for those components. In this, we have to install a library for the Arduino UNO module.
We should first download the Arduino UNO library.
We will need the following components for this project
As we know counters are simple electronic circuits which count some values and after reaching the maximum value they will reset. In this project, we will make an Up-Down counter which means our counter will count from 0-9 and again after 9-0.
We will use the 7 segment display for showing the counter values. In this project, we have used the common ground type of LED display. And two push buttons to start the counter in up counting or in down counting. When we press the UP push button, then the Arduino will activate the pins as per the up counting and LED will display numbers from 0-9 and when we press the DOWN push button then the Arduino will activate the pin as per the down counting and LED will display numbers from 9-0.
To control the LEDs, Arduino will set the pins as HIGH and LOW as per the truth table for the common ground display.
Arduino will set the pins and LED will display the numbers.
Now we know the working of our counter so let’s make the circuit for the same:
Now we will start writing the code of the Up-Down counter. The code of this project will be divided into three major parts. In the first part, we will declare all the required variables and pins. In the second part, we will set the modes of pins and set the initial states to pins and do the required configuration if needed and the last part we will write our main functionality of our project which we want to run continually.
After the circuit and the coding part, we are all set to run the simulation:
I hope we have covered all the points related to this project. I think it will be a useful project for learning purposes and gives an understanding about working of counters. Please let us know in the comment section if you have faced any issues while making this project.
Thanks for reading this article. See you in the next project.
In this project, we are going to make a water level indicator. We all know it is one of the most essential products because there are many water tanks in every house or office, and most of them are not easily accessible to check the level of water in it and I think most of us faced the problem such as shortage of water as we do not have anything to monitor the exact amount of water available in the tank and this causes many problems on our daily lives.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | LEDs | Amazon | Buy Now | |
2 | Arduino Uno | Amazon | Buy Now |
As we are going to make this project in the simulation first, for that, we will use the Proteus simulation tool. It is a tool used for electronic projects in which, we can run the real-time simulation of any electronic project and we can debug it in real-time without making any damage to real components.
Proteus has a very big database for electronic components which comes in the installation package of Proteus, but still, sometimes we have to install packages or libraries for some modules which are not pre-installed in it.
As in this project, we are going to use Arduino which is not pre-installed in the Proteus software. So we can download the Arduino module package from the link given below:
Note- While uploading the code on the Arduino UNO, disconnect any wire which is connected to Rx(D0) and Tx(D1) pins, otherwise it will give an error while uploading the code.
The water level indicator works on the principle of change in the resistance of the water level sensor due to a change in the amount of water in the container.
Basically, there are two parallel strips in the water level sensor, one for the power supply and another is for the sensor strip. As we know, water is a conductor of electricity so when we increase the amount of water in the container then more length of the sensor emerges in the water and that will increase the conductivity between the strips therefore, it increases the voltage on the sensor pin as well. We will read that voltage on the Arduino UNO.
To get the exact amount of water level in the container, we have to calibrate the sensor with the water because we can not be assured that the output voltage will be the same for every water because we know that there are lots of materials dissolved in the water so it will vary for a different source of water, therefore, we have to calibrate it first.
For calibration of the sensor, we will take a container with the water and we will read the values from the sensor by changing the level of water in the container. We will perform this action till the container gets filled with water and we will note down all the reference values and mark them as thresholds for each level.
As in this project, we are making it in the simulation so it would not be possible for changing the values as per the water level therefore we have used the potentiometer and we have chosen the threshold values randomly.
No need to worry while making this project with the real components as the sensor values from the water level sensor will be in the same format as the output of the potentiometer.
Now that we know the working principle of the water level indicator let’s go for the circuit diagram of the project.
As we know the required components which we are going to use in this project.
For coding, we will use the Arduino IDE. It is a built-in IDE for Arduino developments.
Arduino code is divided into mainly three parts: declaration of function and variables, second is void setup section, and third is void loop.
First of all, declare the variables and pin number which we are going to use in this project.
Now we have completed our code and circuit, it's time to run the project.
I hope we have covered all the points related to this project, and I think it will be very useful in daily life and it will give us ease of monitoring water in our water tanks. After this project, we don’t have to take the headache of how much water is available in our tank. And please let us know in the comment section if you have faced any issues while making it and also how you are going to use it in real life.
Thanks for reading this article. All the best for your projects.
Hello readers, we hope you all are doing great. Welcome to the 4th lecture of Section 5(ESP32 Sensor) in the ESP32 Programming Series. So far, we have discussed the ESP32 built-in sensors in this section. Today, we are going to interface an external embedded sensor(i.e. PIR Sensor) with the ESP32 Microcontroller board. At the start, we will discuss the basics of a PIR Sensor(HC-SR501) i.e. its pinout and working. After that, we will design a simple project to detect the motion with a PIR sensor and ESP32. Finally, we will display the motion detection results on the ESP32 WebServer.
We will use ESP32 interrupts to detect the motion. Interrupts are used when a microcontroller needs to continuously monitor an event while executing other tasks at the same time. We have already posted a tutorial on ESP32 Interrupts, which includes both software and hardware interrupts. In this tutorial, we are implementing the hardware interrupt(Hardware interrupts are the external interrupts that are caused by an external event). In our project, the hardware interrupt will be generated by the PIR sensor.
PIR motion sensor is mostly used in home automation & security projects, used to enable the system to respond automatically over human presence. Appliances connected to ESP32 will respond automatically(as per the instructions provided) whenever an interrupt is triggered by the PIR motion sensor. Let's first have a look at the working of PIR Sensor:
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
In today's project, we will use the HC-SR501 PIR Sensor to detect the motion. PIR stands for Passive Infrared sensors. It uses a pair of pyroelectric sensors to detect heat energy in the surrounding environment. Both the sensors sit beside each other, and when a motion is detected or the signal differential between the two sensors changes the PIR motion sensor will return a LOW result (logic zero volts). It means that you must wait for the pin to go low in the code. When the pin goes low, the desired function can be called.
PIR Sensor has two variable resistors on its back side, used to adjust the Sensitivity and Detection Range, explained below:
Thermal sensing applications, such as security and motion detection, make use of PIR sensors. They're frequently used in security alarms, motion detection alarms, and automatic lighting applications.
Now let's interface the PIR Sensor with ESP32:
As I mentioned earlier, in today's project, we will design a motion detection project with ESP32 and PIR Sensor. In the first example, we will turn "ON" the LED on motion detection, while in the second project, we will display the results in the ESP32 WebServer.
Here's the list of the components for today's project:
Here's the circuit diagram for motion detection with ESP32 and PIR Sensor:
Now let's design the programming code for motion detection:
We are using Arduino IDE to compile and upload code into the ESP32 module. You need to first Install ESP32 in Arduino IDE to get started. Here's the code for motion detection:
//----Set GPIOs for LED and PIR Motion Sensor
const int led = 23;
const int PIRSensor = 4;
// -----Timer: Auxiliary variables
#define timeSeconds 10
unsigned long now = millis();
unsigned long lastTrigger = 0;
boolean startTimer = false;
//---Checks if motion was detected, sets LED HIGH and starts a timer
void IRAM_ATTR detectsMovement()
{
Serial.println( " MOTION DETECTED " );
Serial.println("Turning ON the LED");
digitalWrite(led, HIGH);
startTimer = true;
lastTrigger = millis();
}
void setup()
{
Serial.begin( 115200 ); // Serial port for debugging purposes
pinMode( PIRSensor, INPUT_PULLUP ); // PIR Motion Sensor mode INPUT_PULLUP
pinMode( led, OUTPUT );
digitalWrite( led, LOW );
attachInterrupt( digitalPinToInterrupt( PIRSensor ), detectsMovement, FALLING ); // Set PIRSensor pin as interrupt, assign interrupt function and set RISING mode
}
void loop()
{
now = millis();
if( startTimer && (now - lastTrigger > ( timeSeconds*500)))
{
Serial.println(" Turning OFF the LED " );
digitalWrite( led, LOW );
startTimer = false;
}
}
//----Set GPIOs for LED and PIR Motion Sensor
const int led = 23;
const int PIRSensor = 4;
//-----Timer: Auxiliary variables
#define timeSeconds 10
unsigned long now = millis();
unsigned long lastTrigger = 0;
boolean startTimer = false;
//---Checks if motion was detected, sets LED HIGH and starts a timer
void IRAM_ATTR detectsMovement()
{
Serial.println( " MOTION DETECTED " );
Serial.println("Turning ON the LED");
digitalWrite(led, HIGH);
startTimer = true;
lastTrigger = millis();
}
void setup()
{
Serial.begin( 115200 ); // Serial port for debugging purposes
pinMode( PIRSensor, INPUT_PULLUP ); // PIR Motion Sensor mode INPUT_PULLUP
pinMode( led, OUTPUT );
digitalWrite( led, LOW );
attachInterrupt( digitalPinToInterrupt( PIRSensor ), detectsMovement, FALLING ); // Set PIRSensor pin as interrupt, assign interrupt function and set RISING mode
}
We have activated the interrupt in the Setup Function, so when the PIR Sensor detects the motion, it will automatically execute the interrupt function, which will turn the LED ON and start the timer.
void loop()
{
now = millis();
if( startTimer && (now - lastTrigger > ( timeSeconds*500)))
{
Serial.println(" Turning OFF the LED " );
digitalWrite( led, LOW );
startTimer = false;
}
}
This concludes the tutorial. I hope you find this tutorial helpful. Thanks for reading. See you soon with a new tutorial on ESP32. Take care !!!