Indoor Air Quality Monitor with ESP32 and BME680 Sensor

In this guide, I will explain how to build an indoor air quality monitor using the ESP32 microcontroller and the BME680 sensor. We will be utilizing the power of the ESP32 to monitor various parameters of air quality, such as temperature, humidity, pressure, and gas levels. The BME680 sensor is a versatile and highly accurate sensor that combines all these capabilities into a single compact module.


Part 1: Getting started


In this blog post, I will walk you through the entire process of setting up the hardware, writing the code, and deploying the project. By the end, you will have a fully functional air quality monitor that can provide you with valuable insights into the air quality in your indoor environment. So let's get started!


Hardware Setup:


To begin with, let's gather all the necessary components for this project. Here's a list of what you'll need:


1. ESP32 Development Board: The ESP32 is a powerful microcontroller with built-in Wi-Fi and Bluetooth capabilities. It will serve as the brain of our air quality monitor.

2. BME680 Sensor: The BME680 sensor is a popular environmental sensor module that measures temperature, humidity, pressure, and gas levels.

3. Breadboard and Jumper Wires: These will help us connect the components together.

4. Micro USB Cable: This will be used to power the ESP32 development board.


Now that we have all the components, let's move on to the hardware setup:


Step 1: Connect the BME680 Sensor to the ESP32


Start by placing the ESP32 development board on the breadboard. Ensure that it is firmly seated. Next, connect the BME680 sensor to the ESP32 using jumper wires. Make the following connections:


- Connect the VCC pin of the BME680 sensor to the 3.3V pin on the ESP32.

- Connect the GND pin of the BME680 sensor to the GND pin on the ESP32.

- Connect the SDA pin of the BME680 sensor to the SDA pin on the ESP32.

- Connect the SCL pin of the BME680 sensor to the SCL pin on the ESP32.


Ensure that the connections are secure and there are no loose wires.


Step 2: Power the ESP32 Development Board


Take the micro USB cable and connect it to the USB port of the ESP32 development board. The other end of the cable can be connected to a USB power source, such as a computer or a USB wall adapter. This will provide power to the ESP32 board.


Part 2: Software Setup and Coding


Title: Building an Advanced Indoor Air Quality Monitor with ESP32 and BME680 Sensor


Software Setup:


Now that we have our hardware set up, let's move on to the software setup. In this section, we will install the necessary libraries and set up the development environment for programming the ESP32.


Step 1: Install Arduino IDE


To program the ESP32, we will be using the Arduino IDE. If you haven't installed it already, you can download it from the official Arduino website (https://www.arduino.cc/en/software) and follow the installation instructions specific to your operating system.


Step 2: Install ESP32 Board Support


Once the Arduino IDE is installed, we need to add support for the ESP32 development board. Open the Arduino IDE and navigate to "File" > "Preferences". In the "Additional Boards Manager URLs" field, enter the following URL:


https://dl.espressif.com/dl/package_esp32_index.json


Click "OK" to save the preferences. Then, navigate to "Tools" > "Board" > "Boards Manager". Search for "esp32" and click on the "esp32 by Espressif Systems" option. Click "Install" to install the ESP32 board support.


Step 3: Select ESP32 Board and Port


Connect the ESP32 development board to your computer using the micro USB cable. In the Arduino IDE, navigate to "Tools" > "Board" and select "ESP32 Dev Module" from the list of available boards.


Next, navigate to "Tools" > "Port" and select the port to which the ESP32 board is connected. The port should have "ESP32" mentioned in its name.


With the software setup complete, let's move on to writing the code for our air quality monitor.


Coding:


In this section, we will write the code that will allow the ESP32 to read data from the BME680 sensor and transmit it over a network connection. We will be using the BME680 library, which provides an easy-to-use interface for interacting with the sensor.


Step 1: Install BME680 Library

In the Arduino IDE, navigate to "Sketch" > "Include Library" > "Manage Libraries". In the Library Manager, search for "BME680" and click on the "BME680 by Bosch Sensortec" option. Click "Install" to install the BME680 library.


Step 2: Open a New Sketch

In the Arduino IDE, navigate to "File" > "New" to open a new sketch.


Step 3: Write the Code

Copy and paste the following code into the Arduino IDE:


#include <Wire.h>

#include <Adafruit_Sensor.h>

#include <Adafruit_BME680.h>


Adafruit_BME680 bme;


