IOT

Gas Leakage Detector with Email Alert Notification using ESP32

This project will teach you how to create an ESP32-based gas leak detector with an email notification system. We will utilize the MQ2/MQ5 Gas Sensor to detect LPG in the Air. MQ5 Gas Sensor can detect H2, LPG, CH4, CO, and Alcohol. Due to its heightened Sensitivity and Rapid Response, safety Alerts can be transmitted rapidly.

We will use the ESP32 Mail Client library and an SMTP server to send emails to any address. The email is automatically delivered when a gas/LPG leak is detected that exceeds a specified threshold value. Thus, this ESP32 Email Notifier system alerts users to promptly close the valve or take other action. Through the Local Web Server, activation and deactivation of the system are possible. If we choose to deactivate this feature, we will no longer receive email alerts when the gas level is surpassed. This system can be used as a safety system in industry or at home.

Hardware Required

S.N.COMPONENTS NAMEDESCRIPTION
1ESP32 BoardESP32 ESP-32S Development Board (ESP-WROOM-32)
2Gas SensorMQ2/MQ5 Sensor
3Data Cable5V Micro USB Data Cable
4USB Adapter5V Volt USB Adapter
5Breadboard

MQ5 Gas Sensor

MQ5 Gas Sensor is the most commonly used analog gas sensor. The MQ5 gas sensor detects a variety of gases, including hydrogen, carbon monoxide, methane, and LPG. The sensor interacts with gas to determine its concentration between 100ppm and 3000ppm.

MQ5 Gas Sensor

When a gas interacts with this sensor, it is first ionized and then adsorbed by the sensor’s sensing element. This adsorption generates a potential difference in the element, which is transmitted to the controller unit as the current through an analog output pin. Thus, the analog current is measured as an output that grows with a rising gas level.

The Sensor operates between 3V and 5V and includes both an analog and digital output. It has four pins labeled VCC, GND, D0, and A0. Check out its datasheet here to understand more about this Sensor.MQ5 Datasheet.

You can check some of the previous projects made using this Sensor:

Hardware Circuit Assembly

We are able to create a small battery-powered device. In my case, I assembled and tested the device using a Breadboard. Below is the Circuit Diagram for the “ESP32 Gas Leak Detector with Email Alert Notification.”

ESP32 Gas Sensor

Connect the Sensor VCC Pin to the 3.3V/5V of the ESP32 Board. We do not use the digital Pin, hence the Sensor Analog Pin is connected to GPIO35 on the ESP32 Board.

ESP32 Gas Leakage Detector

PCB Designing & Ordering Online

This project’s PCB was designed using the online PCB design programme EasyEDA. The front view and back view of the PCB are shown below. Gerber Viewer of NextPCB.

The Gerber file for all the PCB is given below. You can download the Gerber file and order the PCB online from NextPCB.

Download Gerber File

Now you can visit the NextPCB official website by clicking here: https://www.nextpcb.com/. So you will be directed to NextPCB website.

You can now upload the Gerber File and place an order on the website. The PCB quality is excellent and spotless. This is why the majority of individuals rely on NextPCB for PCB & PCBA Services.

Setting Up Sender Email Address

Create a New Gmail Account from here: https://www.google.com/gmail/about/. Its better not to use the Personal Gmail Account for this purpose.

esp32 send email

Now you must let less secure apps access to your new Gmail account created with ESP32. If you disable this option, you may not be able to configure the ESP32 Email Alert component.Go to this link & turn on the “allow less secure” option.

Note: Turn OFF two-step Verification to access this.

Installing the Required Libraries

1. ESP32 Mail Client Library

To send emails with the ESP32, the ESP32 Mail Client library will be utilized. Mobizt created the library, which can be installed using Library Manager. Here you may download the library.

Download ESP32 Mail Client Library

2. Asynchronous Web Server Libraries

To create an asynchronous web server, two libraries are required: the ESPAsyncWebServer library and the Async TCP Library.

Download ESPAsyncWebServer Library & Download AsyncTCP Library

Source Code: ESP32 Gas Leakage Detector with Email Alert Notification

Let us now proceed to the programming section of this project. First, add all of the previously described Libraries.

Before uploading the code to the ESP32 Board, make the adjustments described below to the copied code.

const char* ssid = “***********”;        //SSID of Wifi network
const char* password = “***********”;   // Password of wifi network

Change the Wifi SSID and password from this page.

#define emailSenderAccount    “examplesender@gmail.com”    // Sender email address
#define emailSenderPassword   “***********”            // Sender email password

Change the Sender Email and enter the Email Address and Password you already set.

String inputMessage = “examplereceiver@gmail.com”;   //Reciepent email alert.

Enter the email address to which you would want to send the Alert Email.

// Default Threshold Value
String inputMessage3 = “40.0”;                    // Default gas_value

Change the gas’s threshold value from here. When the gas level exceeds this threshold, an email alert will be sent.

That is the entirety of the code modifications required prior to uploading it to the ESP32 board. The complete code is shown below.

#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include “ESP32_MailClient.h”
 
const char* ssid = “***********”;        //SSID of Wifi network
const char* password = “***********”;   // Password of wifi network
 
#define emailSenderAccount    “examplesender@gmail.com”    // Sender email address
#define emailSenderPassword   “***********”            // Sender email password
#define smtpServer            “smtp.gmail.com”
#define smtpServerPort        465
#define emailSubject          “ALERT! Gas Leak Detected”   // Email subject
 
 
String inputMessage = “examplereceiver@gmail.com”;   //Reciepent email alert.
String enableEmailChecked = “checked”;
String inputMessage2 = “true”;
 
// Default Threshold Value
String inputMessage3 = “40.0”;                    // Default gas_value
String lastgaslevel;
 
 
// HTML web page to handle 3 input fields (email_input, enable_email_input, threshold_input)
const char index_html[] PROGMEM = R”rawliteral(
<!DOCTYPE HTML><html><head>
  <title>Email Notification with Gas Level</title>
  <meta name=”viewport” content=”width=device-width, initial-scale=1″>
  </head><body>
  <h2>Gas Level Detection</h2>
  <h3>%GASVALUE%</h3>
  <h2>ESP Email Alert</h2>
  <form action=”/get”>
    Email Address <input type=”email” name=”email_input” value=”%EMAIL_INPUT%” required><br>
    Enable Email Notification <input type=”checkbox” name=”enable_email_input” value=”true” %ENABLE_EMAIL%><br>
    Gas Level Threshold <input type=”number” step=”0.1″ name=”threshold_input” value=”%THRESHOLD%” required><br>
    <input type=”submit” value=”Submit”>
  </form>
</body></html>)rawliteral”;
 
void notFound(AsyncWebServerRequest *request)
{
  request->send(404, “text/plain”, “Not found”);
}
AsyncWebServer server(80);
 
String processor(const String& var)
{
  if(var == “GASVALUE”)
  {
    return lastgaslevel;
  }
  else if(var == “EMAIL_INPUT”)
  {
    return inputMessage;
  }
  else if(var == “ENABLE_EMAIL”)
  {
    return enableEmailChecked;
  }
  else if(var == “THRESHOLD”)
  {
    return inputMessage3;
  }
  return String();
}
 
 
// Flag variable to keep track if email notification was sent or not
bool emailSent = false;
const char* PARAM_INPUT_1 = “email_input”;
const char* PARAM_INPUT_2 = “enable_email_input”;
const char* PARAM_INPUT_3 = “threshold_input”;
 
// Interval between sensor readings.
unsigned long previousMillis = 0;
const long interval = 5000;    
 
SMTPData smtpData;
 
 
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(“ESP IP Address: http://”);
  Serial.println(WiFi.localIP());
  
 
  // Send web page to client
  server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, “text/html”, index_html, processor);
  });
  // Receive an HTTP GET request at <ESP_IP>/get?email_input=<inputMessage>&enable_email_input=<inputMessage2>&threshold_input=<inputMessage3>
  server.on(“/get”, HTTP_GET, [] (AsyncWebServerRequest *request) {
    // GET email_input value on <ESP_IP>/get?email_input=<inputMessage>
    if (request->hasParam(PARAM_INPUT_1)) {
      inputMessage = request->getParam(PARAM_INPUT_1)->value();
      // GET enable_email_input value on <ESP_IP>/get?enable_email_input=<inputMessage2>
      if (request->hasParam(PARAM_INPUT_2)) {
        inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
        enableEmailChecked = “checked”;
      }
      else
      {
        inputMessage2 = “false”;
        enableEmailChecked = “”;
      }
      // GET threshold_input value on <ESP_IP>/get?threshold_input=<inputMessage3>
      if (request->hasParam(PARAM_INPUT_3)) {
        inputMessage3 = request->getParam(PARAM_INPUT_3)->value();
      }
    }
    else {
      inputMessage = “No message sent”;
    }
    Serial.println(inputMessage);
    Serial.println(inputMessage2);
    Serial.println(inputMessage3);
    request->send(200, “text/html”, “HTTP GET request sent to your ESP.<br><a href=\”/\”>Return to Home Page</a>”);
  });
  server.onNotFound(notFound);
  server.begin();
}
 
 
 
