ESP32 S3 - Gas Sensor Relay

This tutorial shows you how to program the ESP32 S3 to activate a relay whenever an MQ2 gas sensor detects hazardous gases such as LPG, smoke, alcohol, propane, hydrogen, methane, or carbon monoxide, enabling you to build an automated safety response system. By connecting the relay to a fan, siren, or ventilation actuator, you can trigger an immediate protective action the moment dangerous gas concentrations are detected.

What you'll build:

  1. A circuit connecting an MQ2 gas sensor and relay module to the ESP32 S3
  2. A sketch that activates the relay when gas is detected above the threshold and deactivates it when the air clears
  3. A system capable of switching high-voltage loads such as cooling fans, alarm sirens, or ventilation motors via the relay
  4. A foundation for expanding into full gas-leak alert and home safety automation projects
ESP32 S3 MQ2 gas sensor and relay - switch on a fan or alarm siren when gas is detected

Overview of Relay and MQ2 Gas Sensor

The relay and MQ2 gas sensor are a powerful combination for building indoor safety systems with the ESP32 S3. The MQ2 gas sensor detects a wide range of combustible and toxic gases and outputs a digital signal when gas concentration exceeds a preset threshold, which the ESP32 S3 reads in real time. A relay then safely switches high-voltage or high-current loads — such as fans, sirens, or ventilation systems — that would otherwise damage the board's GPIO pins, enabling automatic protective responses whenever a gas leak is detected.

Key Specifications

We have dedicated tutorials covering each component in depth. Each tutorial contains detailed information and step-by-step instructions about hardware pinout, working principle, wiring connection to the ESP32 S3, and Arduino code. Learn more about them at the following links:

Wiring Diagram

Connect the MQ2 gas sensor and relay to your ESP32 S3 by following the diagram below. Double-check all connections before applying power, especially on the high-voltage side of the relay.

The wiring diagram between ESP32 S3 Gas Sensor Relay

This image is created using Fritzing. Click to enlarge image

Jumper wires are good for a quick test, but not for a final build. The ESP32 S3 fits a Screw Terminal Block for ESP32 S3, which turns every pin into a screw terminal. See the diagram below for the screw terminal version.

The wiring diagram between ESP32 S3 Gas Sensor Relay Screw Terminal

This image is created using Fritzing. Click to enlarge image

Another choice is a GPIO Breakout Board for ESP32 S3. Each GPIO has a signal pin with 3.3V and GND pins next to it, as shown below:

The wiring diagram between ESP32 S3 Gas Sensor Relay GPIO Breakout Board

This image is created using Fritzing. Click to enlarge image

Safety Notes

Always verify that the relay's COM and NO (or NC) terminals are securely fastened and that no bare wires are exposed before powering the circuit. Keep the low-voltage control wiring to the ESP32 S3 physically separated from any high-voltage load wiring to reduce the risk of accidental contact. Because this project is intended for detecting hazardous gases, ensure the gas sensor has completed its warm-up period (approximately one to two minutes) before relying on its output for safety-critical decisions.

Component Pin ESP32 S3 Pin
MQ2 Gas Sensor GND GND
MQ2 Gas Sensor VCC 5V
MQ2 Gas Sensor DO GPIO9
Relay DC- GND
Relay DC+ 5V
Relay IN GPIO2

ESP32 S3 Code

The following code reads the digital output of an MQ2 gas sensor connected to the ESP32 S3 and controls a relay accordingly — activating the relay when hazardous gas is detected above the sensor's threshold and deactivating it when the air returns to safe levels. All logic is handled with standard Arduino digitalRead() and digitalWrite() calls, so no external libraries are required.