void setup() {

  Serial.begin(9600);

  while (!Serial);


  if (!bme.begin(0x76)) {

    Serial.println("Could not find a valid BME680 sensor, check wiring!");

    while (1);

  }


  Serial.println("Air Quality Monitor");

  Serial.println("-------------------");

}


void loop() {

  if (!bme.performReading()) {

    Serial.println("Failed to perform reading!");

    return;

  }


  float temperature = bme.temperature;

  float humidity = bme.humidity;

  float pressure = bme.pressure / 100.0;

  float gas = bme.gas_resistance / 1000.0;


  Serial.print("Temperature: ");

  Serial.print(temperature);

  Serial.println(" °C");


  Serial.print("Humidity: ");

  Serial.print(humidity);

  Serial.println(" %");


  Serial


.print("Pressure: ");

  Serial.print(pressure);

  Serial.println(" hPa");


  Serial.print("Gas Resistance: ");

  Serial.print(gas);

  Serial.println(" KOhms");


  delay(5000);

}


This code initializes the BME680 sensor and continuously reads temperature, humidity, pressure, and gas resistance values from the sensor. It then prints the values to the serial monitor. The delay of 5000 milliseconds (5 seconds) between readings ensures that the sensor is not polled too frequently.


Step 4: Upload the Code

Click on the "Upload" button in the Arduino IDE to compile and upload the code to the ESP32 board. You should see the status messages in the bottom panel of the IDE.


Once the code is successfully uploaded, open the serial monitor by navigating to "Tools" > "Serial Monitor" or by pressing "Ctrl+Shift+M". Set the baud rate to 9600 to match the value specified in the code.


Part 3: Interpreting Sensor Readings and Enhancing Functionality


Interpreting Sensor Readings:

Now that we have our code uploaded and the sensor readings displayed on the serial monitor, let's dive into interpreting the sensor readings and understanding the air quality in our indoor environment.


1. Temperature:

The temperature reading provides information about the ambient temperature in degrees Celsius. It can help us monitor temperature variations and ensure that the indoor environment is within a comfortable range.


2. Humidity:

The humidity reading indicates the amount of moisture in the air as a percentage. Higher humidity levels can contribute to discomfort and potential mold growth, while lower humidity levels can lead to dryness and respiratory problems. It's important to maintain an optimal humidity level for a healthy indoor environment.


3. Pressure:

The pressure reading gives us an idea of the atmospheric pressure in hectopascals (hPa). Monitoring pressure levels can be useful for predicting weather patterns and detecting changes in air pressure that may affect the indoor environment.


4. Gas Resistance:

The gas resistance reading measures the resistance of the gas sensor in kilohms (KOhms). It provides an indication of the air quality in terms of volatile organic compounds (VOCs) and other gases present in the environment. Higher gas resistance values may indicate poorer air quality, while lower values may indicate better air quality.


By monitoring these sensor readings, we can gain insights into the air quality in our indoor environment and take appropriate measures to maintain a healthy living or working space.


Enhancing Functionality:

While the current code provides basic functionality by displaying sensor readings on the serial monitor, we can enhance the functionality of our air quality monitor by incorporating additional features. Let's explore a few possibilities:


1. Displaying Readings on an LCD:

Instead of relying on the serial monitor, we can connect an LCD display to the ESP32 and show the sensor readings in real-time. This allows for a more convenient and user-friendly interface.


2. Adding Wi-Fi Connectivity:

By integrating Wi-Fi capabilities, we can transmit the sensor readings to a web server or a cloud platform. This enables remote monitoring and data visualization, providing access to air quality information from anywhere with an internet connection.


3. Implementing Data Logging:

To analyze air quality trends over time, we can incorporate data logging functionality. By storing the sensor readings in a file or a database, we can generate graphs and perform statistical analysis to gain deeper insights into air quality patterns.


4. Setting Thresholds and Alerts:

To ensure prompt action in case of deteriorating air quality, we can set threshold values for each parameter. If any reading exceeds the defined thresholds, the system can trigger alerts through notifications, email, or even audible alarms.


These are just a few ideas to enhance the functionality of our air quality monitor. Depending on your requirements and creativity, you can further customize and expand the capabilities of your project.


Part 4: Adding Wi-Fi Connectivity and Data Transmission


Adding Wi-Fi Connectivity:


In this section, we will enhance our air quality monitor by adding Wi-Fi connectivity to transmit sensor readings to a web server. This will enable remote monitoring and data visualization, providing a convenient way to access air quality information from anywhere with an internet connection.


Step 1: Include Required Libraries

