IoT Home Automation Project Tutorial

freeCodeCamp.org

Summary

Ebenezer Asabre, a graduate engineering student at the University of Massachusetts, Amherst, walks through building a complete IoT home automation system. An ESP32 microcontroller simulates temperature, pressure, air quality, and light intensity readings every five seconds and publishes them over MQTT to a Raspberry Pi 3 Model B running a Mosquitto broker, while subscribing to commands that toggle four LEDs and a servo motor. On the backend, a layered Node.js and Express server buffers 60 readings over five minutes before writing averaged records into PostgreSQL and uses Socket.io to stream real-time telemetry to a Plotly and EJS web dashboard.

This architecture demonstrates how to pair low-bandwidth MQTT device messaging with WebSockets and buffered SQL storage so high-frequency sensor streams do not overwhelm the database. Next, Asabre plans to release projects covering STM32 with FreeRTOS and building bare-metal embedded firmware from the terminal without an IDE.

How time-sensitive the topic is: Evergreen

By the numbers

  • 5 seconds: Interval at which the ESP32 publishes simulated sensor readings and updates the live web dashboard. (Mentioned at 1:07)
  • 4 LEDs: Number of LEDs connected alongside a servo motor to the ESP32 microcontroller client. (Mentioned at 1:16)
  • 115200 baud rate: Serial communication speed initialized in the Arduino setup function for the ESP32. (Mentioned at 16:36)
  • 180 degrees: Angle the servo motor rotates to on pin 13 when the air quality sensor switch is turned on. (Mentioned at 21:05)
  • 1883 port number: Default MQTT network port configured on the Mosquitto broker listener for local network access. (Mentioned at 23:13)
  • 5432 port number: Default port configured in db.config.js to connect the Node.js application to PostgreSQL. (Mentioned at 29:21)
  • 3000 port number: Localhost port on which the Node.js Express and Socket.io server listens for browser requests. (Mentioned at 49:15)
  • 60 samples: Number of 5-second sensor readings collected in the server buffer over 5 minutes before averaging and saving to PostgreSQL. (Mentioned at 1:02:00)
  • 20 data points: Maximum number of points displayed on each live Plotly sensor graph before shifting older points left. (Mentioned at 1:07:57)

Questions this video answers

How do MQTT and Socket.io work together in a Node.js IoT home automation system?

The ESP32 microcontroller uses MQTT to publish sensor telemetry and subscribe to hardware commands through a Mosquitto broker on a Raspberry Pi. The Node.js server subscribes to those MQTT topics and uses Socket.io to push real-time updates to the web browser and relay user checkbox toggles back to MQTT. This pairs a lightweight low-bandwidth device protocol with instant bidirectional browser updates.

Ebenezer Asabre, 5:21 to 9:12

From this keypoint: How MQTT and Socket.io Bridge Sensors and Browsers

How do you avoid overloading a PostgreSQL database with frequent IoT sensor readings?

Instead of inserting a new database row every five seconds when the ESP32 publishes data, the Node.js server pushes each incoming reading into an in-memory array buffer. Once the buffer collects 60 samples over five minutes, the server averages each sensor metric with JavaScript's reduce function, writes a single averaged row to PostgreSQL, and empties the buffer.

Ebenezer Asabre, 59:57 to 1:04:42

From this keypoint: Buffering 60 Sensor Samples to Save 5-Minute Averages

How do you allow external devices on a local network to connect to a Mosquitto MQTT broker?

In the Mosquitto configuration file, you must enable anonymous access by setting allow_anonymous to true and add a listener on port 1883 bound to 0.0.0.0. Without binding the listener to 0.0.0.0, Mosquitto blocks external devices like the ESP32 from connecting via the server's IP address.

Ebenezer Asabre, 21:40 to 28:32

From this keypoint: Setting Up Mosquitto, PostgreSQL, and MVC Folders

How can an ESP32 parse MQTT messages to control multiple GPIO pins and a servo motor?

The ESP32 subscribes to the esp/cmd topic and passes incoming payload strings to a parser that splits the text at the comma into a sensor name and an integer state. Conditional statements then match the sensor name to trigger digitalWrite on LED pins or call the ESP32Servo library to rotate pin 13 between 0 and 180 degrees.

Ebenezer Asabre, 12:45 to 16:31

From this keypoint: Asabre Parses MQTT Payloads to Toggle ESP32 Pins

How do you query historical sensor data within a relative hour range in PostgreSQL?

Using a timestamp column in the sensordata table, you write a SELECT query with a WHERE clause using BETWEEN NOW() - INTERVAL for the end hour and NOW() - INTERVAL for the start hour. This lets users enter a simple range like 1,5 on the frontend to retrieve all records saved between one and five hours ago.

Ebenezer Asabre, 34:19 to 39:56

From this keypoint: Writing SQL Interval Queries and CRUD Operations

How do you display real-time scrolling sensor graphs in HTML using Plotly and Socket.io?

The frontend listens for Socket.io sensor data events and passes the incoming object to an updatePlot function that appends the current time and sensor readings to arrays. To keep the chart readable, the array shifts out the oldest value whenever it exceeds 20 points before calling Plotly to redraw the four sensor graphs.

Ebenezer Asabre, 1:04:42 to 1:12:37

From this keypoint: Rendering Live Plotly Charts and EJS History Tables

Credible AI™ signals

Confidence: Demonstrated Working Code. Ebenezer Asabre walks through live hardware demonstrations, functional C++ firmware, and a complete Node.js and PostgreSQL backend, proving the architecture works in real time.

Bias: Standard Open-Source Stack. The tutorial focuses purely on technical implementation using widely adopted open-source tools like Mosquitto, PostgreSQL, Express, and Socket.io without commercial promotion.

Originality (76%): Full-Stack IoT Integration. While individual tutorials on ESP32 or Node.js are common, combining MQTT hardware control, 5-minute buffer averaging in PostgreSQL, and live Plotly dashboards in one end-to-end build is practical and distinct.

Depth (82%): End-to-End Architecture. Covers the entire data lifecycle from microcontroller pin state parsing and MQTT publish-subscribe topics to MVC backend structuring, SQL interval queries, and WebSocket DOM updates.

Key points (12)

  • Short (26 min): key points 1, 2, 4, 8 and 10
  • Medium (36 min): key points 1, 2, 4, 5, 8, 10 and 11
  • Relaxed (1h 8min): all 12 key points

1. Asabre Demos Live ESP32 Dashboard and Servo Control

Timestamp: 00:01:44 to 00:05:20 (4 min)

Speaker: Ebenezer Asabre

Ebenezer Asabre demonstrates the completed IoT system where a Raspberry Pi 3 Model B hosts both the MQTT broker and Node.js server to control an ESP32 client wired to four LEDs and a servo motor. Toggling dashboard switches sends binary commands that rotate the servo or light LEDs while logging to the Arduino IDE and querying PostgreSQL history.

Impact: Medium. Why it matters: Seeing the hardware respond immediately to browser clicks and database queries grounds the abstract architecture before coding begins.

“So, when the ESP32 receives zero or one, it uses that information to either switch on or off an LED.”

In the video: Ebenezer Asabre, at 3:34

2. How MQTT and Socket.io Bridge Sensors and Browsers

Timestamp: 00:05:21 to 00:09:12 (4 min)

Speaker: Ebenezer Asabre

The system architecture places the Raspberry Pi at the center as an MQTT broker and Node.js backend connected to PostgreSQL and Socket.io. Because MQTT uses a lightweight publish-subscribe model suited for low-bandwidth networks, the ESP32 publishes telemetry to specific topics while Socket.io pushes live updates to the web interface.

Impact: High. Why it matters: Separating device telemetry via MQTT from browser updates via WebSockets creates a scalable pattern for unreliable networks.

“It is a lightweight messaging protocol designed for small sensors and mobile devices in low bandwidth and high latency.”

In the video: Ebenezer Asabre, at 7:31

3. Configuring ESP32 Wi-Fi Reconnection and MQTT Topics

Timestamp: 00:09:12 to 00:12:45 (4 min)

Speaker: Ebenezer Asabre

In the Arduino IDE, Asabre installs the ESP32 board manager and PubSubClient library, defines sensor GPIO pins, and writes functions to connect to Wi-Fi and automatically reconnect to the Raspberry Pi MQTT broker every five seconds if dropped. Upon connecting, the ESP32 subscribes to the esp/cmd topic to listen for incoming server instructions.

Impact: Medium. Why it matters: Auto-reconnection logic ensures wireless microcontrollers recover from network drops without manual resets.

“Now, we know that wireless connections can sometimes be unstable. We need to define the function whenever we are disconnected, the ESP32 will once again connect to the Wi-Fi.”

In the video: Ebenezer Asabre, at 11:22

4. Asabre Parses MQTT Payloads to Toggle ESP32 Pins

Timestamp: 00:12:45 to 00:16:31 (4 min)

Speaker: Ebenezer Asabre

To handle incoming commands from the broker, Asabre writes a callback function that verifies the esp/cmd topic and passes the payload to a string parser. The parser splits the string at the comma into a sensor name and an integer pin state, using conditional checks to write high or low states to the corresponding GPIO pins.

Impact: High. Why it matters: Splitting comma-separated payloads provides a minimal, low-overhead command protocol for constrained C++ firmware.

“We have decoded the incoming string from the broker into the sensor name and the pin state.”

In the video: Ebenezer Asabre, at 15:44

5. Simulating Sensor Telemetry and Driving the Servo

Timestamp: 00:16:31 to 00:21:40 (5 min)

Speaker: Ebenezer Asabre

Inside the Arduino setup and main loop, Asabre initializes serial communication at 115200 baud, configures MQTT port 1883, and simulates floating-point readings for temperature, pressure, air quality, and light intensity to publish every five seconds. He then integrates the ESP32Servo library on pin 13 so air quality commands rotate the servo between 0 and 180 degrees.

Impact: High. Why it matters: Simulating sensor floats lets developers test the full MQTT and database pipeline before wiring physical transducers.

“Whenever from the web client we turn the air sensor on or off, the servo motor will move to zero or move to 180.”

In the video: Ebenezer Asabre, at 21:31

6. Setting Up Mosquitto, PostgreSQL, and MVC Folders

Timestamp: 00:21:40 to 00:28:32 (7 min)

Speaker: Ebenezer Asabre

Moving to the terminal on macOS, Asabre installs Mosquitto and PostgreSQL via Homebrew, configuring the Mosquitto broker to allow anonymous connections and listen on port 1883 across all network interfaces (0.0.0.0). He then initializes a Node.js project with Express, pg, Socket.io, and MQTT dependencies, organizing the backend into config, models, services, controllers, routes, and public directories.

Impact: Medium. Why it matters: Binding Mosquitto to 0.0.0.0 on port 1883 is the critical configuration step that allows external microcontrollers on the LAN to reach the broker.

“Right above this, let us add listener 1883. This is the default port for MQTT. 0.0.0.0 so that this will allow anybody on the network, the home network to have access to the Mosquito.”

In the video: Ebenezer Asabre, at 23:11

7. Asabre Builds the PostgreSQL Connection Pool and Schema

Timestamp: 00:28:32 to 00:34:19 (6 min)

Speaker: Ebenezer Asabre

Asabre configures PostgreSQL connection credentials on port 5432 in db.config.js and instantiates a connection pool in db.js. In sensors.model.js, he writes an asynchronous function that automatically creates the sensordata table if it does not exist, defining an auto-incrementing primary key, a default current timestamp, and numeric columns for the four sensors, alongside basic select queries.

Impact: Medium. Why it matters: Auto-creating the schema with default timestamps ensures the backend initializes cleanly on a fresh Raspberry Pi deployment.

“A model is going to describe the fields in our database and the operations that we would like to do in the database.”

In the video: Ebenezer Asabre, at 30:50

8. Writing SQL Interval Queries and CRUD Operations

Timestamp: 00:34:19 to 00:39:56 (6 min)

Speaker: Ebenezer Asabre

Continuing in sensors.model.js, Asabre implements a time-range query using PostgreSQL's BETWEEN NOW() - INTERVAL syntax so users can fetch historical records between specific past hours. He completes the data access layer by adding parameterized INSERT and DELETE queries that return the modified row and exporting the model functions.

Impact: High. Why it matters: Using SQL interval subtraction lets users filter time-series telemetry by relative hours without complex frontend date math.

“Now, something that we would like to do with this project is that we want to enable the user who is accessing the web client to input a time range in which he wants to see the sensor data.”

In the video: Ebenezer Asabre, at 34:19

9. Connecting Services, Express Controllers, and Routes

Timestamp: 00:39:56 to 00:48:04 (8 min)

Speaker: Ebenezer Asabre

Asabre abstracts the database calls by creating wrapper functions in sensors.services.js and HTTP request handlers in sensors.controller.js that return status 200 JSON responses or status 500 error messages. He then maps POST, GET, and DELETE endpoints in sensors.routes.js using Express Router to expose the complete REST API.

Impact: Medium. Why it matters: Decoupling SQL queries from HTTP routing via service and controller layers keeps the Node.js codebase maintainable as endpoints grow.

“The controller will call the service and the service will call the model, which will execute the query. We use this abstraction in Node.js application.”

In the video: Ebenezer Asabre, at 42:56

10. Asabre Links MQTT Subscriptions to Socket.io Events

Timestamp: 00:50:34 to 00:59:57 (9 min)

Speaker: Ebenezer Asabre

In index.js, Asabre installs EJS, initializes the Express and HTTP server on port 3000, attaches Socket.io, and connects the backend MQTT client to the broker IP. When the server receives telemetry on home/sensors/data, it emits the parsed object to the web dashboard via Socket.io, and when the browser emits checkbox or time-search events, the server publishes MQTT commands or queries PostgreSQL.

Impact: High. Why it matters: This central hub translates browser WebSocket events into microcontroller MQTT messages and vice versa in real time.

“Whenever we get data from the web client, send it to the ESP32. And when it goes to the ESP32, it will take it and it will execute it.”

In the video: Ebenezer Asabre, at 58:41

11. Buffering 60 Sensor Samples to Save 5-Minute Averages

Timestamp: 00:59:57 to 01:04:42 (5 min)

Speaker: Ebenezer Asabre

To avoid saving every 5-second reading to PostgreSQL, Asabre writes helper functions in index.js to split the incoming comma-separated telemetry string into floats and push each reading into an in-memory array buffer. Once the buffer reaches 60 samples—representing five minutes of data—the server calculates the mean for each sensor using JavaScript's reduce method, saves the rounded record to PostgreSQL, and clears the buffer.

Impact: High. Why it matters: Downsampling 5-second telemetry into 5-minute averages cuts database write volume by 98% while retaining accurate historical trends.

“We are going to send sensor data from the client every 5 seconds. If that is the case, it means that we will have 60 samples in 5 minutes, okay?”

In the video: Ebenezer Asabre, at 1:01:52

12. Rendering Live Plotly Charts and EJS History Tables

Timestamp: 01:04:42 to 01:12:37 (8 min)

Speaker: Ebenezer Asabre

In the final section, Asabre builds graph.html using a W3.CSS template, Plotly.js, and Socket.io to render live 20-point scrolling charts for all four sensors and emit checkbox toggle states. He then creates detail.ejs to render initial database rows via server-side EJS tags and dynamically rebuild the HTML table body when users search custom time ranges over Socket.io.

Impact: Medium. Why it matters: Capping Plotly charts at 20 shifting points keeps the browser DOM responsive during continuous real-time streaming.

“So, we update it, and in order to make the graph readable, we only show 20 points. So, what we do is that if we get more values than that, we just have to shift it.”

In the video: Ebenezer Asabre, at 1:07:55

Key sources

  • Ebenezer Asabre: Graduate Student in Electrical, Electronics, and Computer Engineering at University of Massachusetts, Amherst

Who's in this

  • University of Massachusetts, Amherst
  • ESP32
  • Raspberry Pi 3 Model B
  • PostgreSQL
  • Node.js
  • Socket.io
  • Mosquitto
  • Plotly

Also mentioned

  • Arduino IDE (First mentioned at 3:10)
  • Express (First mentioned at 25:00)
  • PubSubClient (First mentioned at 9:30)
  • ESP32Servo (First mentioned at 20:01)
  • VS Code (First mentioned at 25:57)
  • EJS (First mentioned at 48:24)
  • MacBook (First mentioned at 2:22)
  • macOS (First mentioned at 21:42)
  • Linux (First mentioned at 21:50)
  • Homebrew (First mentioned at 21:57)
  • W3.CSS (First mentioned at 1:06:08)
  • GitHub (First mentioned at 2:32)
  • Windows (First mentioned at 21:53)
  • Nano (First mentioned at 23:35)
  • STM32 (First mentioned at 1:12:42)

This analysis was generated by skim (skim.plus), an AI-powered content analysis platform by Credible AI. Scores and classifications represent the platform's AI-generated assessment and should be considered alongside other sources.