Hari ini aku deploy sensor MQ135 untuk monitor tahap kualiti udara yang berada berdekatan dengan dapur masakan.
Nampak semua berjalan dengan baik cuma ada beberapa benda yang aku mula perasan tak kena dengan module ini macam contoh dia tiba-tiba berhenti hantar data.
Tapi aku ambil inisiatif deploy sahaja dulu dan tengok balik kemudian.
Bawah ini code yang aku guna untuk sensor MQ135 terus hantar data ke MQTT server.
#include <ESP8266WiFi.h> #include <PubSubClient.h> #include "MQ135.h" #define ANALOGPIN A0 // Define Analog PIN on Arduino Board #define RZERO 206.85 // Define RZERO Calibration Value MQ135 gasSensor = MQ135(ANALOGPIN); const char* ssid = ""; const char* password = ""; const char* mqtt_server = ""; WiFiClient espClient; PubSubClient client(espClient); unsigned long lastSend; void setup() { Serial.begin(9600); float rzero = gasSensor.getRZero(); delay(3000); Serial.print("MQ135 RZERO Calibration Value : "); Serial.println(rzero); setup_wifi(); client.setServer(mqtt_server, 1883); } void setup_wifi() { delay(10); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } randomSeed(micros()); Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void sendDataCollection() { float ppm = gasSensor.getPPM(); char ppmvalue[10]; dtostrf(ppm, 6, 2, ppmvalue); delay(1000); Serial.print("CO2 ppm value : "); Serial.println(ppm); client.publish("/home/sensor/MQ135_01", ppmvalue); } void reconnect() { // Loop until we're reconnected Serial.println("In reconnect..."); while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("esp12e_O2Sensor")) { Serial.println("connected"); sendDataCollection(); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } void loop() { if ( !client.connected() ) { reconnect(); } client.loop(); if ( millis() - lastSend > 1000 ) { sendDataCollection(); lastSend = millis(); } }