To add Wi-Fi functionality, we need to include the necessary libraries. Add the following lines of code at the beginning of your sketch, before the setup() function:


#include <WiFi.h>

#include <HTTPClient.h>


Step 2: Set Up Wi-Fi Credentials

In the setup() function, we need to configure the Wi-Fi connection. Replace the existing setup() function with the following code:


void setup() {

  Serial.begin(9600);

  while (!Serial);


  if (!bme.begin(0x76)) {

    Serial.println("Could not find a valid BME680 sensor, check wiring!");

    while (1);

  }


  Serial.println("Air Quality Monitor");

  Serial.println("-------------------");


  // Connect to Wi-Fi network

  WiFi.begin("Your_SSID", "Your_Password");


  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);

    Serial.println("Connecting to Wi-Fi...");

  }


  Serial.println("Connected to Wi-Fi!");

  Serial.print("IP Address: ");

  Serial.println(WiFi.localIP());

}


Replace "Your_SSID" and "Your_Password" with the credentials of your Wi-Fi network. This code connects the ESP32 to the Wi-Fi network and displays the assigned IP address on the serial monitor.


Step 3: Transmit Sensor Readings to a Web Server

To transmit the sensor readings to a web server, add the following code inside the loop() function, after printing the sensor readings:


  // Create an HTTPClient object

  HTTPClient http;


  // Construct the URL for the web server

  String url = "http://your-web-server.com/air-quality-update?temperature=";

  url += temperature;

  url += "&humidity=";

  url += humidity;

  url += "&pressure=";

  url += pressure;

  url += "&gas=";

  url += gas;


  // Send the HTTP GET request

  http.begin(url);

  int httpResponseCode = http.GET();


  // Check for successful response

  if (httpResponseCode == 200) {

    Serial.println("Data transmitted successfully!");

  } else {

    Serial.print("Error in HTTP GET request. Error code: ");

    Serial.println(httpResponseCode);

  }


  // Close the connection

  http.end();


  delay(5000);


Replace "http://your-web-server.com/air-quality-update" with the URL or endpoint where you want to send the sensor readings. This code constructs the URL with the sensor readings as query parameters and sends an HTTP GET request to the web server. It then checks the response code and displays the appropriate message on the serial monitor.


Make sure to adapt the server-side code to receive the GET request and store the sensor readings in your desired format or database.


Step 4: Upload the Updated Code

Upload the updated code to the ESP32 board by clicking on the "Upload" button in the Arduino IDE.


Now, the ESP32 will connect to your Wi-Fi network and transmit the sensor readings to the specified web server at regular intervals.


Part 5: Conclusion and Further Enhancements


Conclusion:

Congratulations! You have successfully built an advanced indoor air quality monitor using the ESP32 microcontroller and the BME680 sensor. Throughout this project, we covered the hardware setup, software setup, coding, interpreting sensor readings, and enhancing the functionality of the air quality monitor. By incorporating Wi-Fi connectivity, we enabled remote monitoring and data transmission to a web server, providing access to air quality information from anywhere.


With this air quality monitor, you can now gain valuable insights into the temperature, humidity, pressure, and gas levels in your indoor environment. This information can help you make informed decisions about ventilation, air purification, and overall comfort in your living or working space.


Further Enhancements:

While we have covered a range of features and enhancements in this project, there are still plenty of opportunities for further customization and improvements. Here are a few ideas to take your air quality monitor to the next level:


1. Mobile App Integration:

Develop a mobile app that can connect to the ESP32 via Wi-Fi and display real-time sensor readings. This provides a more intuitive and user-friendly interface, allowing users to monitor air quality on their smartphones.


2. Data Visualization:

Instead of just transmitting sensor readings to a web server, create a visually appealing dashboard to display historical data and trends. Graphs, charts, and analytics can provide a more comprehensive view of air quality patterns over time.


3. Machine Learning and Predictive Analysis:

Utilize machine learning algorithms to analyze the sensor data and predict future air quality trends. This can help identify potential issues in advance and take preventive measures to maintain a healthy environment.


4. Integration with Smart Home Systems:

Integrate your air quality monitor with existing smart home systems such as Amazon Alexa or Google Home. This allows you to control ventilation systems, air purifiers, or other smart devices based on the air quality readings.


Remember, the possibilities are endless when it comes to customization and expanding the functionality of your air quality monitor. Feel free to explore additional features that align with your specific needs and interests.


I hope you enjoyed this technical blog post and found it helpful in your journey of building an advanced indoor air quality monitor. Happy tinkering!