Smart Indoor Safety project

ESP32 · Arduino C++ · Firmware walkthrough

Smart Indoor Safety: Code Explained

From sensor inputs to local decisions, HTTPS messages and a remote door command—an annotated walkthrough of the supplied sketch.

Chathuranga Polkotuwa & Suad Abujarad · Educational model-house prototype

Public teaching copy: credentials removed. Change the exposed Wi-Fi password and device secret. The sketch has security and output-polarity issues described below; it is not a deployment-ready alarm or access-control system.

Actual interior showing the breadboard, wiring and output devices; presentation slide 32.

One cycle, two directions

  1. 01

    setup(): GPIO, DHT, servos → wait for Wi-Fi

  2. 02

    loop(): elapsed time ≥ 2000 ms?

  3. 03

    sendSensorData(): read → decide → outputs

ESP32 JSON payloadHTTPS POST → dashboard200 response → door command
Source-derived control flow, not a measured latency or reliability chart.

STEP 01

Libraries and configuration

The sketch is Arduino C++ for an ESP32. WiFi joins the network; WiFiClientSecure creates the TLS connection; HTTPClient sends an HTTP request; DHT reads the DHT11; ESP32Servo generates servo control pulses. Install the ESP32 board package, DHT sensor library (and its dependency if requested), and ESP32Servo through Arduino IDE.

The Wi-Fi name/password and device secret were private values in the supplied file. They are replaced throughout this public copy. Rotate the exposed Wi-Fi password and device secret before further use. Configure replacement credentials only in a private local copy; do not paste them into this website.

The supplied target host is smart-haven-heart.lovable.app and the path is /api/public/sensors. Together they form the firmware's HTTPS destination. This is a configured external dashboard, not an endpoint added to EMBEDLIX, and its availability or authorization is not verified here. DEVICE_ID is esp32-home; the destination must associate readings with that exact identifier.

The x-device-secret request header carries the device credential. HTTPS protects transport only if the remote certificate is validated. This sketch disables that validation later; do not treat it as a secure deployment template.

STEP 02

Pins, sensors and state

The GPIO table below matches the uploaded sketch. GPIO34 and GPIO35 are analog inputs for the LDR and MQ sensor; on a classic ESP32 these are input-only ADC1 pins. GPIO27 and GPIO13 read digital module outputs. GPIO4 supplies the DHT11 data connection. Exact board variants must be checked before wiring.

DHT dht(dhtPin, DHTTYPE) constructs a reader configured for DHT11, while windowServo and doorServo are separate Servo objects. lastDoorOpen starts false and tracks the last accepted door state. lastSendMs starts zero; SEND_INTERVAL_MS is 2000 milliseconds.

Example: writing 90 to windowServo requests a 90° servo position; it does not measure the actual window angle or prove that the mechanism moved. Servo power should use a suitably rated low-voltage supply with shared signal ground, not be assumed safe from a GPIO pin. Confirm 3.3 V input limits, module output voltages, resistor values and supply ratings separately.

ComponentGPIOSignalPurpose
DHT114Digital inputTemperature and humidity
MQ-series gas sensor35Analog inputRaw gas-sensor reading
PIR motion sensor27Digital inputMotion detection
Flame sensor13Digital inputActive-low flame indication
LDR34Analog inputAmbient brightness
Buzzer25Digital outputLocal audible indication
RGB LED — red16Digital outputStatus indicator channel
RGB LED — green17Digital outputStatus indicator channel
RGB LED — blue18Digital outputStatus indicator channel
Relay23Digital outputTemperature-based load simulation
Window servo19PWMPrototype window mechanism
Door servo14PWMRemote door mechanism
Room light LED22Digital outputMotion + darkness lighting

STEP 03

Startup and Wi-Fi

setup() runs once after reset. Serial.begin(115200) sets the Serial Monitor baud rate. After a 200 ms delay, pinMode configures PIR/flame inputs and the buzzer, RGB, relay and room-light outputs. The analog inputs are read later with analogRead.