void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis – previousMillis >= interval) {
    previousMillis = currentMillis;
 
    float gas_analog_value = analogRead(35);
    float gas_value = ((gas_analog_value/1023)*100);
    Serial.print(gas_analog_value);
    Serial.print(“, “);
    Serial.println(gas_value);
    
    lastgaslevel = String(gas_value);
    
    // Check if gas_value is above threshold and if it needs to send the Email alert
    if(gas_value > inputMessage3.toFloat() && inputMessage2 == “true” && !emailSent){
      String emailMessage = String(“Gas Level above threshold. Current Gas Level: “) +
                            String(gas_value));
      if(sendEmailNotification(emailMessage)) {
        Serial.println(emailMessage);
        emailSent = true;
      }
      else {
        Serial.println(“Email failed to send”);
      }    
    }
    // Check if gas_value is below threshold and if it needs to send the Email alert
    else if((gas_value < inputMessage3.toFloat()) && inputMessage2 == “true” && emailSent)
    {
      String emailMessage = String(“Gas Level below threshold. Current gas_value: “) +
                            String(gas_value) + String(” C”);
      if(sendEmailNotification(emailMessage))
      {
        Serial.println(emailMessage);
        emailSent = false;
      }
      else {
        Serial.println(“Email failed to send”);
      }
    }
  }
}
 
 
bool sendEmailNotification(String emailMessage)
{
  // Set the SMTP Server Email host, port, account and password
  smtpData.setLogin(smtpServer, smtpServerPort, emailSenderAccount, emailSenderPassword);
  
  smtpData.setSender(“ESP32_Gas_Alert_Mail”, emailSenderAccount);
  
  // Set Email priority or importance High, Normal, Low or 1 to 5 (1 is highest)
  smtpData.setPriority(“High”);
  
  // Set the subject
  smtpData.setSubject(emailSubject);
  
  // Set the message with HTML format
  smtpData.setMessage(emailMessage, true);
  
  // Add recipients
  smtpData.addRecipient(inputMessage);
  smtpData.setSendCallback(sendCallback);
  
  if (!MailClient.sendMail(smtpData))
{
    Serial.println(“Error sending Email, ” + MailClient.smtpErrorReason());
    return false;
  }
  smtpData.empty();
  return true;
}
 
 
void sendCallback(SendStatus msg)
{
  // Print the current status
  Serial.println(msg.info());
  
  // Do something when complete
  if (msg.success())
{
    Serial.println(“—————-“);
  }
}

ESP32 Gas Leakage Detector with Email Alert Notification

Now that the code has been uploaded to the ESP32 Board, the Serial Monitor can be opened. The Serial Monitor will reveal the ESP32 Board’s IP Address. It will display the entire process from beginning to conclusion, including Mail Server Starting and Email Sending, if the threshold is exceeded.

In addition to displaying the Gas Level, it will also display the Analog value.

Now Copy the IP Address and paste it into any web browser, such as Chrome, before pressing “Enter.” The Web Browser will display the Gas Value and the Set Threshold Value beside the Gas Value.

Here, you may enable or disable the Email Alert form by simply checking or unchecking the corresponding box. You can also modify the Email Address and the Gas Threshold Value. Simply enter the value and press the Send button.

Open your Gmail inbox to view Email Message Alerts sent using ESP32 over the SMTP Mail Server.

ESP32 Email Notification

Conclusion

Hope this blog helps you to understand how to design a Gas Leakage Detector with Email Alert Notification using ESP32. We, MATHA ELECTRONICS will come back with more informative blogs.

Leave a Reply

Your email address will not be published.