Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MH-Z14 ESP8266 Arduino example
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <time.h>
const char* ssid = "co2_sensor";
const char* password = "1qazxsw2";
ESP8266WebServer server(80);
const int led = BUILTIN_LED;
int getCO2();
int pwm_co2 = 0;
void pwm_in_interrupt() {
static int t_last = 0;
int t = micros();
if (digitalRead(D5) == 0) {
pwm_co2 = (t - t_last - 2) * 4 / 1000;
}
t_last = t;
}
void setup(void) {
WiFi.mode(WIFI_AP);
pinMode(led, OUTPUT);
digitalWrite(led, 0);
Serial.begin(9600);
Serial.swap();
WiFi.softAP(ssid, password);
attachInterrupt(D5, pwm_in_interrupt, CHANGE);
// // Wait for connection
// while (WiFi.status() != WL_CONNECTED) {
// digitalWrite(led, 1);
// delay(400);
// digitalWrite(led, 0);
// delay(100);
// }
// if (MDNS.begin("esp8266-mh-z14")) {
// MDNS.addService("http", "tcp", 80);
// }
// configTime(3600 * 3, 0, "pool.ntp.org");
server.on("/", []() {
digitalWrite(led, 0);
int co2 = getCO2();
// time_t ts;
// time(&ts);
int ts = millis();
String response = String("{\"co2\":") + co2 + ", \"pwm_co2\":" + pwm_co2 + ", \"time\":" + ts + "}\n";
server.send(200, "text/json", response);
digitalWrite(led, 1);
});
server.begin();
delay(5000);
digitalWrite(led, 1);
}
void loop(void) {
server.handleClient();
}
const uint8_t cmd[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
int getCO2() {
uint8_t response[9];
Serial.write(cmd, 9);
if (Serial.readBytes(response, 9) == 9) {
int responseHigh = (int) response[2];
int responseLow = (int) response[3];
int ppm = (256 * responseHigh) + responseLow;
return ppm;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.