Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
BETTESWORTHConstruction
Arduino

Build an ESP32 Security and Gas-Monitoring Prototype with PIR, MQ-5 and Blynk

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Direct answer: an ESP32, PIR motion sensor and MQ-5 gas sensor can form a useful IoT monitoring prototype. The PIR reports motion locally, the MQ-5 reports a relative response to combustible gases, and Blynk provides a remote dashboard and configurable notifications.

This is an educational project—not a certified burglar alarm, fire alarm or gas-leak detector. Use approved commercial detectors for life-safety protection. The original project, published on Hackster.io on December 9, 2023, used a DOIT ESP32 DEVKIT V1, PIR sensor, DFRobot Gravity analog MQ-5 sensor, LCD, gauge, value display, LED, buzzer and Blynk: original project reference.

As an Amazon Associate I earn from qualifying purchases.

What this system detects

The build combines two different sensing functions:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Function Sensor Output Reasonable interpretation
Motion PIR module, commonly HC-SR501-style Digital HIGH/LOW Movement across the sensor’s field of view
Combustible-gas indication MQ-5 module Analog voltage or ADC value Relative sensor response after warm-up and calibration

A PIR does not identify a person, recognize an intruder or reliably detect someone who remains still. It can also react to pets, heaters, sunlight, airflow and rapid temperature changes.

#1 Best Overall
ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA Compatible with Arduino IDE (3PCS)
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Support LWIP protocol, Freertos
  • SupportThree Modes: AP, STA, and AP+STA
  • Ultra-Low power consumption, Compatible with Arduino IDE
  • ESP32 is a safe, reliable, and scalable to a variety of applications

An MQ-5 is a heated metal-oxide sensor intended to respond to combustible gases such as LPG and related gases. Its raw ESP32 ADC value is not automatically a parts-per-million measurement. Sensor age, heater temperature, supply voltage, humidity, temperature, airflow and gas composition all affect the result.

How the prototype works

  1. The PIR and MQ-5 produce sensor signals.
  2. The ESP32 reads the digital PIR state and samples the MQ-5 through an ADC input.
  3. The ESP32 switches a local LED and buzzer when configured conditions are met.
  4. Wi-Fi connects the board to Blynk.Cloud.
  5. Blynk datastreams feed dashboard widgets, while Blynk events can send push, email or SMS notifications.

Local outputs should remain functional when Wi-Fi or Blynk.Cloud is unavailable. Cloud monitoring is an additional convenience, not the only alarm path.

Parts required

  • DOIT ESP32 DEVKIT V1, or another clearly documented ESP32 development board.
  • PIR motion sensor module.
  • MQ-5 gas-sensor breakout. The original build identifies a DFRobot Gravity analog MQ-5 sensor.
  • Breadboard, jumper wires and USB data cable.
  • LED and a current-limiting resistor.
  • Buzzer. Use a transistor or MOSFET driver if its current exceeds what an ESP32 GPIO can safely supply.
  • Stable USB power supply.
  • Voltage-divider or level-shifting components if the MQ-5 analog output can exceed the ESP32 ADC input range.

Product documentation matters. MQ-5 modules vary in supply requirements, connector pinout, heater current and analog-output voltage. Do not assume that two boards labelled “MQ-5” are electrically identical.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wire the sensors safely

The following is an example for a typical ESP32 DevKit. Confirm every connection against the exact board and sensor documentation before powering it.

