Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@igrr
Created December 25, 2015 11:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save igrr/deb7ba7755fcffe0b96e to your computer and use it in GitHub Desktop.
Save igrr/deb7ba7755fcffe0b96e to your computer and use it in GitHub Desktop.
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;
}
@petefreid
Copy link

I'm having problems reading the UART register. It looked like the values were correct once but then switched to this:
Address 0 FF
Address 1 86
Address 2 7
Address 3 D0
Address 4 43
Address 5 0
Address 6 0
Address 7 0
Address 8 60
I sent the device this request
byte addArray[] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment