MH-Z-CO2-Sensors/MHZ.cpp
2018-06-23 14:32:55 +02:00

104 lines
2.2 KiB
C++

/* MHZ library
By Tobias Schürg
*/
#include "MHZ.h"
MHZ:: MHZ(uint8_t rxpin, uint8_t txpin, uint8_t pwmpin, uint8_t type)
: co2Serial(rxpin, txpin)
{
_rxpin = rxpin;
_txpin = txpin;
_pwmpin = pwmpin;
_type = type;
co2Serial.begin(9600);
}
int MHZ::readCO2UART() {
Serial.println("-- read CO2 uart ---");
byte cmd[9] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};
byte response[9]; // for answer
Serial.println("Sending CO2 request...");
co2Serial.write(cmd, 9); //request PPM CO2
// clear the buffer
memset(response, 0, 9);
int i = 0;
while (co2Serial.available() == 0) {
// Serial.print("Waiting for response ");
// Serial.print(i);
// Serial.println(" s");
delay(1000);
i++;
}
if (co2Serial.available() > 0) {
co2Serial.readBytes(response, 9);
}
// print out the response in hexa
for (int i = 0; i < 9; i++) {
Serial.print(String(response[i], HEX));
Serial.print(" ");
}
Serial.println("");
// checksum
byte check = getCheckSum(response);
if (response[8] != check) {
Serial.println("Checksum not OK!");
Serial.print("Received: ");
Serial.println(response[8]);
Serial.print("Should be: ");
Serial.println(check);
}
// ppm
int ppm_uart = 256 * (int)response[2] + response[3];
Serial.print("PPM UART: ");
Serial.println(ppm_uart);
// temp
byte temp = response[4] - 40;
Serial.print("Temperature? ");
Serial.println(temp);
// status
byte status = response[5];
Serial.print("Status? ");
Serial.println(status);
if (status == 0x40) {
Serial.println("Status OK");
}
return ppm_uart;
}
byte MHZ::getCheckSum(byte *packet) {
Serial.println("-- get checksum ---");
byte i;
unsigned char checksum = 0;
for (i = 1; i < 8; i++) {
checksum += packet[i];
}
checksum = 0xff - checksum;
checksum += 1;
return checksum;
}
int MHZ::readCO2PWM() {
Serial.println("-- read CO2 pwm ---");
unsigned long th, tl, ppm_pwm = 0;
do {
Serial.print(".");
th = pulseIn(_pwmpin, HIGH, 1004000) / 1000;
tl = 1004 - th;
ppm_pwm = 5000 * (th - 2) / (th + tl - 4);
} while (th == 0);
Serial.print("PPM PWM: ");
Serial.println(ppm_pwm);
return ppm_pwm;
}