The initial relay and room light pins are LOW. The buzzer starts HIGH with the comment “buzzer OFF (active-low module).” The initial RGB call requests green under the declared common-anode logic. dht.begin() starts the reader.

Both servos use 50 Hz control, attach with 500–2400 µs pulse limits, and start at 0°. These limits are configuration, not measured safe endpoints for every SG90 mechanism; test mechanical travel carefully.

WiFi.begin(ssid, pass) starts connection. The while loop delays 500 ms and prints a dot until connected, then prints the local IP address. There is no startup timeout: wrong credentials can prevent loop() and all sensor automation from starting. After startup there is no explicit reconnect routine in this sketch; library-dependent recovery is unverified.

STEP 04

Two-second scheduler

loop() reads millis(), an unsigned millisecond counter since startup. It calls sendSensorData() when now - lastSendMs is at least 2000, assigning lastSendMs = now before the call. Unsigned subtraction handles the usual counter wraparound; do not replace it with a naive absolute deadline comparison.

Example: at 1999 ms, a previous timestamp of 0 does not trigger; at 2000 ms it does. If Wi-Fi startup took longer than two seconds, the first loop may send immediately. Calls are not guaranteed to happen at exactly 2, 4 and 6 seconds: DHT reads and synchronous HTTP requests take time.

Local automation is sampled in the same function as networking. It is not continuously checked between sends, and a blocking POST delays the next sensor cycle. The chart is an idealized schedule, not measured response time. A next version could decouple sampling, output decisions and transmission and define request timeouts.

Idealized send checkpoints

0 s

Reference

2 s

Read → act → POST

4 s

Read → act → POST

6 s

Read → act → POST

Illustrative 2000 ms intervals only. Startup and blocking sensor/network calls shift actual timestamps; no timing measurements were supplied.

STEP 05

Readings and room light

sendSensorData() reads raw LDR/gas ADC values and the PIR input. roomDark is ldrValue < 2500; motionDetected is true when the PIR is HIGH. The room-light output is HIGH only when both are true.

bool roomDark = (ldrValue < 2500);
bool motionDetected = (motionValue == HIGH);
bool roomLightOn = (roomDark && motionDetected);
LDR ADCMotionDark?Room light
2400HIGHYesON
2400LOWYesOFF
2500HIGHNo (strict comparison)OFF
3000HIGHNoOFF

These are invented teaching inputs, not recorded readings. LDR numbers are raw ADC codes, not lux. The direction of the brightness relationship depends on the voltage divider; this sketch assumes smaller values mean darker. Confirm it on the actual circuit.

STEP 06

Gas, flame and window

flameDetected is true when the flame input is LOW. gasDetected is true only above 1300. The OR operator means either input can set dangerDetected.

bool flameDetected = (flameValue == LOW);
bool gasDetected = (gasValue > 1300);
bool dangerDetected = gasDetected || flameDetected;
Gas ADCFlame pinGas detected?DangerWindow command
1200HIGHNoNo0°
1300HIGHNoNo0°
1301HIGHYesYes90°
1200LOWNoYes90°

The danger branch writes the buzzer HIGH, calls setRGB(LOW, HIGH, LOW), moves the window to 90° and reports window_open true. The normal branch writes LOW, calls setRGB(HIGH, LOW, LOW), closes to 0° and reports false. None of these output states is sensor feedback.

Important contradictions: the helper inverts each RGB channel. For the declared common-anode wiring, danger requests GREEN and normal requests RED—not the red-danger prose in the report. Also, the startup comment calls the buzzer active-low/OFF at HIGH, but the danger branch uses HIGH and says ON. Pin commands are certain; physical buzzer operation and actual wiring must be checked rather than guessed. The simulator below reports pin levels, not verified sound or color.

Safety: this is a model mechanism, not a fire/gas safety design. Use simulated inputs—never released gas or open flames—and never apply this automatic window response to a real hazard.

Gas > 1300 OR flame pin LOW

Danger = true

Window 90° · buzzer pin HIGH · green channel requested

LDR < 2500 AND PIR HIGH

Room light = true

Room-light GPIO22 HIGH

Exact software decisions from the upload. Physical output polarity and hazard safety are not validated.

STEP 07

Temperature and relay

dht.readTemperature() and dht.readHumidity() return floating-point values. isnan detects failed reads. Serial prints valid measurements or a failure message. The relay variable starts false each cycle; for a valid temperature below 27°C the pin becomes HIGH and relayOn becomes true. At 27°C or above the pin becomes LOW.

TemperaturePrevious relay pinNew relay pinPosted relay_on
26.9°CEitherHIGHtrue
27.0°CEitherLOWfalse
Invalid / NaNHIGHHIGH (unchanged)false
Invalid / NaNLOWLOW (unchanged)false

Fault mismatch: an invalid temperature skips every digitalWrite in the relay branch. A previously HIGH output therefore remains HIGH, even though the local relayOn variable and posted state are false. No fail-safe shutdown is implemented for this case. The connected load and relay module's active polarity remain unverified.

There is no hysteresis or minimum switching interval, so values near 27°C can cause repeated switching. Before sending, invalid DHT values are replaced with zero. This also means the dashboard cannot distinguish a failed read from a genuine zero using these fields alone; no validity flag is sent. A revised design should retain fault status and report the actual commanded output.

STEP 08

JSON and HTTPS POST

postSensorData() first checks WiFi.status(). If disconnected, it prints a message and returns without POST. Local decisions from sendSensorData() have already run that cycle. It then builds an HTTPS URL and HTTP headers and manually concatenates JSON into a String.

The uploaded sketch calls client.setInsecure(). TLS encryption can still be used, but server-certificate verification is disabled, allowing an impersonated server to receive the device secret or send commands. For a deployment, provision appropriate trusted certificate validation and test renewal; do not disable verification to fix connection problems.

Payload fields are device_id, ldr, gas, temperature, humidity, motion, flame, gas_detected, danger, window_open, relay_on and room_light. Numbers and booleans are unquoted JSON values; temperature/humidity use one decimal place. The example below is synthetic, computed from gas=1400, LDR=2400, motion=true, no flame and 26.5°C.

{
  "device_id": "esp32-home",
  "ldr": 2400,
  "gas": 1400,
  "temperature": 26.5,
  "humidity": 58.0,
  "motion": true,
  "flame": false,
  "gas_detected": true,
  "danger": true,
  "window_open": true,
  "relay_on": true,
  "room_light": true
}

http.POST(payload) is synchronous. Repeated String concatenation is simple for a prototype, but a reviewed JSON serializer would improve escaping and field validation—especially if device identifiers ever become configurable. http.end() frees the HTTP resources after the response branch.

Historical screenshot from presentation slide 33; values are recorded examples, not live telemetry.

STEP 09

Response and door control

The sketch treats HTTP 200 as success, reads and prints the body, and searches for the exact substring "door_open":true. If found, the requested state is open; otherwise it assumes closed. Only a change from lastDoorOpen writes the door servo: 90° open, 0° closed.

HTTP response body (200)Sketch interpretationWhy
{"door_open":true}OpenExact substring found
{"door_open": true}ClosedSpace prevents matching
{"door_open":false}ClosedTrue substring absent
{}ClosedMissing command is treated as false

This is not JSON parsing. Valid whitespace can change behavior, and missing, nested or malformed data is not validated. For example, if the door was open and a 200 body omits the field, this sketch commands it closed. A robust revision would parse structured JSON, require a boolean field and keep a defined safe state for invalid responses.

A 401 prints “DEVICE_SECRET mismatch,” but the actual reason could be any server-side rejection; no server implementation is supplied. Other status codes/errors are logged; non-200 responses do not alter lastDoorOpen. Remote commands are only checked after a successful POST, so two seconds is not a guaranteed command latency.

There is no door position feedback, access-control audit, offline command queue or verified API contract in this upload. This page does not send requests or control the actual device.

STEP 10

Worked cycle and debugging

Synthetic cycle: LDR=2400, gas=1400, PIR=HIGH, flame=HIGH, temperature=26.5°C and humidity=58%. The sketch turns the room-light pin HIGH, calculates danger=true from gas, writes buzzer HIGH, requests the green channel, commands the window to 90°, and writes relay HIGH. It posts those calculated states. A 200 response containing {"door_open":true} changes the door command from 0° to 90°.

On the next synthetic cycle, gas=1200 and flame=HIGH remove danger, so the window closes and the RGB call requests red. If temperature is now 28°C the relay is LOW. If instead the temperature read fails, the relay pin stays at its prior level while relay_on is false—use the invalid-DHT example below to see this distinction.

Serial observationMeaning / next check
Connecting to WiFi followed by dotsStartup remains blocked; privately check network setup
DHT sensor read failed!Check model, wiring and supply; do not interpret posted zero as valid
WiFi not connected, skipping POSTLocal cycle ran, but cloud send was skipped
POST status: 200A body was received; it still requires correct command validation
401 UnauthorizedVerify the private credential and actual server rejection reason
Danger! Buzzer ON, Window OPENA log of intended actions, not physical output confirmation

Reproduce threshold examples with software inputs or safe low-voltage bench signals. Check each output's polarity before integration; do not connect mains loads. The teaching simulator runs only in the browser and cannot validate sensor accuracy, wiring, server security or physical mechanisms.

Try a synthetic sensor cycle

Software-only examples. No live readings or hardware commands.

Danger
true
Room light
ON
Window command
90°
Buzzer pin
HIGH
RGB request (common-anode)
green
Physical relay pin command
HIGH
Posted relay_on
true
Posted temperature
26.5°C

STEP 11

Review before deployment

The uploaded sketch is preserved below with only Wi-Fi name, Wi-Fi password and device secret replaced. Its decision logic and limitations are intentionally not silently fixed. Reading and copying it is not evidence that it has been compiled, flashed or tested on the model hardware.

Before any real deployment: rotate exposed credentials; enable trusted certificate verification; implement robust command parsing and server-side device authorization; reconcile buzzer/RGB wiring; define relay behavior for sensor faults; distinguish missing readings from zero; add calibrated thresholds and appropriate hysteresis; add bounded startup/reconnect/request timing; and independently verify low-voltage wiring and mechanical limits.

This upload clarifies the firmware-side behaviors left uncertain in the earlier report excerpts. It does not reconcile historical dashboard screenshots, provide the cloud server code or establish a certified safety system.

Complete sketch · public teaching copy

Original behavior preserved. Only the Wi-Fi name, Wi-Fi password and device secret have been replaced with placeholders. Examples above are synthetic; the code has not been compiled or tested on hardware here.

/*
  Smart Indoor Safety and Environment Monitoring System
  ESP32 -> Lovable Cloud dashboard

*/

#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <DHT.h>
#include <ESP32Servo.h>

// =================== USER CONFIG ===================
// Wi-Fi
char ssid[] = "YOUR_WIFI_NAME";
char pass[] = "YOUR_WIFI_PASSWORD";

// Lovable Cloud dashboard (URL)
const char* SERVER_HOST   = "smart-haven-heart.lovable.app";
const char* SENSORS_PATH  = "/api/public/sensors";

// Must match DEVICE_SECRET stored in Lovable Cloud -> Secrets
const char* DEVICE_SECRET = "YOUR_DEVICE_SECRET";

// Device id (the dashboard listens for this exact id)
const char* DEVICE_ID     = "esp32-home";
// ===================================================

// ---------------- PIN DEFINITIONS ----------------
const int ldrPin       = 34;
const int gasAnalogPin = 35;
const int pirPin       = 27;
const int dhtPin       = 4;

const int buzzerPin    = 25;
const int redPin       = 16;
const int greenPin     = 17;
const int bluePin      = 18;
const int relayPin     = 23;

const int servoPin     = 19;   // SG90 window servo
const int flamePin     = 13;   // Flame sensor
const int doorServoPin = 14;   // Door servo (cloud-controlled)
const int roomLightPin = 22;

// ---------------- DHT ----------------
#define DHTTYPE DHT11
DHT dht(dhtPin, DHTTYPE);

Servo windowServo;
Servo doorServo;

// last known door state from cloud 
bool lastDoorOpen = false;

unsigned long lastSendMs = 0;
const unsigned long SEND_INTERVAL_MS = 2000; // every 2s 

// ---------------- RGB FUNCTION ----------------
void setRGB(bool redState, bool greenState, bool blueState) {
  // Common-anode style logic preserved from original sketch
  digitalWrite(redPin,   !redState);
  digitalWrite(greenPin, !greenState);
  digitalWrite(bluePin,  !blueState);
}

// ---------------- HTTP POST ----------------
void postSensorData(int ldrValue, int gasValue, float temperature, float humidity,
                    bool motionDetected, bool flameDetected, bool gasDetected,
                    bool dangerDetected, bool windowOpen, bool relayOn, bool roomLightOn) {

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi not connected, skipping POST");
    return;
  }

  WiFiClientSecure client;
  client.setInsecure(); 

  HTTPClient http;
  String url = String("https://") + SERVER_HOST + SENSORS_PATH;
  if (!http.begin(client, url)) {
    Serial.println("http.begin failed");
    return;
  }

  http.addHeader("Content-Type", "application/json");
  http.addHeader("x-device-secret", DEVICE_SECRET);

  // Build JSON payload
  String payload = "{";
  payload += "\"device_id\":\""   + String(DEVICE_ID) + "\",";
  payload += "\"ldr\":"           + String(ldrValue) + ",";
  payload += "\"gas\":"           + String(gasValue) + ",";
  payload += "\"temperature\":"   + String(isnan(temperature) ? 0 : temperature, 1) + ",";
  payload += "\"humidity\":"      + String(isnan(humidity)    ? 0 : humidity,    1) + ",";
  payload += "\"motion\":"        + String(motionDetected   ? "true" : "false") + ",";
  payload += "\"flame\":"         + String(flameDetected    ? "true" : "false") + ",";
  payload += "\"gas_detected\":"  + String(gasDetected      ? "true" : "false") + ",";
  payload += "\"danger\":"        + String(dangerDetected   ? "true" : "false") + ",";
  payload += "\"window_open\":"   + String(windowOpen       ? "true" : "false") + ",";
  payload += "\"relay_on\":"      + String(relayOn          ? "true" : "false") + ",";
  payload += "\"room_light\":"    + String(roomLightOn      ? "true" : "false");
  payload += "}";

  int code = http.POST(payload);
  Serial.print("POST status: "); Serial.println(code);

  if (code == 200) {
    String resp = http.getString();
    Serial.print("Response: "); Serial.println(resp);

    // crude JSON parse for "door_open":true / false (no ArduinoJson dependency)
    bool doorOpenFromCloud = (resp.indexOf("\"door_open\":true") >= 0);

    if (doorOpenFromCloud != lastDoorOpen) {
      lastDoorOpen = doorOpenFromCloud;
      if (doorOpenFromCloud) {
        doorServo.write(90);
        Serial.println("Door OPEN (from cloud)");
      } else {
        doorServo.write(0);
        Serial.println("Door CLOSED (from cloud)");
      }
    }
  } else if (code == 401) {
    Serial.println("401 Unauthorized -> DEVICE_SECRET mismatch");
  } else {
    Serial.print("HTTP error: "); Serial.println(http.errorToString(code));
  }

  http.end();
}

