forked from ricki-z/SDS011
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SDS011.cpp
76 lines (62 loc) · 1.83 KB
/
SDS011.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
// SDS011 dust sensor PM2.5 and PM10
// ---------------------
//
// By R. Zschiegner ([email protected])
// April 2016
//
// Documentation:
// - The iNovaFitness SDS011 datasheet
//
#include "SDS011.h"
// --------------------------------------------------------
// SDS011:read
// --------------------------------------------------------
SDS011::SDS011(void) {
}
int SDS011::read(float *p25, float *p10) {
String s = "";
char buffer;
int value;
int len = 0;
int pm10_serial = 0;
int pm25_serial = 0;
int checksum_is;
int checksum_ok = 0;
int position = 0;
int error = 1;
while ((sds_data->available() > 0) && (sds_data->available() >= (10-len))) {
buffer = sds_data->read();
value = int(buffer);
switch (len) {
case (0): if (value != 170) { len = -1; }; break;
case (1): if (value != 192) { len = -1; }; break;
case (2): pm25_serial = value; checksum_is = value; break;
case (3): pm25_serial += (value << 8); checksum_is += value; break;
case (4): pm10_serial = value; checksum_is += value; break;
case (5): pm10_serial += (value << 8); checksum_is += value; break;
case (6): checksum_is += value; break;
case (7): checksum_is += value; break;
case (8): if (value == (checksum_is % 256)) { checksum_ok = 1; } else { len = -1; }; break;
case (9): if (value != 171) { len = -1; }; break;
}
len++;
if (len == 10 && checksum_ok == 1) {
*p10 = pm10_serial/10;
*p25 = pm25_serial/10;
len = 0; checksum_ok = 0; pm10_serial = 0.0; pm25_serial = 0.0; checksum_is = 0;
error = 0;
}
yield();
}
return error;
}
void SDS011::begin(uint8_t pin_rx, uint8_t pin_tx) {
int error;
uint8_t c;
_pin_rx = pin_rx;
_pin_tx = pin_tx;
SoftwareSerial *softSerial = new SoftwareSerial(_pin_rx, _pin_tx);
//Initialize the 'Wire' class for I2C-bus communication.
softSerial->begin(9600);
sds_data = softSerial;
}