Rank #2
ELEGOO 3PCS ESP-32 Dev Boards, ESP-WROOM-32, USB-C, WiFi Bluetooth 4.2 | Low-power IoT Applications, Smart Devices, Automation, Wireless Communication, GPIO Headers, Simplifying Development
  • Dual-Core Performance Up to 240 MHz: Run sensor processing, wireless communication, automation logic and connected-device tasks on a 32-bit dual-core ESP32 platform designed for responsive embedded and IoT projects
  • Built-in Wi-Fi and Bluetooth 4.2: Connect to 2.4 GHz Wi-Fi networks or use Bluetooth Classic and BLE for wireless sensors, smart devices, remote controls, home automation and other connected projects
  • Flexible Power-Saving Modes: ESP32 power-management features support dynamic clock scaling and low-power operating modes, helping developers reduce energy use in compatible sensing, monitoring and connected-device applications, suitable for battery-powered Internet of Things (IoT) devices.
  • USB-C Programming with CP2102: Connect through USB-C for power, sketch uploads and serial monitoring, while GPIO, UART, SPI and I2C interfaces support sensors, displays, motor drivers and other modules (USB-C cable not included)
  • Over-the-Air Update Support: Configure OTA functionality through a compatible ESP-32 software framework to update deployed firmware over Wi-Fi without reconnecting the board by USB for every revision
Component Example ESP32 connection Important note
PIR VCC Module-approved 5 V or 3.3 V rail Check the module’s voltage limits.
PIR GND GND All grounds must be common.
PIR OUT GPIO 27 Use a suitable digital input.
MQ-5 analog output GPIO 34 through suitable protection GPIO 34 is an ADC1 input on common ESP32 boards; verify output voltage first.
MQ-5 VCC Supply recommended by the module manufacturer The heater can draw substantial current.
MQ-5 GND GND Use a common ground with the ESP32.
LED GPIO 25 through a resistor Never connect an LED directly without current limiting.
Buzzer GPIO 26 through a driver when required Do not exceed GPIO current limits.

Protect the ESP32 ADC input

Many MQ modules are designed around 5 V and can produce an analog output above the ESP32’s safe input range. Connecting that output directly can damage the board. Measure or verify the module’s maximum output before wiring it.

For a 5 V maximum signal, an example divider using a 10 kΩ resistor from the MQ output to the ESP32 ADC pin and a 20 kΩ resistor from the ADC pin to ground reduces the signal to approximately 3.33 V. Treat this only as an example: choose values and an ADC attenuation setting appropriate to the actual module and board, and verify the result with a meter.

Power problems are common. If the ESP32 resets when the MQ-5 heater starts or Wi-Fi transmits, use a suitable regulated supply, shorter wiring, adequate decoupling and, where necessary, a separate regulated supply for the gas-sensor module with a shared ground.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test the PIR before adding Blynk

Upload a minimal sketch first. This separates wiring and sensor problems from cloud configuration problems.

Rank #3
Sale
ELEGOO ESP-32 Super Starter Kit with Tutorial Compatible with Arduino IDE | Development Board, USB-C Dual Core Microcontroller Support AP/STA/AP+STA, CP2102 Chip, WiFi, Bluetooth, 200+ parts for IoT
  • Powerful ESP-32 Board: Unlock the world of Internet of Things (IoT) and advanced electronics with the heart of this kit: the ESP-32 board. It features a powerful dual-core processor, integrated Wi-Fi and Bluetooth 4.2, making it perfect for building connected, smart devices that communicate with your phone or the cloud. It's fully compatible with the Arduino IDE for easy programming.
  • Super Starter Kit: This kit contains over 35 different modules and electronic components, including sensors, displays, motors, and input devices. From LEDs and buttons to an OLED screen, servo motor, and keypad, you have everything needed to explore a vast range of projects in one box.
  • Step by Step Online Tutorial: Jump right in with our detailed, beginner-friendly tutorial. Access 30+ projects with complete code, clear circuit diagrams, and step-by-step instructions. Learn the fundamentals of electronics, coding, and how to utilize the ESP-32's unique capabilities without any prior experience.
  • Hands-on Learning for All Skill Levels: Perfect for students, makers, engineers, and hobbyists. Start with basic circuits and coding, then progress to intermediate and advanced IoT applications. Build practical projects like weather stations, smart home controllers, remote-controlled devices, and interactive gadgets. The skills you learn are the foundation for real-world innovation.
  • Quality & Great Support: Elegoo is committed to quality. We provide a clear, detailed tutorial guide, refined code, and a well-organized component kit. All modules are carefully selected for reliability and ease of use. Our dedicated technical support team and active online community are ready to help you succeed in your learning journey.
const int PIR_PIN = 27;

void setup() {
  Serial.begin(115200);
  pinMode(PIR_PIN, INPUT);
  Serial.println("Waiting for PIR stabilization");
  delay(30000); // Allow the module to settle; follow its documentation
}

void loop() {
  Serial.println(digitalRead(PIR_PIN) ? "Motion: 1" : "Motion: 0");
  delay(250);
}

Open the Serial Monitor at 115200 baud. After stabilization, walk across—not directly toward—the sensor’s field of view. Adjust the HC-SR501-style module’s sensitivity and time-delay controls if fitted. Test for false triggers caused by sunlight, heating vents, fans, pets and moving curtains.

Test the MQ-5 separately

const int MQ5_PIN = 34;

void setup() {
  Serial.begin(115200);
  analogReadResolution(12); // Confirm support in the installed ESP32 core
  Serial.println("MQ-5 warm-up in progress");
}

void loop() {
  int gasRaw = analogRead(MQ5_PIN);
  Serial.print("Gas raw: ");
  Serial.println(gasRaw);
  delay(1000);
}

Allow the sensor to warm up according to its documentation. Record several minutes of readings in clean air and calculate a practical baseline. The baseline is specific to the sensor, breakout, supply, environment and firmware. Do not assume a universal threshold such as 600, and do not label the ADC value “ppm” without a documented gas-specific calibration process.

Never test the sensor with an open flame, a pressurized leak or by deliberately accumulating gas indoors. For a learning test, use only a controlled, safe procedure appropriate to the sensor documentation. For actual protection, install an approved gas detector.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create the current Blynk IoT configuration

Modern Blynk IoT uses templates, datastreams, devices, dashboards and events. It is not safe to assume that the older “create a project and receive an auth token by email” workflow applies to every current account.

Rank #4
ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA Compatible with Arduino IDE (1 PCS)
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Support LWIP protocol, Freertos;ESP32 is a safe, reliable, and scalable to a variety of applications
  • SupportThree Modes: AP, STA, and AP+STA
  • Ultra-Low power consumption, Compatible with Arduino IDE
  • 1PCS 30Pin ESP32 Development Board 2.4GHz WiFi Dual Cores Microcontroller Integrated with Antenna RF Low Noise Amplifiers Filters
  1. Sign in to Blynk and open Blynk.Console.
  2. Go to Developer Zone → Templates and create a template for the ESP32 with Wi-Fi connectivity.
  3. Open the template’s Datastreams section.
  4. Add the datastreams listed below, choosing ranges that match your firmware and ADC configuration.
  5. Create a device from the template.
  6. Add mobile or web dashboard widgets and assign each widget to the matching datastream.
  7. Open the template’s Events & Notifications area and create motion and gas-alert events.
  8. Copy the generated template and device credentials into the firmware without publishing them.
Datastream Type Purpose
Motion Integer or Boolean PIR state, 0 or 1
GasRaw Integer Raw or filtered MQ-5 ADC value
AlarmArmed Boolean Enable or disable alert logic
GasAlert Boolean Current gas-alert state
SystemStatus String Connection and alarm status

The original Hackster project used virtual datastreams V3, V4 and V7 for its gauge, value display and LCD. Those assignments belong to that project; a new template can use clearer names and different virtual pins. Blynk datastreams carry values between the device and Blynk.Cloud, and widgets display those values. See the template documentation, datastream documentation and setup guide.

Configure notification events correctly

Create at least two events:

  • motion_detected for a new PIR motion state.
  • gas_threshold for a confirmed rise above the calibrated project threshold.

Firmware can report an event with:

Blynk.logEvent("motion_detected", "Motion detected");

Do not call this continuously while the PIR remains HIGH or while the gas value remains above its threshold. Use rising-edge detection, a cooldown and, ideally, hysteresis. For example, trigger above the alert threshold only after several consecutive samples, then clear only after the reading falls below a lower recovery threshold.

Send telemetry on a timer rather than on every pass through loop(). Blynk specifically warns that uncontrolled repeated writes can spam the cloud. Event quotas and notification behavior can depend on the current plan and platform limits; check the current event documentation.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Combined firmware structure

