Introduction: Flammable Gas Detector/alarm

Hello

This is a tutorial on how to make a gas detector / alarm using an ESP32-Stick-POE-P. The basic idea is that there will be a flammable gas sensor which if triggered sends an email to let you know.

Supplies

Step 1: Connecting

If your MQ-2 has 4 PINs and not 3 than use analog PIN (commonly marked with letter A)


Than just connect your ESP32 to USB-C and Ethernet cable and we're done with connecting

Step 2: Code

We'll be using VSCode with PlatformIO extension installed.


So, after installing PlatformIO click at a "Bee icon" and then select "PIO Home>Open"


Click on "New Project" give your project a name, select board "Adafruit ESP32 Feather" and hit Finish


After that open file "platformio.ini" and check if all info is same as here:


[env:featheresp32]
platform = espressif32@2.0.0
board = esp32dev
framework = arduino
monitor_speed = 115200


If not, rewrite anything that is missing or is different



Now for the main code.


You will find it in "src>main.cpp"



(Everything marked with "//" or written between "/* */" is comment. That means it's not a code, but a text written to help you understand it better. Try to read it and see, if you understand what's going on)


//this adds library
#include <ETH.h>
#include <Arduino.h>
#include <ESP_Mail_Client.h>

#ifdef ETH_CLK_MODE
#undef ETH_CLK_MODE
#endif


//this defines important iner pins
#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT
#define ETH_POWER_PIN   -1
#define ETH_TYPE        ETH_PHY_LAN8720
#define ETH_ADDR        1
#define ETH_MDC_PIN     23
#define ETH_MDIO_PIN    18


#define SMTP_HOST "smtp.gmail.com"
#define SMTP_PORT 465


/* The sign in credentials */
#define AUTHOR_EMAIL "xxx@xxx.com"
#define AUTHOR_APP_PASSWORD "xxx"


/* Recipient's email*/
#define RECIPIENT_EMAIL "xxx@xxx.com"


int lastSensorState = LOW;


/* The SMTP Session object used for Email sending */
SMTPSession smtp;


/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status);

//this defines LED pin
#define ReadPIN         35                

//var telling us if we're connected
static bool eth_connected = false;        

/*
 *  this is a method that checks what kind of WiFi event happend and than prints out important info to
* console
 */
void WiFiEvent(WiFiEvent_t event)
 {
  switch (event)
   {

    //if event is "START" this prints it out to console and setsup hostname
    case SYSTEM_EVENT_ETH_START:
      Serial.println("ETH Started");
      ETH.setHostname("esp32-ethernet");
      break;

      //if event is "CONNECTED" this prints it out to console
    case SYSTEM_EVENT_ETH_CONNECTED:
      Serial.println("ETH Connected");
      break;

      /*if event is "ETH_GOT_IP" this prints out all important info to console (MAC, IPv4, etc.) and
sets eth_connected to true*/
    case SYSTEM_EVENT_ETH_GOT_IP:
      Serial.print("ETH MAC: ");
      Serial.print(ETH.macAddress());
      Serial.print(", IPv4: ");
      Serial.print(ETH.localIP());
      if (ETH.fullDuplex()) {
        Serial.print(", FULL_DUPLEX");
      }
      Serial.print(", ");
      Serial.print(ETH.linkSpeed());
      Serial.println("Mbps");
      eth_connected = true;
      break;

      //if event is "DISCONNECTED" this prints it out to console and sets eth_connected to false
    case SYSTEM_EVENT_ETH_DISCONNECTED:
      Serial.println("ETH Disconnected");
      eth_connected = false;
      break;

      //if event is "ETH_STOP" this prints it out to console and sets eth_connected to false
    case SYSTEM_EVENT_ETH_STOP:
      Serial.println("ETH Stopped");
      eth_connected = false;
      break;

      //default does nothing
    default:
      break;
  }
}


/*
 *  this is first called methode that setup everything
 */
void setup() {
  //this setup LED pin
  pinMode(ReadPIN, INPUT);  

  //this setup console and print in it that esp32 stick is started    
  Serial.begin(115200);
  Serial.println("ESP32-Stick begin\n");

  //this setup WifiEvent as method that activates when WiFi starts event
  WiFi.onEvent(WiFiEvent);

  //this passes important pins to ETH
  ETH.begin(ETH_ADDR, ETH_POWER_PIN, ETH_MDC_PIN, ETH_MDIO_PIN, ETH_TYPE, ETH_CLK_MODE);


 
}

/*
 *  this methode is called as second and will loop forever
 */
void loop() {

  //if ETH is connected start controling st
  if (eth_connected)
   {
    int currentSensorState = analogRead(ReadPIN);
    if (currentSensorState > 2050)
    {


      Serial.println(currentSensorState);


        /** Enable the debug via Serial port
       * none debug or 0
       * basic debug or 1
      */
      smtp.debug(1);

      /* 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_APP_PASSWORD;
      session.login.user_domain = "";


      /* Declare the message class */
      SMTP_Message message;


      /* Set the message headers */
      message.sender.name = "Fire Sensor";
      message.sender.email = AUTHOR_EMAIL;
      message.subject = "SENSOR TRIGGERED";
      message.addRecipient("Sara", RECIPIENT_EMAIL);


      /*Set HTML message*/
      String htmlMsg = "<div style=\"color:#2f4468;\"><h1>SENSOR WAS TRIGGERED</h1><p>Your house might be filled with gas<br/>- Sent from ESP board</p></div>";
      message.html.content = htmlMsg.c_str();
      message.html.content = htmlMsg.c_str();
      message.text.charSet = "us-ascii";
      message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;


      /*Connects to server and sends email*/
      while(true)
      {
        if (!smtp.connect(&session))
          continue;


        /* Start sending Email and close the session */
        if (!MailClient.sendMail(&smtp, &message))
        {
          Serial.println("Error sending Email, " + smtp.errorReason());
          continue;
        }
        break;
      }


      /*Freez program till the gass is no longer in room*/
      while(true)
      {
        Serial.println(analogRead(ReadPIN));
        if(analogRead(ReadPIN) < 1250)
          break;
      }
     
    }
     
  }


}


Now let's change some things so the code would work for you.

Step 3: Email

You'll need to create new email account. Name it whatever you like.

I would recommend using gmail becos that's what I'll be using but other services can also be used.


Alright. Now we need to find our application key. To find yours follow this tutorial: here


After that let's change the code to suit your needs:


Change these two settings to fit a service your using. If you don't kow what to fill in use Google to find out

#define SMTP_HOST "smtp.gmail.com"
#define SMTP_PORT 465


Change these two settings to your new email and its application key

#define AUTHOR_EMAIL "xxx@xxx.com"
#define AUTHOR_APP_PASSWORD "xxx"


And lastly change this seeting to email you would like to recive the notifications on

#define RECIPIENT_EMAIL "xxx@xxx.com" 


You can also change messege you'll be sending but that requiers a basic knowlidge of HTML

String htmlMsg = "<div style=\"color:#2f4468;\"><h1>SENSOR WAS TRIGGERED</h1><p>Your house might be filled with gas<br/>- Sent from ESP board</p></div>";


Now just save, hit CTRL-ALT-U and click on "connector" icon on bottom blue line and you're done

Good job :D