Created
February 6, 2016 12:19
-
-
Save yoggy/980171c7080ca0db0061 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// test program for esp-wroom-02 & mh-z19 | |
// | |
// ESP-WROOM-02 development board | |
// https://www.switch-science.com/catalog/2500/ | |
// | |
// MH-Z19 | |
// http://www.winsen-sensor.com/products/ndir-co2-sensor/mh-z19.html | |
// | |
// License: | |
// Copyright (c) 2016 yoggy <[email protected]> | |
// Released under the MIT license | |
// http://opensource.org/licenses/mit-license.php; | |
// | |
#include <SoftwareSerial.h> // https://github.com/plerup/espsoftwareserial | |
SoftwareSerial sws = SoftwareSerial(4, 5); // RX, TX | |
byte buf[9]; | |
void setup() { | |
Serial.begin(9600); | |
sws.begin(9600); | |
} | |
void loop() { | |
int co2 = read_data_from_mh_z19(); | |
if (co2 < 0) { | |
Serial.println("read failed..."); | |
} | |
else { | |
Serial.print("co2 = "); | |
Serial.print(co2); | |
Serial.print(" ppm"); | |
} | |
delay(1000); | |
} | |
int read_data_from_mh_z19() { | |
for (int i = 0; i < 10; ++i) { | |
// send command | |
sws.write((uint8_t)0xff); | |
sws.write((uint8_t)0x01); | |
sws.write((uint8_t)0x86); | |
sws.write((uint8_t)0x00); | |
sws.write((uint8_t)0x00); | |
sws.write((uint8_t)0x00); | |
sws.write((uint8_t)0x00); | |
sws.write((uint8_t)0x00); | |
sws.write((uint8_t)0x79); | |
sws.flush(); | |
// read | |
memset(buf, 0, 9); | |
sws.readBytes(buf, 9); | |
// parse | |
if (buf[0] == 0xff && buf[1] == 0x86) { | |
int co2 = buf[2] * 256 + buf[3]; | |
Serial.println(co2); | |
return co2; | |
} | |
delay(100); | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment