Smart Air Quality Monitor + AI-Powered Ventilation Advisor

Smart Air Quality Monitor + AI-Powered Ventilation Advisor

(C++ Program Integrated with Sensors on Raspberry Pi)


Introduction

In today’s fast-paced urban environments, indoor air quality has become a significant factor in maintaining human health, focus, and productivity. Whether in homes, classrooms, offices, or factories, stale or polluted indoor air can contribute to fatigue, irritation, and long-term health problems.

This project demonstrates a powerful, affordable solution: a Smart Air Quality Monitor + AI-Powered Ventilation Advisor developed in C++ and running on a Raspberry Pi. It integrates real sensors for CO₂, PM2.5, humidity, and temperature — and uses artificial intelligence to give actionable ventilation recommendations.


Project Goals

  • - Use actual sensors to check air quality (CO₂, PM2. 5, humidity, temperature)

  • - Show the information on the screen instantly.

  • Log readings to a MySQL database

  • Analyze data using an AI module to recommend ventilation actions

  • Keep the code modular and Raspberry Pi compatible


Hardware Used

  • Raspberry Pi 3 or 4

  • PMS5003 – PM2.5 Sensor

  • MH-Z19 – CO₂ Sensor

  • DHT22 – Temperature & Humidity Sensor

  • MCP3008 – ADC (for analog sensors if needed)

  • Breadboard, wires, resistors

  • Relay Module (for fan control – optional)


Software Stack

  • C++17

  • pigpio or wiringPi for GPIO handling

  • MySQL server & C++ connector library

  • CMake for building

  • g++ compiler


High-Level Architecture

[ Sensors ] --> [ SensorReader Module ]  
                 |  
                 v  
          [ AI Advisor Module ]  
                 |  
                 v  
          [ Decision Display + Logging ]  
                 |  
                 v  
        [ MySQL Database for Historical Data ]

Module 1: Reading Real Sensor Data (SensorReader)

SensorReader.h

#ifndef SENSOR_READER_H
#define SENSOR_READER_H

struct AirData {
    float pm25;
    float co2;
    float temperature;
    float humidity;
};

class SensorReader {
public:
    SensorReader();
    AirData readSensors();
};

#endif // SENSOR_READER_H

SensorReader.cpp (Mock Simulation for Development)

#include "SensorReader.h"
#include <cstdlib>
#include <ctime>

SensorReader::SensorReader() {
    srand(time(0));
}

AirData SensorReader::readSensors() {
    AirData data;
    data.pm25 = 50 + (rand() % 100);         // Simulate PM2.5: 50–150 Β΅g/m³
    data.co2 = 400 + (rand() % 1200);        // Simulate CO₂: 400–1600 ppm
    data.temperature = 20 + (rand() % 10);   // 20–30 °C
    data.humidity = 40 + (rand() % 30);      // 40%–70%
    return data;
}

Module 2: Logging Data to MySQL (DataLogger)

DataLogger.h

#ifndef DATA_LOGGER_H
#define DATA_LOGGER_H

#include "SensorReader.h"

class DataLogger {
public:
    DataLogger();
    void logToDatabase(const AirData &data);
};

#endif // DATA_LOGGER_H

DataLogger.cpp

#include "DataLogger.h"
#include <mysql/mysql.h>
#include <iostream>

DataLogger::DataLogger() {
    // constructor could initialize database connection if needed
}

void DataLogger::logToDatabase(const AirData &data) {
    MYSQL* conn = mysql_init(NULL);
    mysql_real_connect(conn, "localhost", "username", "password",
                       "air_quality_db", 0, NULL, 0);

    std::string query = "INSERT INTO air_readings (pm25, co2, temperature, humidity) VALUES (" +
        std::to_string(data.pm25) + "," +
        std::to_string(data.co2) + "," +
        std::to_string(data.temperature) + "," +
        std::to_string(data.humidity) + ")";

    if (mysql_query(conn, query.c_str())) {
        std::cerr << "Error inserting into MySQL: " << mysql_error(conn) << std::endl;.
    }

    mysql_close(conn);
}

