// ESP32 + MQ2: publishes the analog value to the IMITECH MQTT broker once per second. // Wiring: MQ2 VCC -> 5V (VIN), GND -> GND, AOUT -> GPIO34. // The MQ2 outputs up to 5 V on AOUT; put a voltage divider (e.g. 10k + 20k) in front of the ESP32 pin. // Library: "PubSubClient" (Arduino Library Manager). #include #include #include const char* WIFI_SSID = "YOUR_WIFI"; const char* WIFI_PASS = "YOUR_PASSWORD"; const char* MQTT_HOST = "monitoringiotkit.imitech.my.id"; const int MQTT_PORT = 8883; // TLS const char* MQTT_USER = "aeronix-mq2-001"; const char* MQTT_PASS = "YOUR_MQTT_PASSWORD"; // ask the site owner const char* TOPIC = "aeronix/v1/mq2-001/telemetry"; const int MQ2_PIN = 34; WiFiClientSecure net; PubSubClient mqtt(net); void connectMqtt() { while (!mqtt.connected()) { if (!mqtt.connect("aeronix-mq2-001", MQTT_USER, MQTT_PASS)) delay(2000); } } void setup() { Serial.begin(115200); analogReadResolution(12); // values 0..4095 WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) delay(300); net.setInsecure(); // no certificate check; add the CA for a stricter setup mqtt.setServer(MQTT_HOST, MQTT_PORT); } void loop() { if (!mqtt.connected()) connectMqtt(); mqtt.loop(); long sum = 0; for (int i = 0; i < 16; i++) sum += analogRead(MQ2_PIN); // average out the noise int value = sum / 16; String body = "{\"value\":" + String(value) + "}"; bool ok = mqtt.publish(TOPIC, body.c_str()); Serial.printf("value=%d published=%d\n", value, ok); delay(1000); }