TKHTS2
TKHTS2
PROJECT REPORT
DIGITAL SYSTEM DESIGN 2
Hanoi, 06-2024
1
Table of Contents
I. PROBLEM ANALYSIS.........................................................................................4
1. Problem Statement...............................................................................................4
2. Proposed Treatment..............................................................................................4
II. SPECIFICATIONS............................................................................................5
1. Functional Requirements......................................................................................5
2. Non-functional Requirements..............................................................................6
3. System block diagram..........................................................................................6
1. ESP8266 Module..................................................................................................7
2. BME680 Air Quality Sensor................................................................................9
IV. IMPLEMENTATION......................................................................................10
1. Experiment Setup...............................................................................................10
2. Experiment Procedure........................................................................................11
V. CONCLUSION.................................................................................................24
2
I. PROBLEM ANALYSIS
1. Problem Statement
In-home air quality problems can significantly impact health and well-being,
with sources ranging from household products and building materials to cooking,
heating, and biological contaminants. Common pollutants like VOCs, mold spores,
dust mites, and radon contribute to respiratory issues, cardiovascular effects,
headaches, fatigue, and even long-term health risks such as cancer. Poor ventilation,
high or low humidity, and temperature fluctuations can exacerbate these problems.
Environmental factors within the home, such as improper humidity levels and
inadequate ventilation, can further compound these problems. High humidity can
encourage mold growth and dust mite proliferation, while low humidity can cause dry
skin and respiratory irritation. Inadequate ventilation allows pollutants to accumulate,
significantly degrading air quality. Temperature fluctuations, if not well-regulated, can
also affect indoor air quality and overall comfort, especially for vulnerable populations
like the elderly and young children.
Therefore, the need for air quality measuring devices in homes is crucial. These
devices help in detecting and monitoring indoor pollutants, providing essential data to
protect occupants' health. By identifying sources of contamination and measuring
pollutant levels, homeowners can take proactive steps to improve ventilation, use air
purifiers, and make informed decisions about household products and materials,
ultimately ensuring a safer and healthier indoor environment for all residents.
2. Proposed Treatment
3
Temperature: Provides accurate temperature readings
Humidity: Measures relative humidity levels in the air
Pressure: Provides atmospheric pressure data
Gas: Specifically measures volatile organic compounds (VOCs) in the air,
making it particularly useful for indoor air quality monitoring
II. SPECIFICATIONS
1. Functional Requirements
Data Collection: The device should collect real-time data from the connected
sensors at regular intervals. It should retrieve and store data for all relevant
weather parameters.
Wireless Communication: The device should establish wireless connectivity,
such as Wi-Fi or Bluetooth, to transmit the weather data to a central server or
cloud plat form. It should support secure and reliable data transmission
Real-Time Monitoring: These devices provide real-time data on air quality
levels, allowing users to track fluctuations in pollutant concentrations over time.
Remote Monitoring: Users can remotely access real-time air quality data from
their smartphones, providing peace of mind even when they're away from home
or the monitoring site.
Alert Systems: Some devices are equipped with alert systems that notify users
when pollutant levels exceed predefined thresholds, enabling prompt action to
mitigate exposure.
Calibration and Accuracy: Air quality measuring devices are calibrated to
ensure accuracy and reliability in pollutant detection, making them suitable for
research, regulatory compliance, and public health monitoring purposes.
User-Friendly Interface: The system should provide a user-friendly interface,
both locally and remotely, to access weather data. The interface should be
intuitive, easy to navigate, and visually appealing.
Power Efficiency: The system should be designed to optimize power
consumption and maximize battery life. It should incorporate power-saving
techniques such as sleep modes and efficient data transmission protocols.
4
2. Non-functional Requirements
Specifications Range
Power Supply 5V
The ESP8266 microcontroller is responsible for retrieving data from the connected
sensor. Using its built-in Wi-Fi module, the ESP8266 establishes a connection to a
cloud server. The collected sensor data is then transmitted from the ESP32 to the cloud
server over the Wi-Fi network.
Once the data reaches the cloud server, it is stored and made accessible for further
processing and analysis. The smartphone app, which is connected to the same cloud
server, retrieves the stored data and presents it in a user-friendly interface. This allows
5
users to conveniently access and view the real-time air quality information and any
historical data that has been collected.
By leveraging this architecture, the ESP8266 enables seamless data transfer from
the sensors to the cloud server, providing a reliable and scalable solution for air quality
monitoring. Users can effortlessly monitor the air quality conditions and trends
through the smartphone app, enhancing their overall experience and convenience
The ESP8266 is a system on a chip (SOC) Wi-Fi microchip for Internet of Things
(IoT) applications produced by Espressif Systems. Given its low cost, small size and
adaptability with embedded devices, the ESP8266 is now used extensively across IoT
devices.
6
The ESP8266 module enables microcontrollers to connect to 2.4 GHz Wi-Fi, using
IEEE 802.11 bgn. It can be used with ESP-AT firmware to provide Wi-Fi connectivity
to external host MCUs, or it can be used as a self-sufficient MCU by running an
RTOS-based SDK. The module has a full TCP/IP stack and provides the ability for
data processing, reads and controls of GPIOs. The ESP8266 specifications is described
in Table 1
ESP8266 Description
Core 1
Bluetooth No
GPIO 16
DAC 0
ADC 1
Interfaces SPI-I2C-UART-I2S
ESP8266 has many applications when it comes to the IoT. Here are just some of
the functions the chip is used for:
7
P2P Connectivity: Create direct communication between ESPs and other
devices using IoT P2P connectivity
Web Server: Access pages written in HTML or development languages.
Figure 2. BME680
The BME680 is the first gas sensor that integrates high-linearity and high-accuracy
gas, pressure, humidity and temperature sensors. It is especially developed for mobile
applications and wearables where size and low power consumption are critical
requirements. The BME680 guarantees - depending on the specific operating mode -
optimized consumption, long-term stability and high EMC robustness. To measure air
quality for personal wellbeing the gas sensor within the BME680 can detect a broad
range of gases such as volatile organic compounds (VOC).
The module comes with a XC6206 3.3V precise voltage regulator and voltage
level translator, so you can use it with your favorite 3.3V or 5V microcontroller
without worry. The BME680 consumes less than 1mA during measurements and only
8
0.15µA during sleep mode. This low power consumption allows the implementation in
battery driven devices such as handsets, wearables or smart watches.
The BME680 pin configuration is given in Table 2
VCC Connected to 5V
SDA The Serial Data In (SDI/MOSI) pin, for data sent from your
microcontroller to the BME680.
SDO The Serial Data Out (SDO/MISO) pin, for data sent from the
BME680 to your microcontroller.
IV. IMPLEMENTATION
1. Experiment Setup
For our experiment setup, we will need the following components and materials:
9
ESP8266 module: This is the microcontroller board that will be used to
interface with the sensors and collect data.
BME680 air quality sensor: The sensor to measure specifics parameters of the
air such as temperature, humidity, pressure. Make sure they are compatible with
the ESP32 module and can provide accurate measurements in normal
conditions.
Breadboard: A breadboard will be used to create temporary connections
between the components without the need for soldering.
Jumper wires: These wires will be used to connect the ESP8266 module,
sensors, and breadboard, ensuring proper electrical connections.
2. Experiment Procedure
To begin, we first determine the pinout configuration of the ESP8266 module and
select the suitable GPIO (General Purpose Input/Output) pin to establish a connection
with the sensor. Subsequently, we utilize Fritzing, a software tool for creating visual
representations of circuits, to draw the circuit diagram. The resulting diagram would
depict the ESP8266 module and the sensor, showcasing their interconnections and
providing a visual representation of the circuit setup.
10
Following the configuration of the pinout and the creation of the circuit diagram,
the next step involves procuring the required sensors and constructing the actual circuit
to verify its functionality.
11
In Application, we do more than that, we made multiple devices that can be
added, removed and controlled easily with Graphics Users Interface, currently
supported iOS. The future works target is Android supported and Desktop app for
Windows and macOS.
12
Using MAC Addresses as Identifiers for Air Quality Sensors
In the implementation of a network of air quality sensors using ESP8266
microcontrollers, it is crucial to ensure the accurate identification and differentiation of
data originating from various sensors. This will discuss the rationale behind utilizing
MAC addresses as unique identifiers for the sensors and the structure of the database
designed to store the sensor data.
Media Access Control (MAC) addresses are globally unique identifiers assigned to
network interfaces. Each ESP8266 microcontroller is equipped with a distinct MAC
address. By leveraging these unique addresses, we can achieve the following:
1. Unique Identification: Each air quality sensor is linked to a specific ESP8266
microcontroller. The uniqueness of MAC addresses ensures that data from each
sensor can be distinctly identified.
2. Data Association: By associating sensor data with the corresponding MAC
address, we can determine which specific ESP8266 transmitted the data. This
association facilitates efficient filtering and organization of data.
3. Reliable Tracking: Using MAC addresses allows for reliable tracking and
management of multiple sensors within the network, ensuring that data integrity
is maintained.
13
Database Schema
The database schema includes the following fields for each record:
1. Timestamp
2. ID
3. MAC Address
4. Temperature
5. Humidity
6. Pressure
7. Gas resistance
8. Indoors-Air-Quality (IAQ)
Utilizing MAC addresses as unique identifiers for air quality sensors in a network
of ESP8266 microcontrollers provides a reliable method for data association and
management. The designed database schema and data management strategy ensure
efficient storage and retrieval of sensor data while maintaining memory efficiency.
This approach facilitates accurate tracking and analysis of air quality data, contributing
to the overall effectiveness of the monitoring system.
14
Figure 7. PhpMyAdmin SQL database
Server Specifications
Hosting Platform: The server is hosted on a private server, ensuring dedicated
resources and enhanced security for our application.
Control Panel: The server is managed using aaPanel, a popular Linux-based
web hosting control panel. aaPanel provides an intuitive graphical user interface
for managing various aspects of the server, including websites, databases, and
security settings.
15
Server Features
1. File Management:
o Directory Structure: The image shows the directory structure with files
related to the air quality monitoring application.
o File Types: Includes PHP scripts (data.php, get.php) and an HTML file
(index.html).
o Permissions and Ownership: Each file is marked with its respective
permissions and ownership details, ensuring proper access control.
2. PHP Execution:
o PHP Files: The data.php and get.php scripts are crucial for handling data
submissions from the sensors and fetching data from the database.
o User Profile File: The .user.ini file is used to configure PHP user
settings, enhancing security by preventing cross-site scripting (XSS)
attacks.
3. Web Interface:
o index.html: Serves as the front-end interface for accessing the air quality
data, providing users with a user-friendly way to view the collected data.
4. Database Management:
o PhpMyAdmin Integration: The server includes PhpMyAdmin for
managing the SQL database, facilitating easy administration of the
database where sensor data is stored.
5. Security:
o File Protection: The server setup includes file protection mechanisms to
safeguard against unauthorized access.
o Backups: The aaPanel interface offers options for creating backups,
ensuring data can be recovered in case of any issues.
Server Operation
Data Handling: The server receives data from multiple air quality sensors
every 2 to 4 seconds. The PHP scripts process this data, associate it with the
corresponding MAC address, and store it in the SQL database.
16
Data Retrieval: Users can retrieve the latest data through the web interface,
with the server dynamically generating responses based on the current database
contents.
Scalability: The server is configured to scale the range of stored records based
on the number of active sensors, optimizing memory usage and maintaining
performance.
The private hosting server running aaPanel Linux provides a robust and secure
environment for managing the air quality monitoring system. By leveraging the
features of aaPanel and integrating essential PHP scripts and database management
tools, the server ensures efficient data processing, storage, and retrieval, thereby
supporting the overall functionality of the air quality monitoring application.
Code explanation
ESP8266 code (Arduino IDE):
Initial setup.
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
#include <ESP8266WiFi.h>
#include "ESPAsyncWebServer.h"
17
#include <WiFiClientSecureBearSSL.h>
#include <ESP8266HTTPClient.h>
float temperature;
float humidity;
float pressure;
float gasResistance;
String IAQ;
float hum_weighting = 0.25; // so hum effect is 25% of the total air quality score
float gas_weighting = 0.75; // so gas effect is 75% of the total air quality score
AsyncWebServer server(80);
AsyncEventSource events("/events");
void getBME680Readings(){
// Tell BME680 to begin measurement.
unsigned long endTime = bme.beginReading();
if (endTime == 0) {
Serial.println(F("Failed to begin reading :("));
return;
}
if (!bme.endReading()) {
Serial.println(F("Failed to complete reading :("));
return;
}
temperature = bme.temperature;
pressure = bme.pressure / 100.0;
humidity = bme.humidity;
gasResistance = bme.gas_resistance / 1000.0;
18
//Calculate gas contribution to IAQ index
float gas_lower_limit = 5000; // Bad air quality limit
float gas_upper_limit = 50000; // Good air quality limit
if (gas_reference > gas_upper_limit) gas_reference = gas_upper_limit;
if (gas_reference < gas_lower_limit) gas_reference = gas_lower_limit;
gas_score = (0.75/(gas_upper_limit-gas_lower_limit)*gas_reference -
(gas_lower_limit*(0.75/(gas_upper_limit-gas_lower_limit))))*100;
The code above is how we collect data, analysis the data and got the IAQ
measurement based on all data we collected (temperature, pressure, humidity and gas
resistance), from that we can conclude the IAQ value (Hazardous to Good air quality).
The formular data analysis is take from open source Github code:
https://github.com/ghtomcat/co2ampel (MIT License).
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
Serial.println("\n");
} else {
Serial.print("Loi: ");
Serial.println(httpResponseCode);
}
19
http.end();
} else {
Serial.println("WiFi Disconnected");
}
}
date_default_timezone_set('Asia/Ho_Chi_Minh');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$macAddress = $_POST['macAddress'];
$temperature = $_POST['temperature'];
$humidity = $_POST['humidity'];
$pressure = $_POST['pressure'];
$gas_resistance = $_POST['gasResistance'];
$iaq = $_POST['IAQ'];
$conn->close();
?>
The script constructs an SQL query to insert the retrieved data into the readings
table. The table is assumed to have the following columns: mac_address, temperature,
humidity, pressure, gas_resistance, iaq, and reading_time.
The data.php script efficiently handles the process of receiving sensor data from
ESP8266 devices, processing it, and storing it in a MySQL database. By leveraging the
unique MAC addresses of the sensors, the script ensures accurate identification and
association of data. The use of a POST request method guarantees secure and reliable
data transmission. The script's error handling mechanisms and database connection
management contribute to the robustness and reliability of the air quality monitoring
system.
$servername = "localhost";
$username = "sql_huy34306_x2n";
$password = "e0466b55b4c14";
$dbname = "sql_huy34306_x2n";
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
21
// Check if the MAC address is provided
if (!isset($_GET['mac']) || !isValidMAC($_GET['mac'])) {
echo json_encode(array("error" => "Invalid MAC address. Please re-input."));
$conn->close();
exit();
}
$mac_address = $_GET['mac'];
if ($result_latest->num_rows > 0) {
$latest_reading = $result_latest->fetch_assoc();
echo json_encode($latest_reading);
} else {
echo json_encode(array("error" => "No data found for the specified MAC address."));
}
$conn->close();
?>
The PHP script efficiently handles the retrieval of the latest air quality sensor
data for a specified MAC address. It validates the MAC address format, manages the
database to retain only the latest 25 records, and fetches the most recent data entry.
The script ensures that the data is returned in JSON format, making it suitable for web
and mobile applications. The error handling mechanisms provide meaningful feedback
to the client in case of invalid input or missing data.
V. CONCLUSION
Both PHP code handle specific tasks related to the air quality monitoring
system.
Detailed Steps
a. Database Connection:
The script initializes connection parameters (server name, username,
password, database name).
It establishes a connection to the MySQL database using these
parameters.
If the connection fails, it terminates the script with an error message.
b. POST Request Handling:
The script checks if the incoming request method is POST.
If not, it returns an error message.
c. Data Retrieval:
The script retrieves the following data from the POST request:
MAC address
Temperature
Humidity
Pressure
Gas resistance
Indoor Air Quality (IAQ)
It also captures the current timestamp.
d. Data Insertion:
The script constructs an SQL INSERT query to add the retrieved data to
the readings table.
It executes the query to insert the data into the database.
e. Error Handling:
If the data insertion is successful, it returns a success message.
If there is an error, it returns an error message with details.
24
get.php for Fetching Sensor Data
Overview
The get.php code retrieves the latest sensor data for a specified MAC address and
manages the database to retain only the latest 25 records. The algorithm can be broken
down into the following steps:
1. Content Type Setting: Set the content type of the response to JSON.
2. Database Connection: Establish a connection to the MySQL database.
3. MAC Address Validation: Validate the provided MAC address.
4. Record Management: Ensure only the latest 25 records are retained in the
database.
5. Data Retrieval: Retrieve the latest sensor data for the specified MAC address.
6. Error Handling: Provide feedback on the success or failure of the data retrieval.
Detailed Steps
Both scripts implement robust algorithms to handle specific tasks related to the
air quality monitoring system. The first script focuses on securely inserting sensor data
into the database, while the second script ensures efficient retrieval of the latest sensor
data and manages the database to retain only the most recent records. Error handling
and validation are integral parts of both algorithms, ensuring reliability and robustness
in data processing and management.
26