// ---------------- SENSOR LOOP (every 2s) ----------------
void sendSensorData() {

  // -------- READ SENSORS --------
  int ldrValue    = analogRead(ldrPin);
  int gasValue    = analogRead(gasAnalogPin);
  int motionValue = digitalRead(pirPin);

  // -------- ROOM LIGHT LOGIC --------
  bool roomDark       = (ldrValue < 2500);
  bool motionDetected = (motionValue == HIGH);
  bool roomLightOn    = (roomDark && motionDetected);

  if (roomLightOn) {
    digitalWrite(roomLightPin, HIGH);
    Serial.println("Dark room + motion detected -> Room light ON");
  } else {
    digitalWrite(roomLightPin, LOW);
    Serial.println("Room light OFF");
  }

  int  flameValue     = digitalRead(flamePin);
  bool flameDetected  = (flameValue == LOW);
  bool gasDetected    = (gasValue > 1300);
  bool dangerDetected = gasDetected || flameDetected;

  float temperature = dht.readTemperature();
  float humidity    = dht.readHumidity();

  // -------- SERIAL --------
  Serial.println("----------- SENSOR DATA -----------");
  Serial.print("LDR: ");    Serial.println(ldrValue);
  Serial.print("Gas: ");    Serial.println(gasValue);
  Serial.print("Motion: "); Serial.println(motionValue);
  Serial.print("Flame: ");  Serial.println(flameValue);
  Serial.println(flameDetected ? "FLAME DETECTED!" : "No Flame");
  Serial.println(gasDetected   ? "GAS DETECTED!"   : "Gas Normal");

  if (isnan(temperature) || isnan(humidity)) {
    Serial.println("DHT sensor read failed!");
  } else {
    Serial.print("Temperature: "); Serial.print(temperature); Serial.println(" C");
    Serial.print("Humidity: ");    Serial.print(humidity);    Serial.println(" %");
  }

  // -------- DANGER LOGIC --------
  bool windowOpen;
  if (dangerDetected) {
    digitalWrite(buzzerPin, HIGH);
    setRGB(LOW, HIGH, LOW);
    windowServo.write(90);
    windowOpen = true;
    Serial.println("Danger! Buzzer ON, Window OPEN");
  } else {
    digitalWrite(buzzerPin, LOW);
    setRGB(HIGH, LOW, LOW);
    windowServo.write(0);
    windowOpen = false;
    Serial.println("Normal. Buzzer OFF, Window CLOSED");
  }

  // -------- TEMPERATURE / RELAY LOGIC --------
  bool relayOn = false;
  if (!isnan(temperature)) {
    if (temperature < 27) {
      digitalWrite(relayPin, HIGH);
      relayOn = true;
      Serial.println("Temp < 27C -> Relay ON");
    } else {
      digitalWrite(relayPin, LOW);
      relayOn = false;
      Serial.println("Temp >= 27C -> Relay OFF");
    }
  }

  // -------- SEND TO CLOUD --------
  postSensorData(ldrValue, gasValue,
                 isnan(temperature) ? 0 : temperature,
                 isnan(humidity)    ? 0 : humidity,
                 motionDetected, flameDetected, gasDetected,
                 dangerDetected, windowOpen, relayOn, roomLightOn);

  Serial.println("-----------------------------------\n");
}

// ---------------- SETUP ----------------
void setup() {
  Serial.begin(115200);
  delay(200);

  // Inputs
  pinMode(pirPin,   INPUT);
  pinMode(flamePin, INPUT);

  // Outputs
  pinMode(buzzerPin,    OUTPUT);
  pinMode(redPin,       OUTPUT);
  pinMode(greenPin,     OUTPUT);
  pinMode(bluePin,      OUTPUT);
  pinMode(relayPin,     OUTPUT);
  pinMode(roomLightPin, OUTPUT);

  // Initial states
  digitalWrite(buzzerPin,    HIGH); // buzzer OFF (active-low module)
  digitalWrite(relayPin,     LOW);
  digitalWrite(roomLightPin, LOW);
  setRGB(LOW, HIGH, LOW);           // initial RGB (mirrors original sketch)

  dht.begin();

  // Window servo
  windowServo.setPeriodHertz(50);
  windowServo.attach(servoPin, 500, 2400);
  windowServo.write(0);

  // Door servo (locked initially)
  doorServo.setPeriodHertz(50);
  doorServo.attach(doorServoPin, 500, 2400);
  doorServo.write(0);
  lastDoorOpen = false;

  // Wi-Fi
  Serial.print("Connecting to WiFi");
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Connected. IP: ");
  Serial.println(WiFi.localIP());
}

// ---------------- LOOP ----------------
void loop() {
  unsigned long now = millis();
  if (now - lastSendMs >= SEND_INTERVAL_MS) {
    lastSendMs = now;
    sendSensorData();
  }
}
Back to project