Low-Cost IoT Smart-Home Node for Motion and Gas Leakage Monitoring with Arduino and ESP8266
Abstract:
Cooking-related fires and combustible-gas leaks remain recurring domestic hazards, while lights and ventilation fans are often left running in empty rooms. This paper presents the design and experimental validation of a low-cost retrofit IoT node that integrates occupancy-aware actuation with early smoke and gas monitoring under a safety-first policy. An Arduino UNO executes time-critical sensing and relay control, and an ESP8266 provides Wi-Fi connectivity and a lightweight smartphone interface. Occupancy is inferred using a passive infrared (PIR) sensor to gate a lamp and fan, while an MQ-2 module monitors smoke and combustible gases. The control logic is implemented as an event-driven state machine that prioritises safety events, enforces minimum on and off timing to suppress relay chattering, and stabilises the gas channel using clean-air baseline normalisation (R/R0) with hysteresis. Bench verification confirmed I/O mapping and electrical isolation via an opto-isolated relay stage, and repeated switching did not reveal relay instability under the prototype loads. Scenario trials in a two-zone mock-up demonstrated reliable manual overrides, motion-triggered actuation without oscillation, and consistent alert generation during staged smoke exposures. The results support feasibility for incremental residential retrofits and identify deployment priorities, including sensor drift management, power integrity, and installation practice.1. Introduction
Smart home systems increasingly combine sensing, actuation, and networked interaction to improve domestic safety, comfort, and energy efficiency. Adoption, however, remains uneven. Cost, vendor lock-in, and configuration complexity still limit practical uptake, particularly for households that could benefit most from assistive automation, including older adults and individuals with functional limitations. Recent gerontechnology and ageing-in-place studies highlight both the value of smart-home support for independence and caregiver relief, and the persistent barriers of affordability, interoperability, and user-facing complexity [1], [2], [3]. These realities motivate low-cost, retrofit-friendly designs that deliver measurable benefits without adding operational burden.
Domestic risk patterns further sharpen the engineering case for integrated home monitoring and control. Cooking is consistently reported as the leading cause of home structure fires and fire-related injuries, with unattended stovetop activity a prominent driver across jurisdictions [4]. Gas leaks involving liquefied petroleum gas (LPG) and related fuels can escalate rapidly into explosions or severe fires when detection is delayed [5]. Alongside safety, everyday inefficiencies such as lighting and ventilation left active in empty rooms continue to waste energy and raise household costs. A practical smart-home node for ordinary dwellings should therefore meet three requirements: it must sense events that map directly to safety and use, execute local actions with predictable latency, and deliver timely notifications over common household connectivity such as Wi-Fi and mobile data.
Within this context, occupancy-aware control is a well-supported baseline for reducing avoidable electricity use. Evidence from field studies and technical reports on lighting control commonly reports double-digit savings when loads are switched or dimmed in response to presence, with typical reductions in lighting energy on the order of 20–40 percent in suitable applications [6]. Passive infrared (PIR) sensing remains the most common occupancy modality in cost-constrained deployments because it is inexpensive, low power, and privacy-preserving, and recent experiments confirm that PIR-based systems can produce reliable occupancy cues when placement and control logic are treated as first-order design choices [7]. This makes PIR sensing technically attractive, but it also places emphasis on timing policy and nuisance-trigger mitigation, not only on hardware selection.
A parallel stream of work has explored low-cost gas and smoke monitoring using resistive sensors such as MQ-2, often paired with Arduino-class controllers and Wi-Fi modules. Many prototypes demonstrate that elevated LPG, methane, or smoke levels can be detected and relayed to users, sometimes via rapid-development platforms such as ESP8266 and Blynk for remote alerts [8], [9]. Yet a recurring limitation is methodological rather than functional: calibration and threshold selection are frequently treated as ad hoc, cross-sensitivity and environmental drift are rarely addressed explicitly, and cloud connectivity is often assumed rather than engineered as a non-critical layer. Broader smart-home surveys similarly note that, despite technical feasibility, reproducible designs suitable for deployment and maintenance in ordinary housing stock remain underdeveloped [10]. In other words, there is still a gap between “it works once” demonstrations and experimentally grounded, locally reliable nodes that integrate efficiency and safety under a coherent control policy.
The present work targets that gap with a low-bill-of-materials smart-home node that integrates three high-value capabilities within a single, smartphone-accessible interface: remote appliance control, occupancy-aware actuation of lighting and ventilation, and early detection of smoke and combustible gases. The design intentionally separates deterministic embedded control from the user-interface layer. An Arduino-class microcontroller executes the safety and automation policy locally, interfacing directly with the PIR module, the MQ-2 analog front end, and relay-isolated loads, while the ESP8266 provides a lightweight browser and mobile dashboard for manual override, mode selection, and alert delivery without binding the system to a proprietary hub or vendor ecosystem [11]. The problem addressed can be stated as follows: how to design an integrated, affordable, and responsive smart home node that reduces interaction friction for everyday appliance control, lowers avoidable energy use through occupancy-aware policies, and shortens time to awareness for hazardous conditions by pushing alerts directly to the user’s handset.
Our contribution is threefold.
• We present a unified, retrofit-oriented architecture that couples occupancy-based automation and hazard monitoring under a single phone-accessible interface, while keeping safety-critical decisions local and cloud-independent.
• We formalise the sensing-and-actuation strategy as an event-driven control policy, and make the parameter choices explicit, especially PIR timing and MQ-2 calibration and thresholds, because these details govern stability in real homes.
• We report validation under representative scenarios and repeated trials, and interpret responsiveness and operational stability in engineering terms, including latency behaviour, nuisance-trigger tendencies, and implications for maintainable extension in cost-sensitive deployments.
The remainder of the paper, section 2, reviews related work on smart home automation and IoT safety systems; section 3 describes the hardware, firmware, and networking methodology; section 4 presents experimental results and discusses implications for cost-effective, assistive deployments; and section 5 concludes.
2. Literature Review
Smart home research has progressed from isolated remote switching toward integrated cyber-physical systems that couple sensing, embedded control, and internet connectivity. As expectations have matured, the emphasis has shifted from “connectivity works” to whether systems remain affordable, maintainable, and reliable in ordinary dwellings, where installation constraints, intermittent connectivity, and user tolerance for nuisance behaviour all shape real adoption. Recent surveys note that deployments increasingly mix device classes, communication stacks, and cloud services, yet many commercial ecosystems remain vertically siloed, vendor locked, or costly to retrofit into existing buildings [12], [13]. Against this backdrop, the following review focuses on four connected strands that frame the present work: communication and control architectures, occupancy-aware automation for energy efficiency, gas and smoke monitoring for domestic safety, and microcontroller-centric implementations that enable low-cost retrofits.
Most IoT smart home platforms rely on a blend of local networking and wide-area connectivity to coordinate devices and expose user interfaces. Architectural surveys consistently position Wi-Fi and Ethernet as practical high-bandwidth in-home links, while Global System for Mobile Communications (GSM) or Long Term Evolution (LTE) is used for off-site alerting, particularly in settings where broadband is unreliable or absent [14]. Wi-Fi-centric designs remain attractive for low to moderate device counts because they reuse existing routers, support browser and app-based interfaces, and integrate naturally with cloud dashboards and mobile back ends [15]. However, the engineering challenge is not only reachability, it is also predictability. If time-critical automation is delegated to the cloud, latency variability and connectivity loss can turn safety functions into best-effort services.
This has motivated local-first control patterns, where embedded controllers perform time-critical decisions on-device and treat the cloud as an optional extension rather than a dependency. Experiments using webserver-based ESP8266 or node microcontroller unit (NodeMCU) gateways indicate that simple Representational State Transfer (REST) or Message Queuing Telemetry Transport (MQTT) endpoints can expose device states and accept commands, while deterministic actuation remains in the microcontroller domain [16]. This approach, local execution with networked visibility, is a recurring architectural response to interoperability and latency concerns, and it directly informs the design decisions in this paper.
Reducing avoidable household energy use remains a primary driver of domestic automation, and the evidence base has become increasingly quantitative. Systematic reviews of lighting controls repeatedly report that occupancy-based strategies yield double-digit energy savings, particularly when manual switching is inconsistent or when spaces exhibit high variability in use. A meta-analysis of lighting control studies reports typical savings of 20 to 60 percent, with space type and occupancy diversity acting as dominant moderators of benefit [17]. Field guidance for public and multifamily buildings similarly reports wide ranges, from 10 to 90 percent, and identifies off-delay tuning as a key parameter because it mediates the trade-off between savings and user acceptance [18]. Within home settings, integrating occupancy sensing with efficient lighting and ventilation can improve savings while preserving safety, provided that automation logic is conservative enough to avoid unsafe darkness or poor indoor air exchange [19], [20].
PIR sensors remain the default occupancy modality in cost-constrained deployments because they are inexpensive, low power, and do not capture identifiable imagery [21]. Yet PIR modules exhibit operational behaviours that must be treated as part of the design space, including warm-up time, output hold times after motion ceases, and sensitivity to line-of-sight geometry and thermal backgrounds. Recent experiments show that robustness improves when simple timing policies are implemented explicitly, such as minimum on and off intervals, or when PIR inputs are fused with secondary modalities, which reduces false switching and stabilises user experience [22]. These findings justify PIR as a practical choice, but they also imply that the firmware policy, not the sensor alone, determines whether occupancy control is perceived as helpful or intrusive.
The case for early hazard detection in residential environments is supported by incident statistics that are stable across reporting agencies and time. National Fire Protection Association and federal reports consistently identify cooking as the leading cause of home structure fires, accounting for roughly 40 to 50 percent of reported residential incidents, with substantial contributions to injuries and property loss [23]. In practical terms, this means that detection and alerting are most valuable in kitchens and adjacent spaces, where distraction, temporary absence from the room, or reduced mobility can delay awareness. From an engineering perspective, the objective is not only to detect hazardous conditions, but also to do so with thresholds and timing policies that avoid false alarms that could lead users to ignore or disable safety functions.
MQ-series semiconductor sensors, including MQ-2, are commonly used in low-cost detectors for LPG, methane, hydrogen, and smoke [24]. The sensor’s heated tin dioxide element produces a resistance change correlated with gas concentration, enabling analog readout through microcontroller Analog-to-Digital Converters (ADCs). Recent IoT prototypes combine MQ-2 modules with ESP8266-class Wi-Fi nodes to provide leak detection and smartphone alerts, often using rapid interface platforms such as Blynk for ease of deployment [25]. However, the literature also highlights limitations that matter for reproducibility and reliability: MQ-2 sensors require burn-in and baseline stabilisation, they exhibit cross-sensitivity to multiple gases, and their output can drift with temperature, humidity, and ageing. As a result, conservative thresholding and transparent calibration assumptions are necessary to reduce false positives and to maintain safety credibility over time. These concerns motivate a safety-first control loop where detection logic is local, thresholds are justified, and alerting is treated as an engineered function rather than a demonstration feature.
Arduino-class microcontrollers remain a common foundation for academic and prototype smart home systems because they offer sufficient I/O, a broad ecosystem of shields and libraries, and a toolchain that supports rapid iteration. Many designs combine Arduino UNO boards with relays, environmental probes, PIR modules, and MQ-series sensors to produce integrated monitoring and control nodes that can be replicated at low cost [26]. The rise of ESP8266-based NodeMCU boards further reduced the bill of materials for IP-connected nodes by integrating a Wi-Fi radio with modest processing resources, enabling lightweight web servers or MQTT clients to run directly on the device [27], [28]. This shift materially changed the design trade space, making it feasible to expose browser-accessible control without requiring an external gateway.
At the same time, recent energy management research positions microcontroller platforms as local coordinators that bridge cloud-side optimisation and field devices, particularly for distributed loads where centralised control can become brittle under network variability [29]. Even so, a recurring pattern in published prototypes is that convenience functions and safety functions are frequently treated in isolation. Remote switching is often validated as a user-interface capability, while hazard detection is treated as a threshold trigger, with limited attention to nuisance behaviour, calibration drift, or maintenance requirements. This separation can be adequate for demonstrations, but it leaves a gap for designs that treat safety, usability, and energy efficiency as coupled engineering objectives.
Taken together, the literature supports three actionable conclusions. First, Wi-Fi-based IoT architectures, optionally complemented by cellular alerting, provide a pragmatic backbone for residential environments because they combine in-home responsiveness with out-of-home reach when needed [30], [31]. Second, PIR-based occupancy control can deliver substantial, empirically documented energy savings, but only when timing policies are designed to balance savings against nuisance switching and safety constraints [17], [18]. Third, MQ-2 sensors enable low-cost early warning for combustible gas and smoke, provided that sensor response is stabilised and thresholds are tuned with cross-sensitivity and drift in mind [24], [25]. Against this evidence, microcontroller-centric implementations pairing Arduino and ESP8266 or NodeMCU have matured into a de facto reference architecture for low-cost smart home nodes [32].
Despite this progress, there remains limited work that integrates occupancy-aware control, gas and smoke monitoring, and browser-accessible actuation within a single node that follows a local-first safety policy, and that remains simple enough to retrofit without proprietary hubs. The present work addresses this gap by combining PIR-based automation, MQ-2 hazard monitoring, relay-isolated actuation, and an ESP8266 web front end into one integrated prototype, while explicitly documenting the calibration and timing choices that most strongly influence stability and user experience in practice.
3. Methodology
The methodology translates the goals of affordable retrofitting, assistive automation, and early hazard detection into an embedded, networked control node. The architecture follows a pattern that is well established in low-cost smart homes: a microcontroller executes deterministic input and output locally, while a Wi-Fi system-on-chip exposes an Internet-protocol interface for human–machine interaction. Prior studies validate this split between an Arduino-class controller and an ESP8266 or NodeMCU front end for domestic automation and security tasks, and report that it offers a practical balance between cost, flexibility, and reliability [33].
In the proposed node, an Arduino UNO acts as the timing-critical I/O hub. A 4-channel opto-isolated relay board switches mains-powered loads, namely a lamp and a small fan, while preserving galvanic isolation between low-voltage logic and the 230 V side. An ESP8266 module, configured as a lightweight web and Blynk client, provides Wi-Fi connectivity and a smartphone view of system status and controls. Related ESP8266-based designs show that responsive home control can be achieved with modest device resources and straightforward integration into existing WLANs [34].
Two sensing streams drive the control policy. A PIR module provides occupancy cues to gate the lamp and fan, so they are energised only when a person is present. PIR remains the dominant choice for low-cost occupancy control, and field studies report significant lighting-energy savings when it is paired with simple timing policies [35]. An MQ-2 gas and smoke sensor monitors the environment for LPG, methane, hydrogen, and smoke, and MQ-2 based detectors can provide reliable hazard detection when readings are appropriately normalised and calibrated [36]. Figure 1 summarises the overall architecture and the separation of roles between the Arduino (local control) and the ESP8266 (user interface and network visibility). The ESP8266 exchanges compact serial commands with the Arduino to implement manual overrides and to propagate alarm and status updates to the handset

The system is governed by an event-driven state machine that prioritises safety over convenience, as summarised in Figure 2. After power-up, the Arduino initialises general-purpose input/output (GPIO) lines, checks that sensor signals fall within expected ranges, and requests Wi-Fi association from the ESP8266. Normal operation then proceeds as a cycle of sensing, decision, and actuation: occupancy events update timers that control the lamp and fan, and gas or smoke events update an alarm state that can pre-empt other behaviours. Manual commands from the smartphone are accepted as overrides, but only within safety constraints, for example an alarm state can force ventilation regardless of a user request to switch the fan off.

For the occupancy channel, the control law applies a hold-time and off-delay policy to prevent relay chattering and frequent toggling near the boundary of the sensor field of view. The behaviour can be written as:
where, $u(t) \in\{0,1\}$ is the actuator state for the lamp or fan, $o(t)$ is the debounced PIR occupancy flag, and $T_{\text {off}}(t)$ is a countdown timer enforcing a minimum off-delay. A symmetric on-timer $T_{o n}(t)$ can be used to guarantee a minimum run time before switch-off. This formulation aligns with recommendations for occupancy-sensor lighting control that emphasise explicit time delays and minimum-run constraints to reduce nuisance switching and switching wear [37].
For the safety channel, the MQ-2 output is converted to sensor resistance $R_s$ using the voltage-divider relation:
where, $R_L$ is the module load resistor, $V_{C C}$ is the supply, and $V_{out}$ is the analogue output. After a $24-48$ hours burn-in period, a clean-air baseline $R_0$ is measured and subsequent readings are expressed as:
Alarm decisions are then based on a hysteretic comparator:
where, $a(t) \in\{0,1\}$ is the alarm state and $\tau_{\text {high}}>\tau_{\text {low}}$ defines a deadband that suppresses oscillations around the threshold. In firmware, this logic is implemented either through an LM358 comparator stage or in software after sampling the analogue channel. Whenever $a(t)=1$, the controller asserts audible and visual alarms, may force the ventilation fan to ON , and queues a high-priority notification to the handset. These safety actions are executed locally and remain active even if Wi-Fi connectivity is lost, because the full state machine runs on the Arduino.
The physical implementation follows standard practices reported for low-cost IoT home automation platforms built around Arduino and ESP8266 devices [38]. The Arduino UNO drives the relay board from digital pins D8 and D9 for lamp and fan switching, reads the PIR output on D7, and samples the MQ-2 through analogue input A0 or a digital comparator line. The ESP8266 is linked through a UART bridge carrying compact one-byte commands for actuator control and status reflection. For signal integrity, the ESP8266 is powered from a dedicated 3.3 V regulator with adequate current margin, its transmit pin connects directly to the UNO, and the UNO transmit line is level shifted to 3.3 V using a resistor divider. Table 1 lists the I/O mapping and configuration, and Table 2 documents the serial command protocol. Thresholds and timing constants used in firmware are summarised in Table 3.
Controller | Pin (Label) | Logical Role | Connected Module | Direction/Type | Notes |
|---|---|---|---|---|---|
Arduino UNO | A0 | Gas/smoke input | MQ-2 (analogue) or LM358 comparator | In/analogue | Normalise to $R/R_0$; or set digital threshold if using comparator. |
Arduino UNO | D7 | Occupancy input | PIR digital out | In/digital | Debounce in firmware; respect the passive infrared (PIR) hold time. |
Arduino UNO | D8 | Relay CH1 (light) | 4-ch relay board | Out/digital | Many boards are active-low; confirm. |
Arduino UNO | D9 | Relay CH2 (fan) | 4-ch relay board | Out/digital | Enforce minimum-on/off timers. |
Arduino UNO | D10 $\rightarrow$ ESP RX0 | UART TX to node microcontroller unit (NodeMCU) | ESP8266 | Out/UART | Level-shift to 3.3 V (divider/buffer). |
Arduino UNO | D11 $\leftarrow$ ESP TX0 | UART RX from NodeMCU | ESP8266 | In/UART | 3.3 V recognised as high by UNO. |
Power rails | 5 V (UNO/relays), 3.3 V (ESP) | - | Regulated supplies | - | Common ground; flyback diodes; decoupling near loads. |
Byte Sent | Action on UNO | Actuator | Note |
|---|---|---|---|
‘1’ | DigitalWrite(fan, LOW) | Fan off | Active-low relay logic in code. |
‘2’ | DigitalWrite(fan, HIGH) | Fan on | - |
‘3’ | DigitalWrite(light, LOW) | Light off | Active-low. |
‘4’ | DigitalWrite(light, HIGH) | Light on | - |
Parameter | Symbol | Value in Code | Purpose |
|---|---|---|---|
Smoke alarm asserts | \(\tau_{\text{high}}\) | ADC > 200 | Enter alarm (sets ALARM = 1, buzzer + red LED). |
Smoke alarm clear | \(\tau_{\text{low}}\) | ADC < 150 | Exit alarm (sets ALARM = 0, green LED). |
Alarm loop step | - | 500 ms | Polling interval in alarm loop. |
PIR debouncing | - | Software + module hold-time | Stable occupancy inference. |
UART baud | - | 9600 bps | UNO--ESP link. |
Reconnect checks | - | In loop() | Reconnect Wi-Fi/Blynk if disconnected. |
Power distribution uses separate regulated rails: 5 V for the UNO and relay coils and 3.3 V for the ESP8266, with a common ground reference. Flyback diodes and local decoupling capacitors are placed near relay coils and sensor modules to limit conducted noise during switching events.
Sensor placement follows typical domestic deployment guidance. The PIR module is mounted to obtain a clear line of sight to doorways and the primary circulation zone, while avoiding windows and HVAC outlets that can induce spurious triggers through thermal gradients or drafts [39]. The MQ-2 sensor is placed near the notional kitchen zone, above floor level and away from strong airflow, to improve interception of smoke and warm rising gases before hazardous accumulation [40]. These placement choices are treated as part of the methodology because they influence false trigger rate, alarm sensitivity, and recovery behaviour.
Arduino firmware is implemented in C/C++ using the Arduino Integrated Development Environment (IDE) and organised into three logical services: Sense, Decide, and Act. Sense periodically samples the PIR and MQ-2 channels, applies debouncing and resistance normalisation, and updates internal occupancy and alarm flags. Decide implements the state machine in (1)–(4), including minimum on and off timers, prioritisation of safety over convenience, and handling of manual override requests received from the ESP8266. Act drives relays, LEDs, and buzzer outputs and generates concise status messages for upstream transmission.
On the networking side, the ESP8266 establishes Wi-Fi connectivity and maintains a persistent session with the Blynk cloud service. The choice of Blynk is consistent with prior work showing that it reduces development time for mobile interfaces in small IoT deployments while still allowing later migration to self-hosted servers when required [41]. The module exposes virtual pins corresponding to lamp and fan commands, real-time gas readings, and alarm flags. Smartphone actions trigger Blynk callbacks that issue serial commands to the Arduino, while local alarm events trigger notification pushes.
All safety-critical behaviour, including alarm assertion and ventilation control, resides on the Arduino. The network layer augments local autonomy rather than replacing it. If WLAN connectivity or the cloud path fails, the Arduino continues to monitor the environment and operate relays according to the configured policy, consistent with recommended practice for safety-related IoT systems where cloud services are treated as advisory layers rather than hard dependencies [42].
Before trials, a calibration procedure is applied to reduce nuisance operation and improve repeatability. For the PIR sensor, hardware sensitivity and hold-time trimmers are tuned jointly with software debouncing so micro-movements and slow thermal drift do not cause frequent toggling. For the MQ-2, the sensor is energised for at least 24 hours to stabilise $R_0$, after which staged sources such as incense and alcohol swabs are used to select conservative values for $\tau_{\text {high}}$ and $\tau_{\text {low}}$. Related MQ-2 leakage detectors report similar burn-in and staged-source procedures as necessary conditions for repeatable behaviour across environments [43]. Connecting an ESP8266 with an MQ-2 sensor supports efficient leak detection and real-time monitoring, and has been reported to improve safety in home settings when notifications are integrated into the user interface [44], [45].
Validation is organised into three phases to separate electrical integrity, timing performance, and scenario realism. First, bench tests verify relay isolation and correct switching under nominal and elevated load conditions, and confirm suppression of relay-coil transients using oscilloscope observation. Second, functional tests quantify latency. Timestamps are recorded from the instant a sensor event occurs to the instant a relay changes state or a notification is displayed on the smartphone. Under typical local area network conditions, the design target is under 200 ms for local switching and under 1 s for smartphone alerts, values aligned with user-perception thresholds reported in smart-building interaction studies [46]. Third, scenario tests emulate home-like patterns: entering and leaving the monitored zone, lingering near the PIR boundary, and exposing the MQ-2 to controlled smoke or aerosol plumes. These scenario trials are used to quantify false-on and false-off behaviour for occupancy control, and to assess alarm assert and clear stability under repeated exposures.
Maintainability and extensibility are built into the prototype at both hardware and firmware levels. Relays and sensors connect through plug-in terminals and keyed leads so modules can be replaced without soldering. Configuration parameters, including thresholds and timers, are stored in non-volatile memory and can be edited from the smartphone interface, reducing the need for physical access during iteration. Spare GPIO and analogue channels remain available on the Arduino headers to support future integration of additional sensors such as temperature, illuminance, or door contacts without redesigning the core node.
4. Results
This section evaluates the prototype against the objectives defined in Section 3: safe retrofit into existing dwellings, occupancy-aware convenience, and early hazard detection with cross-platform alerts. The evidence is presented from the hardware upward. We begin by confirming circuit integrity and noise control, then describe software and interface behaviour, and finally report end-to-end scenarios with attention to stability and abnormal conditions.
Figure 3 shows the consolidated schematic integrating the Arduino UNO controller, ESP8266 interface, PIR module, MQ-2 gas and smoke sensor, and a four-channel opto-isolated relay stage. The low-voltage domain is intentionally split into a 5 V rail for the UNO and relay coils, and a dedicated 3.3 V rail for the ESP8266. The rails share a common reference yet remain independently regulated. This separation reduces susceptibility to brownouts during Wi-Fi transmission bursts and isolates communication load transients from the sensing and actuation path, which is a frequent failure mechanism in low-cost IoT nodes.

The physical wiring reproduced the schematic closely (Figure 4). Sensor leads were kept short, and a star-ground layout was adopted to limit coupling of relay switching transients into the analogue MQ-2 channel. Continuity checks confirmed correct mapping between controller pins and relay inputs, and no inadvertent shorts were detected between low- and high-voltage domains. Under repeated switching, no relay chatter or visible contact welding was observed for the modest lamp and fan loads used here, indicating that the opto-isolated relay board and suppression measures are adequate for the present operating envelope.

To approximate a small apartment while retaining repeatability, the hardware was mounted in a two-zone cardboard mock-up labelled “kitchen” and “living room” (Figure 5). The PIR sensor was positioned to monitor the approach path into the living area, while the MQ-2 module was placed near the kitchen partition but away from direct drafts. This layout enabled controlled motion trajectories and vapour or smoke exposures with limited cross-coupling between sensing channels. The lamp and fan were mounted in view so that state changes could be verified visually during each test.

The firmware, developed in the Arduino IDE, integrates three layers: local sensing and control on the UNO, a compact UART command path between the UNO and ESP8266, and the Blynk client that exposes a smartphone dashboard. Compilation with the ESP8266 core and Blynk libraries completed without warnings, and serial console traces showed stable boot, Wi-Fi association, and authentication to the Blynk cloud.
On the user side, the mobile interface presents a smoke dial, motion status text, and two large buttons for light and fan control (Figure 6). In operation, the app receives streaming sensor updates while button presses are translated into single-character UART commands. At the configured baud rate of 9600 bps (Table 3), the transport overhead of a single-byte command is about 1 ms, so interface responsiveness is dominated by Wi-Fi and cloud path variability rather than the local serial link.

Manual commands issued from the app toggled the lamp and fan reliably (Figure 7). Relay clicks were audibly coincident with on-screen state changes, and no missed or duplicated transitions were observed during repeated toggling. From a control perspective, this establishes a stable baseline: the network layer provides user interaction and visibility, but it does not replace deterministic local actuation. When the app is closed, the embedded state machine continues to operate using PIR and MQ-2 inputs.

When a person entered the mock living area and crossed the PIR field of view, the motion flag changed from “NORMAL” to “MOTION DETECTED” and a pop-up notification was raised (Figure 8). The same event enabled occupancy-gated loads according to the policy formalised in Eq. (1). With the combined hardware hold-time and software debouncing described in Section 3, slow hand movements and minor body shifts did not produce rapid on–off cycling. The off-delay timer also prevented nuisance shut-offs during brief absences, for example when a user stepped into the adjacent zone for a short interval. Practically, these behaviours are essential: occupants interpret frequent toggling as malfunction, and relay cycling imposes unnecessary wear even when electrical safety is not compromised.

Exposing the MQ-2 sensor to a controlled source, such as lighter vapour held several centimetres away, produced a clear excursion on the smoke dial and triggered a “SMOKE DETECTED” alert on the handset (Figure 9). In the illustrated event, the app gauge rose to values above 350 on the 0–500 widget scale, relative to normal readings that were substantially lower during baseline operation, for example around 29.8 in the shown “NORMAL” state. The alarm remained latched until the normalised resistance ratio $S(t)$ in Eq. (3) fell below the lower hysteresis threshold in Eq. (4), after which the indicator returned to “NORMAL”. The time to reach the alarm state was on the order of seconds, dominated by the thermal dynamics of the MQ-2 sensing element, consistent with the characteristic slow response of metal-oxide sensors.

Across repeated trials after the burn-in period, no spurious alarms were observed under clean-air conditions, although transient spikes appeared when airflow changed abruptly near the sensor. This behaviour is expected for MQ-series devices, which are sensitive to local convection and to multiple gases. In a full deployment, it reinforces two engineering implications already built into Section 3: conservative placement away from strong drafts, and the use of $R / R_0$-based normalisation plus hysteresis to reduce threshold chatter under fluctuating ambient conditions.
5. Discussion
Taken together, the tests indicate that the architecture can satisfy the basic responsiveness requirements expected for residential assistance. Local actuation from the UNO to the relay stage is bounded primarily by microcontroller execution and relay coil dynamics, while the UART link contributes negligible delay compared with network variability. Smartphone interactions introduce additional Wi-Fi and cloud delays, yet in practice alerts and command acknowledgements remained within a second-scale window that users perceive as real-time for home control tasks. That perception matters because trust in sensor-driven automation is quickly lost when feedback is inconsistent or delayed.
A central design choice is that safety-critical behaviour is executed locally. If Wi-Fi connectivity is interrupted, the UNO continues to read PIR and MQ-2 inputs, enforce timers and hysteresis, and drive outputs according to the embedded state machine. The mobile layer improves awareness and convenience, but it is not required for core protection. This separation also clarifies the role of the cloud back-end in a safety context: it enhances notification and logging, but it must not become a hard dependency for alarm assertion or hazard-driven actuation.
The experiments underline that calibration is not a cosmetic step, it is the difference between a demonstrator and a deployable node. For MQ-2, operating directly on raw ADC codes can trigger inconsistent behaviour across dwellings because baseline levels drift with sensor ageing, temperature, and cross-sensitivity to non-hazardous vapours. Normalising to a clean-air baseline and applying a two-threshold deadband, as in Eqs. (3) and (4), stabilised behaviour in repeated exposures and reduced oscillation around the decision boundary.
For the PIR channel, joint tuning of the module hold-time and the software debounce provided robust occupancy traces. Short visits were still captured, yet micro-movements did not repeatedly refresh the off-delay timer. From an engineering perspective, this tuning directly affects user acceptance and long-term reliability: overly aggressive timeouts reduce comfort, while overly permissive settings reduce the potential energy benefit referenced in Section 2.
Although the present prototype did not include direct power metering, the implemented policy is aligned with occupancy-based strategies that routinely yield double-digit reductions in lighting energy in intermittently used spaces, as discussed in Section 2. In a small flat, applying the same logic to lighting and a ventilation fan is expected to reduce avoidable runtime without requiring occupants to remember manual switches.
From a safety standpoint, pushing hazard notifications to a smartphone is relevant precisely because domestic incidents often unfold when attention is divided. A local audible alarm remains necessary, yet remote awareness can reduce time-to-response when occupants are outside the room, or briefly away from the dwelling. In that sense, the contribution of the node is not to replace certified detectors, but to complement them by coupling early warning with simple automated responses, such as enabling ventilation under a latched alarm state.
The prototype has clear limitations. First, it relies on a single MQ-2 module, which constrains spatial coverage and makes the system vulnerable to both blind spots and false positives. Redundant sensing, for example combining a gas sensor with a photoelectric smoke detector and a temperature channel, would improve specificity and fault tolerance. Second, the security posture and availability of remote alerts are partly inherited from the app and cloud stack. For field deployment, stronger protections are required, including per-device credentials, rate limiting of remote commands, and a defined update mechanism. Third, notification latency remains coupled to WLAN quality and to the upstream path. Where high resilience is required, an out-of-band alert channel can be added as a fallback.
A practical lesson also emerged during ESP8266 firmware uploads. Intermittent timeouts and sync errors were traced to inadequate current capacity on the 3.3 V rail and incorrect boot-strap pin levels. Migrating the ESP8266 to a dedicated regulator rated at least 500 mA, enforcing the documented GPIO0, GPIO2, and GPIO15 states for programming and run modes, and adding a manual reset path eliminated the issue. This failure mode is common in low-cost nodes: power integrity and boot configuration must be treated as first-class design constraints, not afterthoughts.
To situate the prototype within current practice, we contrast it with representative IoT fire and gas-safety systems drawn from recent Scopus and WoS indexed work. Table 4 summarises the main differences in sensing scope, networking model, and deployment complexity.
Ref. | Application Focus | Platform and Networking | Sensing and Actuation | Distinctive Features | Limitations Relative to This Work |
|---|---|---|---|---|---|
[47], [48] | Kitchen fire prevention in apartments. | Custom IoT node with Wi-Fi link to cloud server. | Temperature, smoke, and flame sensors; gas valve shut-off and alarm. | Multi-sensor fusion around the stove, automatic gas cut-off, cloud logging. | Dedicated to cooking zone, higher sensor and installation cost, no occupancy-aware energy control. |
[49] | Building fire detection with extinguisher support. | Microcontroller unit (MCU) with wireless link to cloud dashboard. | Smoke and temperature sensors; alarm plus extinguisher-class recommendation. | Classifies fire type to suggest suitable extinguisher, focuses on emergency guidance. | Oriented to fire response rather than day-to-day automation, does not address retrofit lighting or fan control. |
[50] | Vision-based fire detection for IoT cameras. | Edge devices plus cloud server running cascade convolutional neural network (CNN). | Video streams from CCTV; alarm to monitoring centre. | High detection accuracy using multi-scale deep learning on red, green, blue (RGB) frames. | Requires cameras, graphics-capable hardware, and stable broadband, which increases cost and raises privacy concerns for homes. |
This work | Retrofit smart-home node for hazard detection and basic automation. | Arduino UNO with ESP8266 Wi-Fi front-end, phone browser or Blynk interface. | Passive infrared (PIR) occupancy sensing, MQ-2 gas/smoke monitoring, relay-isolated lamp and fan control. | Local, deterministic state machine that fuses occupancy-aware actuation with early gas/smoke alerts, minimal bill of materials, browser-accessible without vendor lock-in. | Single gas sensor, limited to two loads, security primitives delegated to app stack, evaluation on benchtop prototype only. |
Compared with kitchen-focused systems that employ multiple sensors and directly actuate gas valves, the present node targets a broader retrofit scenario in which installation friction and cost are decisive constraints. Camera-based approaches can achieve high detection accuracy, yet their compute, bandwidth, and privacy implications are often incompatible with unobtrusive deployments in living spaces. The present contribution is therefore a design argument grounded in implementation evidence: when safety logic is kept local, sensing is calibrated, and timing policies are disciplined, inexpensive microcontroller and Wi-Fi modules can provide practical day-to-day convenience and meaningful hazard awareness in small dwellings. The prototype can sit alongside certified detectors, extend reach into informal or rented spaces, and provide a clear migration path toward richer sensing in future revisions.
6. Conclusions
This study demonstrates that careful embedded design can extract dependable behaviour from inexpensive components when safety and retrofit constraints are treated as engineering requirements, not afterthoughts. The proposed node integrates an Arduino UNO for deterministic sensing and relay control, an ESP8266 for Wi-Fi connectivity, PIR-based occupancy inference, and MQ-2-based smoke and combustible-gas monitoring. In bench checks and scenario trials, the event-driven controller maintained stable switching behaviour: occupancy gating avoided oscillatory relay activity via minimum on/off timing, and hazard events produced latched alerts that cleared predictably under hysteresis. The same evidence also clarifies deployment constraints. Integration with 230 V circuits requires enclosure integrity, strain relief, fusing, and installation consistent with local electrical practice. Long-term reliability depends on relay contact endurance under real load types, power integrity on the 3.3 V rail during Wi-Fi bursts, and MQ-2 ageing effects, including baseline drift and cross-sensitivity. A deployable revision should therefore treat maintenance as part of the system design: modular connectors for replacement, periodic calibration guidance for the gas channel, boot-time self-tests for stuck-at faults, watchdog recovery, and lightweight event logging. With these safeguards, the architecture offers a realistic path from benchtop demonstrator to a cost-sensitive retrofit node suitable for sustained residential operation.
Conceptualization, J.A.J.A. and A.A.H.; methodology, H.T.M.D.; software, J.A.J.A.; validation, H.T.M.D.; formal analysis, H.B.M.N.; investigation, J.A.J.A.; resources, H.B.M.N.; data curation, J.A.J.A.; writing—original draft preparation, J.A.J.A. and S.G.H.; writing—review and editing, A.A.H. and I.; visualization, A.A.H.; supervision, H.B.M.N.; project administration, H.T.M.D.; funding acquisition, I. and S.G.H. All authors have read and agreed to the published version of the manuscript.
All the datasets used in this study are available from the Zenodo database.
Accession number: https://zenodo.org/records/17312669.
The authors express their gratitude to the Centre for Research and Innovation Management (CRIM) at Universiti Teknikal Malaysia Melaka (UTeM) for their valuable support in this research.
The authors declare that they have no conflicts of interest.
