-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSerialCom.h
114 lines (84 loc) · 2.88 KB
/
SerialCom.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
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
#pragma once
#include <SoftwareSerial.h>
#include "Types.h"
namespace SerialCom {
constexpr static const uint8_t PIN_UART_RX = 4; // D2 on Wemos D1 Mini
constexpr static const uint8_t PIN_UART_TX = 13; // UNUSED
SoftwareSerial sensorSerial(PIN_UART_RX, PIN_UART_TX);
uint8_t serialRxBuf[255];
uint8_t rxBufIdx = 0;
void setup() {
sensorSerial.begin(9600);
}
void clearRxBuf() {
// Clear everything for the next message
memset(serialRxBuf, 0, sizeof(serialRxBuf));
rxBufIdx = 0;
}
void parseState(particleSensorState_t& state) {
/**
* MSB DF 3 DF 4 LSB
* uint16_t = xxxxxxxx xxxxxxxx
*/
const uint16_t pm25 = (serialRxBuf[5] << 8) | serialRxBuf[6];
Serial.printf("Received PM 2.5 reading: %d\n", pm25);
state.measurements[state.measurementIdx] = pm25;
state.measurementIdx = (state.measurementIdx + 1) % 5;
if (state.measurementIdx == 0) {
float avgPM25 = 0.0f;
for (uint8_t i = 0; i < 5; ++i) {
avgPM25 += state.measurements[i] / 5.0f;
}
state.avgPM25 = avgPM25;
state.valid = true;
Serial.printf("New Avg PM25: %d\n", state.avgPM25);
}
clearRxBuf();
}
bool isValidHeader() {
bool headerValid = serialRxBuf[0] == 0x16 && serialRxBuf[1] == 0x11 && serialRxBuf[2] == 0x0B;
if (!headerValid) {
Serial.println("Received message with invalid header.");
}
return headerValid;
}
bool isValidChecksum() {
uint8_t checksum = 0;
for (uint8_t i = 0; i < 20; i++) {
checksum += serialRxBuf[i];
}
if (checksum != 0) {
Serial.printf("Received message with invalid checksum. Expected: 0. Actual: %d\n", checksum);
}
return checksum == 0;
}
void handleUart(particleSensorState_t& state) {
if (!sensorSerial.available()) {
return;
}
Serial.print("Receiving:");
while (sensorSerial.available()) {
serialRxBuf[rxBufIdx++] = sensorSerial.read();
Serial.print(".");
// Without this delay, receiving data breaks for reasons that are beyond me
delay(15);
if (rxBufIdx >= 64) {
clearRxBuf();
}
}
Serial.println("Done.");
if (isValidHeader() && isValidChecksum()) {
parseState(state);
Serial.printf(
"Current measurements: %d, %d, %d, %d, %d\n",
state.measurements[0],
state.measurements[1],
state.measurements[2],
state.measurements[3],
state.measurements[4]
);
} else {
clearRxBuf();
}
}
} // namespace SerialCom