MySQL Table Schema

CREATE DATABASE air_quality_db;

USE air_quality_db;

CREATE TABLE air_readings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    pm25 FLOAT,
    co2 FLOAT,
    temperature FLOAT,
    humidity FLOAT,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Module 3: AI-Powered Ventilation Advisor (AIAdvisor)

Since the sensor readers are already created and integrated into SensorReader.cpp, focus can now shift to the AI-powered ventilation advisor.

This module is responsible for:

  1. Analyzing sensor data in real-time

  2. Recommending whether to open windows, turn on fans, or use an air purifier

  3. Logging decisions for analyzing patterns

AIAdvisor.h

#ifndef AI_ADVISOR_H
#define AI_ADVISOR_H

#include "SensorReader.h"
#include <string>

class AIAdvisor {
public:
    std::string advise(const AirData &data);
};

#endif

AIAdvisor.cpp

#include "AIAdvisor.h"
#include <sstream>

std::string AIAdvisor::advise(const AirData &data) {
    std::ostringstream advice;

    if (data.co2 > 1000 || data.pm25 > 75) {
        advice << "Turn on air purifier.";
    } else if (data.humidity > 70) {
        advice << "High humidity detected. Use dehumidifier or fan.";
    } else {
        advice << "Air quality is good. No action needed.";
    }

    return advice.str();
}

Main Application (main.cpp)

Updated main.cpp with all modules integrated

#include <iostream>
#include <thread>
#include <chrono>
#include "SensorReader.h"
#include "DataLogger.h"
#include "AIAdvisor.h"

int main() {
    SensorReader reader;
    DataLogger logger;
    AIAdvisor advisor;

    while (true) {
        AirData data = reader.readSensors();

        std::cout << "\n--- Sensor Readings ---\n";
        std::cout << "Temperature: " << data.temperature << " °C\n";
        std::cout << "Humidity: " << data.humidity << " %\n";
        std::cout << "PM2.5: " << data.pm25 << " Β΅g/m³\n";
        std::cout << "CO₂: " << data.co2 << " ppm\n";

        std::string advice = advisor.advise(data);
        std::cout << "AI Advice: " << advice << "\n";

        logger.logToDatabase(data);
        std::cout << "Data logged to MySQL.\n";

        std::this_thread::sleep_for(std::chrono::seconds(5));
    }

    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(SmartAirMonitor)

set(CMAKE_CXX_STANDARD 17)

find_package(MySQL REQUIRED)
include_directories(${MYSQL_INCLUDE_DIRS})

add_executable(SmartAirMonitor
    main.cpp
    SensorReader.cpp
    DataLogger.cpp
    AIAdvisor.cpp
)

target_link_libraries(SmartAirMonitor ${MYSQL_LIBRARIES})

How to Compile and Run

sudo apt install libmysqlclient-dev
g++ main.cpp SensorReader.cpp DataLogger.cpp AIAdvisor.cpp -o air_monitor -lmysqlclient -lpthread
./air_monitor

Sample Output

--- Sensor Readings ---
Temperature: 25 °C
Humidity: 62 %
PM2.5: 83 Β΅g/m³
CO₂: 1023 ppm
AI Advice: Turn on air purifier.
Data logged to MySQL.

Real-World Use Case Ideas

  • Smart Classroom Air Monitor with alerts for teacher

  • Factory or Lab where air quality must remain within thresholds

  • Smart Homes that automatically control ventilation

  • Office space efficiency tracking using historical air patterns


Conclusion

This project bridges sensor engineering, embedded programming, and AI logic — all in C++ on a Raspberry Pi. It demonstrates how intelligent decisions can be made using environmental data, giving users control and insight into their indoor air environment.

Future upgrades can include:

  • Real-time dashboard with graphs

  • Alert system (email/SMS)

  • Auto-control of windows/fans based on advice

  • Integration with mobile apps

A perfect blend of IoT, AI, and C++ — practical, smart, and extensible.