-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmhz19Component.h
75 lines (66 loc) · 2.26 KB
/
mhz19Component.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "./scheduler.h"
#include "./MHZ19.h"
#include "AltSoftSerial.h"
#include <SoftwareSerial.h>
#define MHZ19_WARMUP_TIME 180000
#define MHZ19_READ_INTERVAL 5100 // 5000 by docs
#define MHZ19_CALIBRATION_POINT_PERIOD 4*60*1000L
#define MHZ19_CALIBRATION_POINTS 5// approx 20 min
#define MHZ19_LOW_LEVEL 400
class Mhz19Component {
public:
struct Args {
uint16_t* outPpmValue;
uint8_t pinRx;
uint8_t pinTx;
Scheduler* timer;
};
Mhz19Component(Args args): serial(args.pinRx, args.pinTx, false), mhz19() {
this->args = args;
args.timer->schedule(MHZ19_READ_INTERVAL, true, &this->update, this);
}
private:
Args args;
bool initialized;
MHZ19 mhz19;
AltSoftSerial serial;
uint16_t calibrationPoints[MHZ19_CALIBRATION_POINTS];
uint8_t calibrationPointsIdx;
uint32_t calibrationPointTime;
bool update() {
if(!this->initialized) {
this->serial.begin(9600);
this->mhz19.begin(this->serial);
this->mhz19.autoCalibration();
this->initialized = true;
// fill calibration array
for(uint8_t i = 0; i < MHZ19_CALIBRATION_POINTS; i ++) {
this->calibrationPoints[i] = MHZ19_LOW_LEVEL;
}
this->calibrationPointsIdx = 0;
}
int val = this->mhz19.getCO2();
if(this->mhz19.errorCode == RESULT_FILTER) {
return;
}
*(this->args.outPpmValue) = val;
// autolcalibrate low level
if(millis() - this->calibrationPointTime > MHZ19_CALIBRATION_POINT_PERIOD){
this->calibrationPointTime = millis();
this->calibrationPoints[this->calibrationPointsIdx] = val;
this->calibrationPointsIdx = (this->calibrationPointsIdx + 1) % MHZ19_CALIBRATION_POINTS;
bool allCalValsLower = true;
for(uint8_t i = 0; i < MHZ19_CALIBRATION_POINTS; i ++) {
allCalValsLower = allCalValsLower && this->calibrationPoints[i] < MHZ19_LOW_LEVEL;
}
if(allCalValsLower) {
Serial.println("mhz19 calibrate");
this->mhz19.calibrate();
this->mhz19.autoCalibration();
for(uint8_t i = 0; i < MHZ19_CALIBRATION_POINTS; i ++) {
this->calibrationPoints[i] = MHZ19_LOW_LEVEL;
}
}
}
}
};