// The MQ-135's analog output (AO) const int AIR_PIN = A0; // The three LEDs' pins const int GREEN_LED = 10; const int YELLOW_LED = 11; const int RED_LED = 12; // The heater's warm-up time (ms) const unsigned long WARM_UP = 30000; // This far above the clean-air value // yellow lights, this far red (0-1023) const int FAIR_RISE = 60; const int POOR_RISE = 150; // Going down it must fall this far below // a threshold: the LEDs do not flicker // at the edge const int MARGIN = 15; // Time between readings (ms) const unsigned long MEASURE_EVERY = 1000; int baseline = 0; // 0 good, 1 fair, 2 poor int level = 0; unsigned long lastMeasure = 0; // The average of 10 readings: less jitter int readAir() { long total = 0; for (int i = 0; i < 10; i++) { total += analogRead(AIR_PIN); delay(10); } return total / 10; } void showLevel() { digitalWrite(GREEN_LED, level == 0 ? HIGH : LOW); digitalWrite(YELLOW_LED, level == 1 ? HIGH : LOW); digitalWrite(RED_LED, level == 2 ? HIGH : LOW); } void setup() { pinMode(GREEN_LED, OUTPUT); pinMode(YELLOW_LED, OUTPUT); pinMode(RED_LED, OUTPUT); Serial.begin(9600); // Yellow blinks while it warms up Serial.println("Sensor warming up, wait 30 s..."); unsigned long start = millis(); while (millis() - start < WARM_UP) { digitalWrite(YELLOW_LED, (millis() / 500) % 2 ? HIGH : LOW); } // Clean air: the average of 10 readings long total = 0; for (int i = 0; i < 10; i++) { total += readAir(); delay(100); } baseline = total / 10; Serial.print("Clean-air value: "); Serial.println(baseline); // Almost 0: the sensor has no power if (baseline < 10) { Serial.println("Cannot read the sensor, check the wires."); while (true) { digitalWrite(RED_LED, (millis() / 250) % 2 ? HIGH : LOW); } } showLevel(); Serial.println("Measuring."); } void loop() { if (millis() - lastMeasure < MEASURE_EVERY) return; lastMeasure = millis(); int air = readAir(); // If the air gets even cleaner, the // clean-air value comes down too if (air < baseline) baseline = air; int rise = air - baseline; // Going up, the threshold itself; going // down, MARGIN below it int newLevel = 0; if (rise >= FAIR_RISE - (level >= 1 ? MARGIN : 0)) newLevel = 1; if (rise >= POOR_RISE - (level >= 2 ? MARGIN : 0)) newLevel = 2; Serial.print("Air: "); Serial.print(air); Serial.print(" | Rise: "); Serial.print(rise); if (newLevel == 0) Serial.println(" | Good"); if (newLevel == 1) Serial.println(" | Fair"); if (newLevel == 2) Serial.println(" | Poor, open a window!"); if (newLevel != level) { level = newLevel; showLevel(); } }