AI-Assisted Air Quality Monitoring - DFRobot Firebeetle ESP32
Using a DFRobot Firebeetle ESP32 to monitor and make predictions about air quality in an environment.
Created By: Kutluhan Aktar
Description
Due to the ever-growing industrialization, forest degradation, and pollution, the delicate balance of ambient gases shifted. Thus, hazardous air pollutants impinge on the human respiratory system detrimentally, in addition to engendering climate change and poisoning wildlife. Even though governments realized that it was incumbent on them to act in order to prevent destructive air contaminants from pervading the ecosystem, we are too far away from obviating human-made air pollutants during the following decades. Therefore, it is still crucial to detect air pollutants to inform people with prescient warnings.
Since some air pollutants can react with each other and spread very rapidly, precedence must be given to detecting highly reactive gases (air contaminants), such as ozone (O3) and nitrogen compounds (NOx, NOy). Thus, in this project, I decided to focus on ozone (O3) and nitrogen dioxide (NO2) concentrations, which denote dangerous air pollution.
In ambient air, nitrogen oxides can occur from diverse combinations of oxygen and nitrogen. The higher combustion temperatures cause more nitric oxide reactions. In ambient conditions, nitric oxide is rapidly oxidized in air to form nitrogen dioxide by available oxidants, for instance, oxygen, ozone, and VOCs (volatile organic compounds). Hence, nitrogen dioxide (NO2) is widely known as a primary air pollutant (contaminant). Since road traffic is considered the principal outdoor source of nitrogen dioxide[^1], densely populated areas are most susceptible to its detrimental effects. Nitrogen dioxide causes a range of harmful effects on the respiratory system, for example, increased inflammation of the airways, reduced lung function, increased asthma attacks, and cardiovascular harm[^2].
Tropospheric, or ground-level ozone (O3), is formed by chemical reactions between oxides of nitrogen (NOx) and volatile organic compounds (VOCs). This chemical reaction is triggered by sunlight between the mentioned air pollutants emitted by cars, power plants, industrial boilers, refineries, and chemical plants[^3]. Depending on the level of exposure, ground-level ozone (O3) can have various effects on the respiratory system, for instance, coughing, sore throat, airway inflammation, increased frequency of asthma attacks, and increased lung infection risk. Some of these detrimental effects have been found even in healthy people, but symptoms can be more severe in people with lung diseases such as asthma[^4].
Since nitrogen dioxide (NO2), ozone (O3), and other photochemical oxidant reactions and transmission rates are inextricably related to air flow, heat, and ambient humidity, I decided to collect the following data parameters to create a meticulous data set:
Nitrogen dioxide concentration (PPM)
Ozone concentration (PPB)
Temperature (°C)
Humidity (%)
Wind speed
After perusing recent research papers on ambient air pollution, I noticed there are very few appliances focusing on collecting air quality data, detecting air pollution levels with machine learning, and providing surveillance footage for further examination. Therefore, I decided to build a budget-friendly and easy-to-use air station to forecast air pollution levels with machine learning and inform the user of the model detection results with surveillance footage consecutively, in the hope of forfending the plight of hazardous gases.
To predict air pollution levels, I needed to collect precise ambient hazardous gas concentrations in order to train my neural network model with notable validity. Therefore, I decided to utilize DFRobot electrochemical gas sensors. To obtain the additional weather data, I employed an anemometer kit and a DHT22 sensor. Since FireBeetle ESP32 is a compact and powerful IoT-purposed development board providing numerous features with its budget-friendly media (camera) board, I decided to use FireBeetle ESP32 in combination with its media board so as to run my neural network model and inform the user of the model detection results with surveillance footage. Due to the memory allocation issues, I connected all sensors to Arduino Mega to collect and transmit air quality data to FireBeetle ESP32 via serial communication. Also, I connected three control buttons to Arduino Mega to send commands to FireBeetle ESP32 via serial communication.
Since the FireBeetle media board supports reading and writing information from/to files on an SD card, I stored the collected air quality data in separate CSV files on the SD card, named according to the selected air pollution class, to create a pre-formatted data set. In this regard, I was able to save and process data records via FireBeetle ESP32 without requiring any additional procedures.
After completing my data set, I built my artificial neural network model (ANN) with Edge Impulse to make predictions on air pollution levels (classes). Since Edge Impulse is nearly compatible with all microcontrollers and development boards, I had not encountered any issues while uploading and running my model on FireBeetle ESP32. As labels, I utilized the empirically assigned air pollution levels in accordance with the Air Quality Index (AQI) estimations provided by IQAir:
Clean
Risky
Unhealthy
After training and testing my neural network model, I deployed and uploaded the model on FireBeetle ESP32 as an Arduino library. Therefore, the air station is capable of detecting air pollution levels by running the model independently without any additional procedures or latency.
Since I focused on building a full-fledged AIoT air station predicting air pollution and informing the user of the model detection results with surveillance footage, I decided to develop a web application from scratch to obtain the detection results with surveillance footage from FireBeetle ESP32 via HTTP POST requests, save the received information to a MySQL database table, and display the stored air quality data with model detection results in descending order simultaneously.
Due to the fact that the FireBeetle media board can only generate raw image data, this complementing web application executes a Python script to convert the obtained raw image data to a JPG file automatically before saving it to the server as surveillance footage. After saving the converted image successfully, the web application shows the most recently obtained surveillance footage consecutively and allows the user to inspect previous surveillance footage in descending order.
Lastly, to make the device as robust and compact as possible while operating outdoors, I designed a metallic air station case with a sliding front cover and a mountable camera holder (3D printable) for the OV7725 camera connected to the FireBeetle media board.
So, this is my project in a nutshell 😃
In the following steps, you can find more detailed information on coding, capturing surveillance footage, building a neural network model with Edge Impulse, running the model on FireBeetle ESP32, and developing a full-fledged web application to obtain the model detection results with surveillance footage from FireBeetle ESP32 via HTTP POST requests.
Step 1: Designing and printing a metallic air station case
Since I focused on building a budget-friendly and accessible air station that collects air quality data and runs a neural network model to inform the user of air pollution via a PHP web application, I decided to design a sturdy and compact metallic case allowing the user to access the SD card after logging data, place the air quality sensors, and adjust the OV7725 camera effortlessly. To avoid overexposure to dust and prevent loose wire connections, I added a sliding front cover with a handle to the case. Then, I designed a separate camera holder mountable to the left side of the case at four different angles. Also, I decided to inscribe air pollution indicators on the sliding front cover to highlight the imminent pollution risk.
Since I needed to attach an anemometer to the case to collect wind speed data, I decided to design a semi-convex structure for the case. This unique shape also serves as a wind deflector that protects the air quality sensors from potential wind damage.
I designed the metallic air station case, its sliding front cover, and the mountable camera holder in Autodesk Fusion 360. You can download their STL files below.
Then, I sliced all 3D models (STL files) in Ultimaker Cura.
Since I wanted to create a solid metallic structure for the air station case with the sliding front cover and apply a unique alloy combination complementing the metallic theme, I utilized these PLA filaments:
eSilk Copper
eSilk Bronze
Finally, I printed all parts (models) with my Creality Sermoon V1 3D Printer and Creality CR-200B 3D Printer in combination with the Creality Sonic Pad. You can find more detailed information regarding the Sonic Pad in Step 1.1.
If you are a maker or hobbyist planning to print your 3D models to create more complex and detailed projects, I highly recommend the Sermoon V1. Since the Sermoon V1 is fully-enclosed, you can print high-resolution 3D models with PLA and ABS filaments. Also, it has a smart filament runout sensor and the resume printing option for power failures.
Furthermore, the Sermoon V1 provides a flexible metal magnetic suction platform on the heated bed. So, you can remove your prints without any struggle. Also, you can feed and remove filaments automatically (one-touch) due to its unique sprite extruder (hot end) design supporting dual-gear feeding. Most importantly, you can level the bed automatically due to its user-friendly and assisted bed leveling function.
Step 1.1: Improving print quality and speed with the Creality Sonic Pad
Creality Sonic Pad is a beginner-friendly device to control almost any FDM 3D printer on the market with the Klipper firmware. Since the Sonic Pad uses precision-oriented algorithms, it provides remarkable results with higher printing speeds. The built-in input shaper function mitigates oscillation during high-speed printing and smooths ringing to maintain high model quality. Also, it supports G-code model preview.
Step 1.2: Assembling the case and making connections & adjustments
Due to the Arduino library incompatibilities and the memory allocation issues, I decided to connect the electrochemical NO2 sensor, the electrochemical ozone sensor, the anemometer kit, and the DHT22 sensor to Arduino Mega so as to collect the required air quality data. Then, I utilized Arduino Mega to transmit the collected air quality data to FireBeetle ESP32 via serial communication.
Since Arduino Mega operates at 5V and FireBeetle ESP32 requires 3.3V logic level voltage, they cannot be connected with each other directly. Therefore, I utilized a bi-directional logic level converter to shift the voltage for the connections between FireBeetle ESP32 and Arduino Mega.
To display the collected information and notifications, I utilized an SH1106 OLED screen. To assign air pollution levels empirically while saving the collected data to individual CSV files on the SD card, I used the built-in MicroSD card module on the media board and added three control buttons.
After printing all parts (models), I fastened all components except the OV7725 camera to their corresponding slots on the metallic air station case via a hot glue gun. I also utilized the anemometer's screw kit to attach it more tightly to its connection points on the top of the metallic case.
I placed the OV7725 camera in the mountable camera holder and attached the camera holder to the metallic case via its snap-fit joints.
Then, I placed the sliding front cover via the dents on the metallic case.
As mentioned earlier, the mountable camera holder can be utilized to adjust the OV7725 camera at four different angles via the snap-fit joints.
Step 2: Developing a web application displaying real-time database updates in PHP, JavaScript, CSS, and MySQL
To provide an exceptional user experience for this AIoT air station, I developed a full-fledged web application from scratch in PHP, HTML, JavaScript, CSS, and MySQL. This web application obtains the collected air quality data, the detected air pollution level (class) by the neural network model, and the captured surveillance footage from FireBeetle ESP32 via an HTTP POST request. After saving the received information to the MySQL database table for further inspection, the web application converts the received raw image data to a JPG file via a Python script. Then, the web application updates itself automatically to show the latest received information and surveillance footage. Also, the application displays all stored air quality data with model detection results in descending order and allows the user to inspect previous surveillance footage.
As shown below, the web application consists of three folders and seven code files:
/assets
-- background.jpg
-- class.php
-- icon.png
-- index.css
-- index.js
/env_notifications
-- /images
-- bmp_converter.py
index.php
show_records.php
update_data.php
📁 class.php
In the class.php file, I created a class named _main to bundle the following functions under a specific structure.
⭐ Define the _main class and its functions.
⭐ In the insert_new_data function, insert the given air quality data to the MySQL database table.
⭐ In the get_data_records function, retrieve all stored air quality data from the database table in descending order and return all data parameters as separate lists.
⭐ Define the required MariaDB database connection settings for LattePanda 3 Delta 864.
📁 update_data.php
⭐ Include the class.php file.
⭐ Define the air object of the _main class with its required parameters.
⭐ Get the current date & time and create the surveillance footage file name.
⭐ If FireBeetle ESP32 sends the collected air quality data parameters with the model detection result, save the received information to the given MySQL database table.
⭐ If FireBeetle ESP32 transfers raw image data as surveillance footage via an HTTP POST request to update the server, save the received raw image data as a TXT file to the env_notifications folder.
⭐ Convert the recently saved raw image data (TXT file) to a JPG file by executing a Python script via the terminal through the web application — bmp_converter.py.
You can get more information regarding converting raw image data in the following step.
⭐ After generating the JPG file from the raw image data, remove the converted TXT file from the server.
📁 show_records.php
⭐ Include the class.php file.
⭐ Define the air object of the _main class with its required parameters.
⭐ Obtain all saved air quality information in the database table as different lists for each data parameter and create HTML table rows by utilizing these arrays.
⭐ Get the name of the latest surveillance footage from the database table.
⭐ Then, create a JSON object from the recently generated HTML table rows and the elicited surveillance footage file name.
⭐ Finally, return the recently created JSON object.
📁 index.php
⭐ Create the web application interface, including the HTML table for displaying the stored air quality information with the model detection results in the MySQL database table and image frames for the latest and selected surveillance footage.
You can inspect and download the index.php file below.
📁 index.js (jQuery and AJAX)
⭐ Display the selected surveillance footage (image) on the web application interface via the HTML buttons added to each data record retrieved from the MySQL database table.
⭐ Every 5 seconds, make an HTTP GET request to the show_records.php file.
⭐ Then, decode the retrieved JSON object to obtain the HTML table rows generated from the database table rows and the latest surveillance footage file name.
⭐ Assign the elicited information to the corresponding HTML elements on the web application interface to inform the user automatically.
Step 2.1: Converting the raw images transferred by FireBeetle ESP32 via POST requests to JPG files
Since the FireBeetle media board can only generate raw image data due to its built-in OV7725 camera, I needed to convert the generated raw image data to readable image files so as to display them on the web application interface as surveillance footage. Since FireBeetle ESP32 cannot convert the generated raw image data due to memory allocation issues, I decided to convert the captured raw image data to a JPG file via the web application.
Even though PHP can handle converting raw image data to different image file formats, converting images in PHP causes bad request issues since the web application receives raw image data from FireBeetle ESP32 via HTTP POST requests. Hence, I decided to utilize Python to create JPG files from raw image data since Python provides built-in modules for image conversion in seconds.
By employing the terminal on LattePanda 3 Delta, the web application executes the bmp_converter.py file directly to convert images.
📁 bmp_converter.py
⭐ Include the required modules.
⭐ Obtain all raw images transferred by FireBeetle ESP32 and saved as TXT files under the env_notifications folder.
Since the web application requires to access the absolute paths via the terminal to execute the Python script in order to convert images, provide the env_notifications folder's exact location.
⭐ Then, convert each retrieved TXT file (raw image) to a JPG file via the frombuffer function.
⭐ Finally, save the generated JPG files to the images folder.
Step 2.2: Setting and running the web application on LattePanda 3 Delta 864
LattePanda 3 Delta is a pocket-sized hackable computer that provides ultra performance with the Intel 11th-generation Celeron N5105 processor.
Plausibly, LattePanda 3 Delta can run the XAMPP application. So, it is effortless to create a server with a MariaDB database on LattePanda 3 Delta.
Step 2.3: Tracking real-time model detection results and displaying surveillance footage captured by FireBeetle ESP32
After setting the web application on LattePanda 3 Delta 864:
🎈⚠️📲 The web application (update_data.php) saves the information transferred by FireBeetle ESP32 via an HTTP POST request with URL query parameters to the given MySQL database table.
/update_data.php?no2=0.15&o3=25&temperature=25.20&humidity=65.50&wind_speed=3&model_result=Clean
🎈⚠️📲 When FireBeetle ESP32 transmits raw image data via the HTTP POST request, the web application converts the received raw image data to a JPG file by executing the bmp_converter.py file via the terminal.
python "C:\Users\kutlu\New E\xampp\htdocs\weather_station_data_center\env_notifications\bmp_converter.py"
🎈⚠️📲 On the web application interface (index.php), the application displays the concurrent list of data records saved in the database table as an HTML table, including HTML buttons for each data record to select the pertaining surveillance footage.
🎈⚠️📲 The web application updates its interface every 5 seconds automatically via the jQuery script to display the latest received air quality data with the model detection result and surveillance footage.
🎈⚠️📲 Until the user selects a surveillance image (footage), the web application shows the default surveillance icon in the latter image frame.
🎈⚠️📲 When the user selects a surveillance image via the assigned HTML buttons, the web application shows the selected image on the screen for further inspection.
🎈⚠️📲 For each air pollution level (class), the web application changes the row color in the HTML table to clarify and emphasize the model detection results:
Clean ➜ Green
Risky ➜ Midnight Green
Unhealthy ➜ Red
🎈⚠️📲 When the user hovers the cursor over the image frames, the web application highlights the selected frame.
Step 3: Setting up FireBeetle ESP32 on Arduino IDE
Before proceeding with the following steps, I needed to set up FireBeetle ESP32 on the Arduino IDE and install the required libraries for this project.
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
Step 3.1: Displaying images on the SH1106 OLED screen
To display images (black and white) on the SH1106 OLED screen successfully, I needed to create monochromatic bitmaps from PNG or JPG files and convert those bitmaps to data arrays.
Step 4: Collecting air quality data and communicating with FireBeetle ESP32 via serial communication w/ Arduino Mega
After setting up FireBeetle ESP32 and installing the required libraries, I programmed Arduino Mega to collect air quality data and transmit the collected data to FireBeetle ESP32 via serial communication. As explained in the previous steps, I encountered Arduino library incompatibilities and memory allocation issues when I connected the sensors directly to FireBeetle ESP32.
Nitrogen dioxide concentration (PPM)
Ozone concentration (PPB)
Temperature (°C)
Humidity (%)
Wind speed
Since I needed to assign air pollution levels (classes) empirically as labels for each data record while collecting air quality data to create a valid data set for my neural network model, I utilized three control buttons connected to Arduino Mega so as to choose among classes and transfer data records via serial communication. After selecting an air pollution level (class) by pressing a control button, Arduino Mega sends the selected class and the recently collected data to FireBeetle ESP32.
Control Button (A) ➡ Clean
Control Button (B) ➡ Risky
Control Button (C) ➡ Unhealthy
You can download the AIoT_weather_station_sensor_readings.ino file to try and inspect the code for collecting air quality data and transferring the collected data via serial communication.
⭐ Include the required libraries.
⭐ Define the collect number (1-100) for the electrochemical ozone sensor.
⭐ If necessary, modify the I2C address of the ozone sensor by utilizing its configurable dial switch.
⭐ Define the ozone sensor object.
⭐ If necessary, modify the I2C address of the electrochemical NO2 sensor by utilizing its configurable dial switch.
⭐ Define the NO2 sensor object.
⭐ Define the SH1106 OLED display (128x64) settings.
⭐ Define monochrome graphics.
⭐ Define the air pollution level (class) names and color codes.
⭐ Define the DHT22 temperature and humidity sensor settings and the DHT object.
⭐ Define the anemometer kit's voltage signal pin (yellow).
⭐ Initialize the hardware serial port (Serial1) to communicate with FireBeetle ESP32.
⭐ Initialize the SH1106 OLED display.
⭐ In the err_msg function, show the error message on the SH1106 OLED screen.
⭐ Check the electrochemical ozone sensor connection status and set its data-obtaining mode (active or passive).
⭐ Check the electrochemical NO2 sensor connection status and set its data-obtaining mode (active or passive).
⭐ Activate the temperature compensation feature of the NO2 sensor.
⭐ Initialize the DHT22 sensor.
⭐ If the sensors are working accurately, turn the RGB LED to blue.
⭐ Wait until electrochemical gas sensors heat (warm-up) for 3 minutes.
⭐ In the collect_air_quality_data function:
⭐ Collect the nitrogen dioxide (NO2) concentration.
⭐ Collect the ozone (O3) concentration.
⭐ Get the temperature and humidity measurements generated by the DHT22 sensor.
⭐ Calculate the wind speed (level) [1 - 30] according to the output voltage generated by the anemometer kit.
⭐ Combine all collected data items to create a data record.
⭐ In the home_screen function, display the collected air quality data on the SH1106 OLED screen.
⭐ In the data_screen function, display the given class icon on the SH1106 OLED screen and turn the RGB LED to the given class' color code.
⭐ If one of the control buttons (A, B, or C) is pressed, add the selected air pollution level to the recently generated data record and send it to FireBeetle ESP32 via serial communication. Then, notify the user according to the selected class.
⭐ In the run_screen function, inform the user when the collected data items are transferred to FireBeetle ESP32 via serial communication.
⭐ Every minute, transmit the collected air quality data parameters to FireBeetle ESP32 via serial communication in order to run the neural network model with the latest collected data. Then, turn the RGB LED to magenta.
Step 4.1: Logging the transmitted air quality data in a CSV file on the SD card w/ FireBeetle ESP32
After uploading and running the code for collecting air quality data and transferring the collected data to FireBeetle ESP32 via serial communication:
🎈⚠️📲 If the electrochemical gas sensors work accurately, the air station turns the RGB LED to blue and waits until the electrochemical gas sensors heat (warm-up) for 3 minutes.
🎈⚠️📲 The air station generates a data record from the recently collected air quality data and shows the collected data parameters on the SH1106 OLED screen to inform the user.
Nitrogen dioxide concentration (PPM)
Ozone concentration (PPB)
Temperature (°C)
Humidity (%)
Wind speed
🎈⚠️📲 If the control button (A) is pressed, Arduino Mega adds Clean as the selected air pollution level to the recently generated data record, transfers the modified data record to FireBeetle ESP32 via serial communication, and turns the RGB LED to green.
🎈⚠️📲 Then, it shows the unique monochrome icon of the selected air pollution level (class) on the SH1106 OLED screen.
🎈⚠️📲 If the control button (B) is pressed, Arduino Mega adds Risky as the selected air pollution level to the recently generated data record, transfers the modified data record to FireBeetle ESP32 via serial communication, and turns the RGB LED to yellow.
🎈⚠️📲 Then, it shows the unique monochrome icon of the selected air pollution level (class) on the SH1106 OLED screen.
🎈⚠️📲 If the control button (C) is pressed, Arduino Mega adds Unhealthy as the selected air pollution level to the recently generated data record, transfers the modified data record to FireBeetle ESP32 via serial communication, and turns the RGB LED to red.
🎈⚠️📲 Then, it shows the unique monochrome icon of the selected air pollution level (class) on the SH1106 OLED screen.
🎈⚠️📲 When FireBeetle ESP32 receives a data record, it creates a new CSV file under the samples folder on the SD card and combines the given air pollution level and the sample number as the file name. Then, FireBeetle ESP32 appends the received air quality data items with the given header to the created CSV file.
🎈⚠️📲 Also, FireBeetle ESP32 increments the sample number of the received air pollution level (class) by 1 to generate unique CSV files (samples).
You can get more detailed information on creating separate CSV files as samples in Step 6.
🎈⚠️📲 Every minute, Arduino Mega transmits the recently collected air quality data parameters to FireBeetle ESP32 via serial communication in order to obtain accurate prediction results after running an inference with the neural network model.
You can get more detailed information on running an inference with the neural network model in Step 7.
🎈⚠️📲 If Arduino Mega throws an error while operating, the air station shows the error message on the SH1106 OLED screen and prints the error details on the serial monitor.
🎈⚠️📲 Also, the air station prints notifications and sensor measurements on the serial monitor for debugging.
After collecting air quality data for nearly 2 months and creating separate CSV files for each data record on the SD card, I elicited my data set with eminent validity and veracity.
You can get more detailed information regarding assigning air pollution levels depending on the Air Quality Index (AQI) estimations provided by IQAir in Step 5.
Step 5: Building a neural network model with Edge Impulse
Before collecting and storing the air quality data, I checked IQAir for the AQI estimation of my region. Then, I derived an air pollution class (level) from the AQI estimation provided by IQAir in order to assign a label empirically to my samples (data records).
Clean
Risky
Unhealthy
When I completed logging the collected data and assigning labels, I started to work on my artificial neural network model (ANN) to detect ambient air pollution levels so as to inform people with prescient warnings before air pollutants engender harmful effects on the respiratory system.
Since Edge Impulse supports almost every microcontroller and development board due to its model deployment options, I decided to utilize Edge Impulse to build my artificial neural network model. Also, Edge Impulse makes scaling embedded ML applications easier and faster for edge devices such as FireBeetle ESP32.
As of now, Edge Impulse supports CSV files to upload samples in different data structures thanks to its CSV Wizard. So, Edge Impulse lets the user upload all data records in a single file even if the data type is not time series. But, I usually needed to follow the steps below to format my data set saved in a single CSV file so as to train my model accurately:
Data Scaling (Normalizing)
Data Preprocessing
However, as explained in the previous steps, I employed FireBeetle ESP32 to save each data record to a separate CSV file on the SD card to create appropriately formatted samples (CSV files) for Edge Impulse. Therefore, I did not need to preprocess my data set before uploading samples.
Plausibly, Edge Impulse allows building predictive models optimized in size and accuracy automatically and deploying the trained model as an Arduino library. Therefore, after collecting my samples, I was able to build an accurate neural network model to predict air pollution levels and run it on FireBeetle ESP32 effortlessly.
Step 5.1: Preprocessing and scaling the data set to create formatted samples for Edge Impulse
As long as the CSV file includes a header defining data fields, Edge Impulse can distinguish data records as individual samples in different data structures thanks to its CSV Wizard while adding existing data to an Edge Impulse project. Therefore, there is no need for preprocessing single CSV file data sets even if the data type is not time series.
Since Edge Impulse can infer the uploaded sample's label from its file name, I employed FireBeetle ESP32 to create a new CSV file for each data record and name the generated files by combining the given air pollution level and the sample number incremented by 1 for each class (label) automatically.
Clean.training.sample_1.csv
Clean.training.sample_2.csv
Risky.training.sample_1.csv
Risky.training.sample_2.csv
Unhealthy.training.sample_1.csv
Unhealthy.training.sample_2.csv
After collecting air quality data and generating separate CSV files for nearly 2 months, I obtained my appropriately formatted samples on the SD card.
Step 5.2: Uploading formatted samples to Edge Impulse
After generating training and testing samples successfully, I uploaded them to my project on Edge Impulse.
Step 5.3: Training the model on air pollution levels
After uploading my training and testing samples successfully, I designed an impulse and trained it on air pollution levels (classes).
An impulse is a custom neural network model in Edge Impulse. I created my impulse by employing the Raw Data processing block and the Classification learning block.
The Raw Data processing block generate windows from data samples without any specific signal processing.
The Classification learning block represents a Keras neural network model. Also, it lets the user change the model settings, architecture, and layers.
According to my experiments with my neural network model, I modified the neural network settings and layers to build a neural network model with high accuracy and validity:
📌 Neural network settings:
Number of training cycles ➡ 50
Learning rate ➡ 0.005
Validation set size ➡ 15
📌 Extra layers:
Dense layer (20 neurons)
Dense layer (10 neurons)
After generating features and training my model with training samples, Edge Impulse evaluated the precision score (accuracy) as 95.7%.
The precision score (accuracy) is approximately 96% due to the modest volume and variety of training samples since I only collected ambient air quality data near my home. In technical terms, the model trains on limited validation samples to cover various regions. Therefore, I highly recommend retraining the model with local air quality data before running inferences in a different region.
Step 5.4: Evaluating the model accuracy and deploying the model
After building and training my neural network model, I tested its accuracy and validity by utilizing testing samples.
The evaluated accuracy of the model is 97.78%.
After validating my neural network model, I deployed it as a fully optimized and customizable Arduino library.
Step 6: Setting up the Edge Impulse model on FireBeetle ESP32
After building, training, and deploying my model as an Arduino library on Edge Impulse, I needed to upload the generated Arduino library on FireBeetle ESP32 to run the model directly so as to create an easy-to-use and capable air station operating with minimal latency, memory usage, and power consumption.
Since Edge Impulse optimizes and formats signal processing, configuration, and learning blocks into a single package while deploying models as Arduino libraries, I was able to import my model effortlessly to run inferences.
After importing my model successfully to the Arduino IDE, I programmed FireBeetle ESP32 to run inferences to detect air pollution levels and capture surveillance footage for further examination every 5 minutes. If manual testing is required, FireBeetle ESP32 can also run inference and capture surveillance footage when the built-in button on the FireBeetle media board is pressed.
User Button (Built-in) ➡ Run Inference
Also, I employed FireBeetle ESP32 to transmit the collected air quality data, the model detection result, and the captured surveillance footage (raw image data) to the web application via an HTTP POST request after running inferences successfully.
You can download the AIoT_weather_station_run_model.ino file to try and inspect the code for running Edge Impulse neural network models and transferring data to a web application via FireBeetle ESP32.
⭐ Include the required libraries.
⭐ Define the required parameters to run an inference with the Edge Impulse model.
⭐ Define the features array (buffer) to classify one frame of data.
⭐ Define the threshold value (0.60) for the model outputs (predictions).
⭐ Define the air pollution level (class) names:
Clean
Risky
Unhealthy
⭐ Define the Wi-Fi network and the web application settings hosted by LattePanda 3 Delta 864.
⭐ Define the FireBeetle media board pin out to modify the official esp_camera library for the built-in OV7725 camera.
⭐ Define the camera (image) buffer array.
⭐ Create a struct including all air quality data items as its elements.
⭐ Disable the brownout detector to avoid system reset errors.
⭐ Initialize the hardware serial port (UART2) with redefined pins to communicate with Arduino Mega.
⭐ Initiate the built-in SD card module on the FireBeetle media board.
⭐ Define the pin configuration settings of the built-in OV7725 camera on the media board.
⭐ Define the pixel format and the frame size settings.
FRAMESIZE_QVGA (320x240)
⭐ Since FireBeetle ESP32 does not have SPI memory (PSRAM), disable PSRAM allocation to avoid connection errors.
⭐ Initiate the built-in OV7725 camera on the media board.
⭐ Initialize the Wi-Fi module.
⭐ Attempt to connect to the given Wi-Fi network.
⭐ Obtain the data packet and commands transferred by Arduino Mega via serial communication.
⭐ In the save_data_to_CSV function:
⭐ Create a new CSV file on the SD card with the given file name.
⭐ Append the header and the given data items to the generated CSV file.
⭐ If Arduino Mega sends the Save command with the recently collected air quality data and the selected air pollution level:
⭐ Glean information as substrings from the transferred data packet by utilizing the ampersand (&) as the delimiter.
⭐ Increment the sample number of the given level (class) by 1 to create unique samples (CSV files).
⭐ Create a new CSV file under the samples folder on the SD card and combine the given air pollution level and the sample number as the file name. Then, append the received air quality data items with the given header to the generated CSV file.
⭐ If Arduino Mega sends the Data command with the recently collected air quality data items:
⭐ Glean information as substrings from the transferred data packet by utilizing the comma (,) as the delimiter.
⭐ Convert the received data items from strings to their corresponding data types and copy them to the struct as its elements.
⭐ Finally, clear the transferred data packet.
⭐ In the run_inference_to_make_predictions function:
⭐ Scale (normalize) the collected data depending on the given model and copy the scaled data items to the features array (buffer).
⭐ If required, multiply the scaled data items while copying them to the features array (buffer).
⭐ Display the progress of copying data to the features buffer on the serial monitor.
⭐ If the features buffer is full, create a signal object from the features buffer (frame).
⭐ Then, run the classifier.
⭐ Print the inference timings on the serial monitor.
⭐ Obtain the prediction (detection) result for each given label and print them on the serial monitor.
⭐ The detection result greater than the given threshold (0.60) represents the most accurate label (air pollution level) predicted by the model.
⭐ Print the detected anomalies on the serial monitor, if any.
⭐ Finally, clear the features buffer (frame).
⭐ In the take_picture function:
⭐ Release the image buffer to avoid FireBeetle ESP32 from throwing memory allocation errors while capturing pictures sequentially.
⭐ Capture a picture with the built-in OV7725 camera on the FireBeetle media board and save it to the image buffer.
⭐ In the make_a_post_request function:
⭐ Connect to the web application named weather_station_data_center.
⭐ Create the query string and add the latest received air quality data items with the model detection result to the string as URL query (GET) parameters.
⭐ Define the boundary parameter named EnvNotification so as to send the captured raw image data as a TXT file to the web application.
⭐ Get the total content length.
⭐ Set the Connection HTTP header as Keep-Alive.
⭐ Make an HTTP POST request with the created query string to the web application in order to transfer the captured raw image data as a TXT file.
⭐ Release the image buffer.
⭐ Every 5 minutes or when the built-in button on the media board is pressed:
⭐ Start running an inference with the Edge Impulse model to make predictions on the air pollution levels (classes).
⭐ If the Edge Impulse model predicts an air quality level (class) successfully:
⭐ Create the request string consisting of the latest received air quality data items and the detected air pollution class.
⭐ Capture a picture with the built-in OV7725 camera on the media board.
⭐ Send the air quality data items, the model detection result, and the recently captured raw image as a TXT file to the web application via an HTTP POST request with URL query parameters.
⭐ Clear the predicted label (class).
⭐ Update the model timer.
Step 7: Running the model on FireBeetle ESP32 to forecast air pollution levels and transferring the model results w/ surveillance footage via POST requests
My Edge Impulse neural network model predicts possibilities of labels (air pollution classes) for the given features buffer as an array of 3 numbers. They represent the model's "confidence" that the given features buffer corresponds to each of the three different air pollution levels (classes) [0 - 2], as shown in Step 5:
0 — Clean
1 — Risky
2 — Unhealthy
After executing the AIoT_weather_station_run_model.ino file on FireBeetle ESP32:
🎈⚠️📲 When FireBeetle ESP32 receives the latest collected air quality data parameters from Arduino Mega via serial communication, it stores them to run an inference with accurate data items.
🎈⚠️📲 After Arduino Mega sends the air quality data parameters via serial communication successfully, the air station turns the RGB LED to magenta.
🎈⚠️📲 Every 5 minutes, the air station runs an inference with the Edge Impulse neural network model by applying the stored air quality data parameters to predict the air pollution level and captures surveillance footage with the OV7725 camera.
🎈⚠️📲 Then, it transfers the stored air quality data parameters, the model detection result, and the captured surveillance footage (raw image data) as a TXT file to the web application via an HTTP POST request with URL query parameters.
🎈⚠️📲 If manual testing is required, the air station can also perform the mentioned sequence when the built-in button on the FireBeetle media board is pressed.
🎈⚠️📲 Also, the air station prints notifications and model detection results on the serial monitor for debugging.
As far as my experiments go, the air station detects air pollution levels precisely, captures real-time surveillance footage, and communicates with the web application faultlessly :)
Videos and Conclusion
Further Discussions
By applying neural network models trained on air quality data in detecting air pollution levels, we can achieve to:
🎈⚠️📲 prevent human-made air pollutants from harming the respiratory system,
🎈⚠️📲 reduce the risk of increased asthma attacks and cardiovascular harm,
🎈⚠️📲 protect people with lung diseases from severe symptoms of air pollution,
🎈⚠️📲 provide prescient warnings regarding a surge in photochemical oxidant reactions and transmission rates.
References
[^1] Jarvis DJ, Adamkiewicz G, Heroux ME, et al, Nitrogen dioxide, WHO Guidelines for Indoor Air Quality: Selected Pollutants, Geneva: World Health Organization, 2010. 5, https://www.ncbi.nlm.nih.gov/books/NBK138707/
[^2] Nitrogen Dioxide, The American Lung Association, https://www.lung.org/clean-air/outdoors/what-makes-air-unhealthy/nitrogen-dioxide
[^3] Ground-level Ozone Basics, United States Environmental Protection Agency (EPA), https://www.epa.gov/ground-level-ozone-pollution/ground-level-ozone-basics
[^4] Health Effects of Ozone Pollution, United States Environmental Protection Agency (EPA), https://www.epa.gov/ground-level-ozone-pollution/health-effects-ozone-pollution
Last updated