ESP8266 - Gas Sensor Relay
This tutorial instructs you how to use the ESP8266, gas sensor and relay do activate the fan or siren when detecting the LPG, smoke, alcohol, propane, hydrogen, methane and carbon monoxide, or other flammable gasses.
Hardware Preparation
Or you can buy the following sensor kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.
Additionally, some of these links are for products from our own brand, DIYables.
Overview of Relay and MQ2 Gas Sensor
If you do not know about relay and MQ2 Gas Sensor (pinout, how it works, how to program ...), learn about them in the following tutorials:
Wiring Diagram
This image is created using Fritzing. Click to enlarge image
See more in ESP8266's pinout and how to supply power to the ESP8266 and other components.
ESP8266 Code
/*
* This ESP8266 NodeMCU code was developed by newbiely.com
*
* This ESP8266 NodeMCU code is made available for public use without any restriction
*
* For comprehensive instructions and wiring diagrams, please visit:
* https://newbiely.com/tutorials/esp8266/esp8266-gas-sensor-relay
*/
#define DO_PIN D1 // The ESP8266 pin connected to DO pin of the MQ2 sensor
#define RELAY_PIN D7 // The ESP8266 pin connected to relay
void setup() {
// Initialize the Serial to communicate with the Serial Monitor.
Serial.begin(9600);
// initialize the ESP8266 pin as an input
pinMode(DO_PIN, INPUT);
pinMode(RELAY_PIN, OUTPUT);
Serial.println("Warming up the MQ2 sensor");
delay(20000); // wait for the MQ2 to warm up
}
void loop() {
int gasState = digitalRead(DO_PIN);
if (gasState == HIGH) {
Serial.println("The gas is NOT present");
digitalWrite(RELAY_PIN, LOW); // turn off
} else {
Serial.println("The gas is present");
digitalWrite(RELAY_PIN, HIGH); // turn on
}
}
Detailed Instructions
To get started with ESP8266 on Arduino IDE, follow these steps:
- Check out the how to setup environment for ESP8266 on Arduino IDE tutorial if this is your first time using ESP8266.
- Wire the components as shown in the diagram.
- Connect the ESP8266 board to your computer using a USB cable.
- Open Arduino IDE on your computer.
- Choose the correct ESP8266 board, such as (e.g. NodeMCU 1.0 (ESP-12E Module)), and its respective COM port.
- Connect ESP8266 to PC via USB cable
- Open Arduino IDE, select the right board and port
- Copy the above code and open with Arduino IDE
- Click Upload button on Arduino IDE to upload code to ESP8266
- Move your hand in front of sensor
- See the change of relay's state
Code Explanation
Read the line-by-line explanation in comment lines of source code!