/* * This ESP32 S3 code was developed by newbiely.com * * This ESP32 S3 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp32-s3/esp32-s3-gas-sensor-relay */ /* * This ESP32-S3 code is created by esp32io.com * * This ESP32-S3 code is released in the public domain * * For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-s3-gas-sensor-relay */ #define DO_PIN 9 // The ESP32-S3 pin GPIO9 connected to DO pin of the MQ2 sensor #define RELAY_PIN 2 // The ESP32-S3 pin GPIO2 connected to relay void setup() { // initialize serial communication Serial.begin(9600); // initialize the ESP32-S3's 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

  1. New to ESP32 S3? Complete our Getting Started with ESP32 S3 guide first.
  2. Wire the components following the wiring diagram shown above.
  3. Connect the ESP32 S3 board to your PC using a USB Type-C cable.
  4. Open Arduino IDE on your PC.
  5. Select the correct ESP32 S3 board and COM port from the Tools menu.
  6. Copy the above code and paste it into Arduino IDE.
  7. Click the Upload button to compile and upload the code to the ESP32 S3.
Arduino IDE Upload Code
  1. Allow the MQ2 gas sensor to warm up for one to two minutes after powering on.
  2. Bring a small amount of gas or smoke near the sensor's detection element.
  3. Observe the relay activating (you will hear a click) when gas concentration exceeds the threshold.
  4. Remove the gas source and observe the relay deactivating when the air clears.
  5. Pro Tip: Open the Serial Monitor at 115200 baud to print relay state messages in real time — this makes it much easier to debug unexpected behavior or calibrate the sensor's sensitivity threshold using the onboard potentiometer.

Serial Monitor Output

The following Serial Monitor output shows the ESP32 S3 responding to gas detection events and clear-air conditions in real time. Each line is timestamped so you can verify the timing between gas-detected and safe transitions.

∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32S3 Dev Module
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32S3 Dev Module' on 'COM15')
New Line
9600 baud
[2026-06-16 10:15:22] Gas detected - Relay: ON [2026-06-16 10:15:45] No gas detected - Relay: OFF [2026-06-16 10:16:03] Gas detected - Relay: ON [2026-06-16 10:16:31] No gas detected - Relay: OFF
Ln 11, Col 1
ESP32S3 Dev Module on COM15
2

Application and Project Ideas

Once you master gas-sensor-controlled relay switching with the ESP32 S3, you can extend this pattern into a wide range of practical safety and industrial automation projects.

  1. Kitchen gas leak alarm: Activate a relay-driven alarm siren and ventilation fan automatically when LPG or propane is detected in a kitchen, giving residents an immediate audible warning.
  2. Garage carbon monoxide detector: Trigger a relay to open a ventilation gate or activate an exhaust fan whenever CO concentrations rise in an enclosed garage, reducing poisoning risk.
  3. Industrial smoke detection: Use the relay to shut down machinery or trigger a fire suppression system when smoke is detected in a tutorial or server room.
  4. Smart home gas shutoff: Connect the relay to a motorized gas valve to automatically shut off the gas supply when a leak is detected, preventing potential explosions.
  5. Alcohol breath tester gate: Use the relay to control access to a vehicle ignition or secure area by blocking entry when alcohol vapor is detected above a safe threshold.
  6. Greenhouse fumigation control: Automate the relay to deactivate a fumigation system and activate ventilation fans once gas concentrations reach a safe lower limit after treatment.

Video Tutorial

Watch the step-by-step video walkthrough for this ESP32 S3 project below.

Challenge Yourself

Now that you can control a relay with an MQ2 gas sensor on the ESP32 S3, try these progressively challenging extensions to deepen your understanding and build more capable projects.

  1. Beginner: Modify the code so the relay stays ON for at least 60 seconds after gas is first detected, even if the sensor briefly reads safe, to prevent rapid relay toggling during fluctuating readings.
  2. Beginner: Add an LED indicator that lights up whenever the relay is active, giving a visual confirmation alongside the audible relay click.
  3. Intermediate: Implement a warm-up timer in the sketch that ignores all sensor readings for the first 90 seconds after power-on, preventing false triggers during sensor stabilization.
  4. Intermediate: Add an LCD or OLED display that shows the current gas level reading and relay state in real time, making the system self-contained without needing a PC.
  5. Advanced: Build a data-logging system that records gas detection events with timestamps to an SD card so you can review historical gas exposure incidents over days or weeks.
  6. Advanced: Extend the project with WiFi so the relay state can be monitored and overridden remotely via a web page served by the ESP32 S3, and send an email or push notification alert when gas is detected.

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!