The code below demonstrates the architecture. Replace the placeholders with credentials generated for your Blynk device and calibrate the gas settings for the chosen hardware.

Best Value
HiLetgo ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA for Arduino IDE
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Ultra-Low power consumption, works perfectly with the Arduino IDE
  • Support LWIP protocol, Freertos
  • SupportThree Modes: AP, STA, and AP+STA
  • ESP32 is a safe, reliable, and scalable to a variety of applications
#define BLYNK_TEMPLATE_ID "YOUR_TEMPLATE_ID"
#define BLYNK_TEMPLATE_NAME "ESP32 Security Monitor"
#define BLYNK_AUTH_TOKEN "YOUR_DEVICE_TOKEN"

#include <WiFi.h>
#include <BlynkSimpleEsp32.h>

char ssid[] = "YOUR_WIFI_NAME";
char pass[] = "YOUR_WIFI_PASSWORD";

const int PIR_PIN = 27;
const int MQ5_PIN = 34;
const int LED_PIN = 25;
const int BUZZER_PIN = 26;

const int GAS_ALERT_THRESHOLD = 600; // Example only: calibrate this value
const int GAS_CLEAR_THRESHOLD = 560; // Hysteresis example
const unsigned long GAS_SAMPLE_MS = 1000;
const unsigned long TELEMETRY_MS = 5000;
const unsigned long NOTIFY_COOLDOWN_MS = 60000;

BlynkTimer timer;
int gasRaw = 0;
bool motion = false;
bool gasAlert = false;
bool previousMotion = false;
unsigned long lastGasSample = 0;
unsigned long lastMotionEvent = 0;
unsigned long lastGasEvent = 0;

void sampleSensors() {
  gasRaw = analogRead(MQ5_PIN);
  bool newMotion = digitalRead(PIR_PIN) == HIGH;

  if (newMotion != motion) {
    motion = newMotion;
    digitalWrite(LED_PIN, motion || gasAlert);

    if (motion && !previousMotion &&
        millis() - lastMotionEvent > NOTIFY_COOLDOWN_MS) {
      Blynk.logEvent("motion_detected", "PIR motion detected");
      lastMotionEvent = millis();
    }
    previousMotion = motion;
  }

  if (!gasAlert && gasRaw >= GAS_ALERT_THRESHOLD) {
    gasAlert = true;
    Blynk.logEvent("gas_threshold", String("MQ-5 raw value: ") + gasRaw);
    lastGasEvent = millis();
  } else if (gasAlert && gasRaw <= GAS_CLEAR_THRESHOLD) {
    gasAlert = false;
  }

  digitalWrite(LED_PIN, motion || gasAlert);
  digitalWrite(BUZZER_PIN, gasAlert ? HIGH : LOW);

  Serial.printf("Motion: %d | Gas raw: %d | Alarm: %sn",
                motion, gasRaw, (motion || gasAlert) ? "ON" : "OFF");
}

void sendTelemetry() {
  Blynk.virtualWrite(V0, motion ? 1 : 0);
  Blynk.virtualWrite(V1, gasRaw);
  Blynk.virtualWrite(V2, gasAlert ? 1 : 0);
}

void setup() {
  Serial.begin(115200);
  pinMode(PIR_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);
  digitalWrite(BUZZER_PIN, LOW);

  Serial.println("System starting");
  Serial.println("Waiting for PIR stabilization");
  delay(30000);
  Serial.println("MQ-5 warm-up in progress");

  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
  timer.setInterval(GAS_SAMPLE_MS, sampleSensors);
  timer.setInterval(TELEMETRY_MS, sendTelemetry);
}

void loop() {
  Blynk.run();
  timer.run();
}

Assign V0, V1 and V2 to the corresponding Blynk datastreams, or change the firmware to match your chosen virtual pins. A production-quality implementation should also confirm that the gas sensor has warmed up before enabling alerts, use a moving average or median filter, and define explicit behavior for sensor disconnection and reconnection.

Expected serial output will resemble:

System starting
Waiting for PIR stabilization
MQ-5 warm-up in progress
Wi-Fi connected
Blynk connected
Motion: 0 | Gas raw: 412 | Alarm: OFF
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Test the completed system

  1. Clean air, no motion: confirm the PIR is LOW, the gas value is stable enough to establish a baseline, and the alarm is OFF.
  2. Motion: cross the PIR field of view and confirm the local LED, dashboard state and one notification.
  3. Repeated motion: verify that the cooldown prevents a notification storm.
  4. Gas threshold: use only a safe, controlled test method; verify the local alarm and configured Blynk event.
  5. Recovery: confirm the gas-alert state clears only below the recovery threshold.
  6. Wi-Fi disconnected: verify that local outputs still operate.
  7. Blynk unavailable: confirm the ESP32 does not lose its local alarm function.
  8. Reboot: confirm PIR stabilization and MQ-5 warm-up are handled before normal alerting.
  9. Sensor disconnected: determine whether the firmware can recognize an implausible or missing reading rather than silently reporting normal conditions.

Calibration and reliability improvements

  • Record a clean-air baseline after warm-up instead of copying a threshold from another project.
  • Use several consecutive samples before declaring a gas alert.
  • Apply moving-average or median filtering to reduce noise.
  • Use hysteresis so the alarm does not chatter around one threshold.
  • Mount the PIR where its lens covers the intended zone and is away from direct heat and airflow.
  • Place the MQ-5 according to the gas and installation requirements; gas distribution varies with room geometry and airflow.
  • Use a regulated supply with enough current for the heater and Wi-Fi bursts.
  • Add a watchdog, reconnection handling and a visible local fault state.
  • Consider battery backup, local data logging, a door contact or camera for additional context.

Troubleshooting

Symptom Likely cause What to check
Device does not appear online Incorrect credentials, Wi-Fi failure or weak signal Serial output, SSID/password, router access, template ID, device token and Blynk device status.
Dashboard values are blank Wrong datastream type or virtual pin Match firmware calls such as Blynk.virtualWrite(V1, gasRaw) to the template configuration.
Notifications do not arrive Event or recipient configuration problem Check Events & Notifications, notification permissions, event timeline and current limits.
Repeated alerts Event called every loop Add edge detection, consecutive-sample confirmation and cooldown logic.
ESP32 resets Insufficient supply, heater load or wiring fault Check voltage under load, use an appropriate supply and inspect grounds and shorts.
Gas readings drift Warm-up, environment or sensor variation Allow warm-up, establish a new baseline and avoid treating raw readings as ppm.
PIR remains HIGH Startup stabilization, wiring, interference or module timing Check OUT voltage and wiring, wait for stabilization and adjust module controls.
Cloud monitoring stops during an outage Wi-Fi or Blynk dependency Retain local LED/buzzer logic and define an offline status policy.

Prototype versus real security equipment

This project can teach GPIO, ADC sampling, Wi-Fi connectivity, dashboards and event-driven alerts. It can also provide remote telemetry for a room or demonstration board. It cannot guarantee intrusion detection, identify an intruder, measure gas concentration accurately without validation, or replace certified safety equipment.

For an occupied building, use approved commercial gas detectors and alarms as the primary protection. Keep the ESP32 build as a supplementary educational or monitoring system, and never publish Wi-Fi passwords, Blynk tokens or other credentials in source code or screenshots.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Alternatives

An ESP8266 can run similar Blynk projects but offers fewer convenient ADC and GPIO options. A Raspberry Pi is better suited to cameras, databases and local dashboards, but consumes more power and requires operating-system maintenance. An Arduino Uno needs a separate connectivity solution. MQTT with Home Assistant or another IoT platform can provide more local control, but changes the software architecture. Certified commercial detectors offer better validation, enclosure, backup power and alarm design, at the cost of flexibility and educational value.

For the original project and its component arrangement, see Hackster.io. For current Blynk concepts, consult the device-template documentation, events tutorial and sensor-data guide.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.