-
Notifications
You must be signed in to change notification settings - Fork 0
/
MHZ19.cpp
766 lines (621 loc) · 19.2 KB
/
MHZ19.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
/* -------------------------------------------------
Author: Jonathan Dempsey [email protected]
Version: 1.4.3
License: LGPLv3
Library supporting MHZ19 sensors
----------------------------------------------------- */
#include "MHZ19.h"
/*#########################-Commands-##############################*/
byte Commands[13] = {
120, // 0 Recovery Reset
121, // 1 ABC Mode ON/OFF
132, // 2 Raw CO2
133, // 3 Temp float, CO2 Unlimited
134, // 4 Temp integer, CO2 limited
135, // 5 Zero Calibration
136, // 6 Span Calibration
153, // 7 Range
155, // 8 Get Range
156, // 9 Get Background CO2
160, // 10 Get Firmware Version
162, // 11 Get Last Response
163 // 12 Get Temp Calibration
};
/*#####################-Initiation Functions-#####################*/
void MHZ19::begin(Stream &serial)
{
mySerial = &serial;
/* establish connection */
stablise();
/* check if successful */
if (this->errorCode != RESULT_OK)
{
#if defined (ESP32) && (MHZ19_ERRORS)
ESP_LOGE(TAG_MHZ19, "Initial communication errorCode recieved");
#elif MHZ19_ERRORS
Serial.println("!ERROR: Initial communication errorCode recieved");
#endif
}
}
/*########################-Set Functions-##########################*/
void MHZ19::setRange(int range)
{
if (range > 65000)
{
#if defined (ESP32) && (MHZ19_ERRORS)
ESP_LOGE(TAG_MHZ19, "Invalid Range value (0 - 65000)");
#elif MHZ19_ERRORS
Serial.println("!ERROR: Invalid Range value (0 - 65000)");
#endif
return;
}
else
provisioning(RANGE, range);
}
void MHZ19::setSpan(int span)
{
if (span > 10000)
{
#if defined (ESP32) && (MHZ19_ERRORS)
ESP_LOGE(TAG_MHZ19, "Invalid Span value (0 - 10000)");
#elif MHZ19_ERRORS
Serial.println("!ERROR: Invalid Span value (0 - 10000)");
#endif
}
else
provisioning(SPANCAL);
return;
}
void MHZ19::setFilter(bool isON, bool isCleared)
{
this->storage.settings.filterMode = isON;
this->storage.settings.filterCleared = isCleared;
}
/*########################-Get Functions-##########################*/
int MHZ19::getCO2(bool isunLimited, bool force)
{
if (force == true)
{
if(isunLimited)
provisioning(TEMPUNLIM);
else
provisioning(TEMPLIM);
}
if (this->errorCode == RESULT_OK || force == false)
{
if (!this->storage.settings.filterMode)
{
unsigned int validRead = 0;
if(isunLimited)
validRead = makeInt(this->storage.responses.TEMPUNLIM[4], this->storage.responses.TEMPUNLIM[5]);
else
validRead = makeInt(this->storage.responses.TEMPLIM[2], this->storage.responses.TEMPLIM[3]);
if(validRead > 32767)
validRead = 32767; // Set to maximum to stop negative values being return due to overflow
else
return validRead;
}
else
{
/* FILTER BEGIN ----------------------------------------------------------- */
unsigned int checkVal[2];
bool trigFilter = false;
// Filter was must call the opposest unlimited/limited command to work
if(!isunLimited)
provisioning(TEMPUNLIM);
else
provisioning(TEMPLIM);
checkVal[0] = makeInt(this->storage.responses.TEMPUNLIM[4], this->storage.responses.TEMPUNLIM[5]);
checkVal[1] = makeInt(this->storage.responses.TEMPLIM[2], this->storage.responses.TEMPLIM[3]);
// Limited CO2 stays at 410ppm during reset, so comparing unlimited which instead
// shows an abormal value, reset duration can be found. Limited CO2 ppm returns to "normal"
// after reset.
if(this->storage.settings.filterCleared)
{
if(checkVal[0] > 32767 || checkVal[1] > 32767 || (((checkVal[0] - checkVal[1]) >= 10) && checkVal[1] == 410))
{
this->errorCode = RESULT_FILTER;
return 0;
}
}
else
{
if(checkVal[0] > 32767)
{
checkVal[0] = 32767;
trigFilter = true;
}
if(checkVal[1] > 32767)
{
checkVal[1] = 32767;
trigFilter = true;
}
if(((checkVal[0] - checkVal[1]) >= 10) && checkVal[1] == 410)
trigFilter = true;
if(trigFilter)
{
this->errorCode = RESULT_FILTER;
}
}
if(isunLimited)
return checkVal[0];
else
return checkVal[1];
/* FILTER END ----------------------------------------------------------- */
}
}
return 0;
}
float MHZ19::getCO2Raw(bool force)
{
if (force == true)
provisioning(RAWCO2);
if (this->errorCode == RESULT_OK || force == false)
return makeInt(this->storage.responses.RAW[2], this->storage.responses.RAW[3]);
else
return 0;
}
float MHZ19::getTransmittance(bool force)
{
if (force == true)
provisioning(RAWCO2);
if (this->errorCode == RESULT_OK || force == false)
{
float calc = (float)makeInt((this->storage.responses.RAW[2]), this->storage.responses.RAW[3]);
return (calc * 100 / 35000); // (calc * to percent / x(raw) zero)
}
else
return 0;
}
float MHZ19::getTemperature(bool isFloat, bool force)
{
if(isFloat)
{
static byte baseTemp = 0;
static bool isSet = false;
if(!isSet)
{
provisioning(TEMPLIM);
byte buff = (this->storage.responses.TEMPLIM[4] - 38);
baseTemp = buff - (byte)getTemperatureOffset(true);
isSet = true;
}
if(force)
provisioning(TEMPUNLIM);
if(this->errorCode == RESULT_OK || force == false)
{
float buff = baseTemp;
buff += getTemperatureOffset(false);
return buff;
}
}
else if(!isFloat)
{
if (force == true)
provisioning(TEMPLIM);
if (this->errorCode == RESULT_OK || force == false)
return (this->storage.responses.TEMPLIM[4] - 38);
}
return -273.15;
}
float MHZ19::getTemperatureOffset(bool force)
{
if (force == true)
provisioning(TEMPUNLIM);
if (this->errorCode == RESULT_OK || force == false)
{
/* Value appears to be for CO2 offset (useful for deriving CO2 from raw?) */
/* Adjustments and calculations are based on observations of temp behavour */
float calc = (((this->storage.responses.TEMPUNLIM[2] - 8) * 1500) + ((this->storage.responses.TEMPUNLIM[3] * 100) * 1 / 17));
calc /= 100;
return calc;
}
return -273.15;
}
int MHZ19::getRange()
{
/* check get range was recieved */
provisioning(GETRANGE);
if (this->errorCode == RESULT_OK)
/* convert MH-Z19 memory value and return */
return (int)makeInt(this->storage.responses.STAT[4], this->storage.responses.STAT[5]);
else
return 0;
}
byte MHZ19::getAccuracy(bool force)
{
if (force == true)
provisioning(TEMPLIM);
if (this->errorCode == RESULT_OK || force == false)
return this->storage.responses.TEMPLIM[5];
else
return 0;
//GetRange byte 7
}
byte MHZ19::getPWMStatus()
{
//255 156 byte 4;
return 0;
}
void MHZ19::getVersion(char rVersion[])
{
provisioning(GETFIRMWARE);
if (this->errorCode == RESULT_OK)
for (byte i = 0; i < 4; i++)
{
rVersion[i] = char(this->storage.responses.STAT[i + 2]);
}
else
memset(rVersion, 0, 4);
}
int MHZ19::getBackgroundCO2()
{
provisioning(GETCALPPM);
if (this->errorCode == RESULT_OK)
return (int)makeInt(this->storage.responses.STAT[4], this->storage.responses.STAT[5]);
else
return 0;
}
byte MHZ19::getTempAdjustment()
{
provisioning(GETEMPCAL);
/* 40 is returned here, however this library deductes -2
when using temperature function as it appears inaccurate,
*/
if (this->errorCode == RESULT_OK)
return (this->storage.responses.STAT[3]);
else
return 0;
}
byte MHZ19::getLastResponse(byte bytenum)
{
provisioning(GETLASTRESP);
if (this->errorCode == RESULT_OK)
return (this->storage.responses.STAT[bytenum]);
else
return 0;
}
/*######################-Utility Functions-########################*/
void MHZ19::stablise()
{
unsigned long timeStamp = millis();
/* construct common command (133) */
constructCommand(TEMPUNLIM);
write(this->storage.constructedCommand);
while (read(this->storage.responses.TEMPUNLIM, TEMPUNLIM) != RESULT_OK)
{
if (millis() - timeStamp >= TIMEOUT_PERIOD)
{
#if defined (ESP32) && (MHZ19_ERRORS)
ESP_LOGE(TAG_MHZ19, "Failed to verify connection(1) to sensor. Failed to stablise");
#elif MHZ19_ERRORS
Serial.println("!ERROR: Failed to verify connection(1) to sensor. Failed to stablise");
#endif
return;
}
}
/* construct & write last response command (162) */
constructCommand(GETLASTRESP);
write(this->storage.constructedCommand);
/* update timeStamp for next comms iteration */
timeStamp = millis();
while (read(this->storage.responses.STAT, GETLASTRESP) != RESULT_OK)
{
if (millis() - timeStamp >= TIMEOUT_PERIOD)
{
#if defined (ESP32) && (MHZ19_ERRORS)
ESP_LOGE(TAG_MHZ19, "Failed to verify connection(2) to sensor. Failed to stablise");
#elif MHZ19_ERRORS
Serial.println("!ERROR: Failed to verify connection(2) to sensor. Failed to stablise");
#endif
return;
}
}
/* compare CO2 response command(133) against, last response command (162)*/
for (byte i = 2; i < 8; i++)
{
if (this->storage.responses.TEMPUNLIM[i] != this->storage.responses.STAT[i])
{
#if defined (ESP32) && (MHZ19_ERRORS)
ESP_LOGE(TAG_MHZ19, "Last response was not found, call back failed. Failed to stablise");
#elif MHZ19_ERRORS
Serial.println("!ERROR: Last response was not found, call back failed. Failed to stablise");
#endif
return;
}
}
return;
}
void MHZ19::autoCalibration(bool isON, byte ABCPeriod)
{
/* If ABC is ON */
if(isON)
{
/* If a period was defined */
if (ABCPeriod)
{
/* Catch values out of range */
if(ABCPeriod >= 24)
ABCPeriod = 24;
/* Convert to bytes */
ABCPeriod *= 6.7;
}
/* If no period was defined (for safety, even though default argument is given)*/
else
ABCPeriod = 160; // Default bytes
}
/* If ABC is OFF */
else
ABCPeriod = 0x00; // Set command byte to Zero to match command format.
/* Update storage */
this->storage.settings.ABCRepeat = !isON; // Set to opposite, as repeat command is sent only when ABC is OFF.
provisioning(ABC, ABCPeriod);
}
void MHZ19::calibrateZero(int rangeCal)
{
if (rangeCal)
{
int rangevalues[11] = {
400,
1000,
1500,
2000,
3000,
4000,
5000,
6000,
7000,
8000,
10000};
byte result = 0;
for (byte i = 0; i < 11; i++)
{
if (i == 10)
{
result = (i + 8);
break;
}
else if ((rangevalues[i] + (rangevalues[i + 1])) / 2 > rangeCal)
{
result = (i + 8);
break;
}
}
provisioning(ZEROCAL, result);
}
else
provisioning(ZEROCAL);
}
void MHZ19::recoveryReset()
{
provisioning(RECOVER);
}
void MHZ19::printCommunication(bool isDec, bool isPrintComm)
{
this->storage.settings._isDec = isDec;
this->storage.settings.printcomm = isPrintComm;
}
/*######################-Inernal Functions-########################*/
void MHZ19::provisioning(Command_Type commandtype, int inData)
{
/* construct command */
constructCommand(commandtype, inData);
/* write to serial */
write(this->storage.constructedCommand);
/*return response */
handleResponse(commandtype);
/* Check if ABC_OFF needs to run */
ABCCheck();
}
void MHZ19::constructCommand(Command_Type commandtype, int inData)
{
/* values for conversions */
byte High;
byte Low;
/* Temporary holder */
byte asemblecommand[9];
/* prepare arrays */
memset(asemblecommand, 0, 9);
memset(this->storage.constructedCommand, 0, 9);
/* set address to 'any' */
asemblecommand[0] = 255; ///(0xFF) 255/FF means 'any' address (where the sensor is located)
/* set register */
asemblecommand[1] = 1; //(0x01) arbitrary byte number
/* set command */
asemblecommand[2] = Commands[commandtype]; // assign command value
switch (commandtype)
{
case RECOVER:
break;
case ABC:
if (this->storage.settings.ABCRepeat == false)
asemblecommand[3] = inData;
break;
case RAWCO2:
break;
case TEMPUNLIM:
break;
case TEMPLIM:
break;
case ZEROCAL:
if (inData)
asemblecommand[6] = inData;
break;
case SPANCAL:
makeByte(inData, &High, &Low);
asemblecommand[3] = High;
asemblecommand[4] = Low;
break;
case RANGE:
makeByte(inData, &High, &Low);
asemblecommand[6] = High;
asemblecommand[7] = Low;
break;
case GETRANGE:
break;
case GETCALPPM:
break;
case GETFIRMWARE:
break;
case GETEMPCAL:
break;
case GETLASTRESP:
break;
}
/* set checksum */
asemblecommand[8] = getCRC(asemblecommand);
/* copy bytes from asemblecommand to constructedCommand */
memcpy(this->storage.constructedCommand, asemblecommand, 9);
}
void MHZ19::write(byte toSend[])
{
/* for print communications */
if (this->storage.settings.printcomm == true)
printstream(toSend, true, this->errorCode);
/* transfer to buffer */
mySerial->write(toSend, 9);
/* send */
mySerial->flush();
}
byte MHZ19::read(byte inBytes[9], Command_Type commandnumber)
{
/* loop escape */
unsigned long timeStamp = millis();
/* prepare memory array with unsigned chars of 0 */
memset(inBytes, 0, 9);
/* prepare errorCode */
this->errorCode = RESULT_NULL;
/* wait for response, allow for defined time before exit */
while (mySerial->available() <= 0)
{
if (millis() - timeStamp >= TIMEOUT_PERIOD)
{
#if defined (ESP32) && (MHZ19_ERRORS)
ESP_LOGW(TAG_MHZ19, "Timed out waiting for response");
#elif MHZ19_ERRORS
Serial.println("!Error: Timed out waiting for response");
#endif
this->errorCode = RESULT_TIMEOUT;
return RESULT_TIMEOUT;
}
}
/* response recieved, read buffer */
mySerial->readBytes(inBytes, 9);
if (this->errorCode == RESULT_TIMEOUT)
return this->errorCode;
byte crc = getCRC(inBytes);
/* CRC error will not overide match error */
if (inBytes[8] != crc)
this->errorCode = RESULT_CRC;
/* construct error code */
if (inBytes[0] != this->storage.constructedCommand[0] || inBytes[1] != this->storage.constructedCommand[2])
this->errorCode = RESULT_MATCH;
/* if error has been assigned */
if (this->errorCode == RESULT_NULL)
this->errorCode = RESULT_OK;
/* print results */
if (this->storage.settings.printcomm == true)
printstream(inBytes, false, this->errorCode);
return this->errorCode;
}
void MHZ19::handleResponse(Command_Type commandtype)
{
if (this->storage.constructedCommand[2] == Commands[2]) // compare commands byte
read(this->storage.responses.RAW, commandtype); // returns error number, passes back response and inputs command
else if (this->storage.constructedCommand[2] == Commands[3])
read(this->storage.responses.TEMPUNLIM, commandtype);
else if (this->storage.constructedCommand[2] == Commands[4])
read(this->storage.responses.TEMPLIM, commandtype);
else
read(this->storage.responses.STAT, commandtype);
}
void MHZ19::printstream(byte inBytes[9], bool isSent, byte pserrorCode)
{
if (pserrorCode != RESULT_OK && isSent == false)
{
Serial.print("Recieved >> ");
if (this->storage.settings._isDec)
{
Serial.print("DEC: ");
for (uint8_t i = 0; i < 9; i++)
{
Serial.print(inBytes[i]);
Serial.print(" ");
}
}
else
{
for (uint8_t i = 0; i < 9; i++)
{
Serial.print("0x");
if (inBytes[i] < 16)
Serial.print("0");
Serial.print(inBytes[i], HEX);
Serial.print(" ");
}
}
Serial.print("ERROR Code: ");
Serial.println(pserrorCode);
}
else
{
isSent ? Serial.print("Sent << ") : Serial.print("Recieved >> ");
if (this->storage.settings._isDec)
{
Serial.print("DEC: ");
for (uint8_t i = 0; i < 9; i++)
{
Serial.print(inBytes[i]);
Serial.print(" ");
}
}
else
{
for (uint8_t i = 0; i < 9; i++)
{
Serial.print("0x");
if (inBytes[i] < 16)
Serial.print("0");
Serial.print(inBytes[i], HEX);
Serial.print(" ");
}
}
Serial.println(" ");
}
}
byte MHZ19::getCRC(byte inBytes[])
{
/* as shown in datasheet */
byte x = 0, CRC = 0;
for (x = 1; x < 8; x++)
{
CRC += inBytes[x];
}
CRC = 255 - CRC;
CRC++;
return CRC;
}
void MHZ19::ABCCheck()
{
/* check timer interval if dynamic hours have passed and if ABC_OFF was set to true */
if (((millis() - ABCRepeatTimer) >= 4.32e7) && (this->storage.settings.ABCRepeat == true))
{
/* update timer inerval */
ABCRepeatTimer = millis();
/* construct ABC_OFF command */
constructCommand(ABC);
/* write to serial */
write(this->storage.constructedCommand);
}
}
void MHZ19::makeByte(int inInt, byte *high, byte *low)
{
*high = (byte)(inInt / 256);
*low = (byte)(inInt % 256);
return;
}
unsigned int MHZ19::makeInt(byte high, byte low)
{
unsigned int calc = ((unsigned int)high * 256) + (unsigned int)low;
return calc;
}