Skip to content

Commit d56a097

Browse files
committed
Add function to average n readings
Examples currently use `refresh()` to fill the data into a `hackAIRData` struct, extract the data into separate variables to calculate the mean value and then put the data back into the struct to use the submit function. This is kinda clunky and this change aims to provide a better API for something commonly used.
1 parent 0b4aacc commit d56a097

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

src/hackair.cpp

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ void hackAIR::begin() {
4141
}
4242
}
4343

44-
void hackAIR::refresh(hackAirData &data) {
44+
void hackAIR::readData(hackAirData &data) {
4545
if (_sensorType == SENSOR_DFROBOT) {
4646
// DFRobot
4747
char index = 0;
@@ -134,6 +134,32 @@ void hackAIR::refresh(hackAirData &data) {
134134
data.error = 1;
135135
}
136136

137+
void hackAIR::readAverageData(hackAirData &data, uint8_t n) {
138+
float sum_pm25 = 0.0f;
139+
float sum_pm10 = 0.0f;
140+
uint8_t successes = 0;
141+
142+
for (uint8_t i = 0; i < n; i++) {
143+
readData(data);
144+
145+
if (data.error == 0) {
146+
sum_pm25 += data.pm25;
147+
sum_pm10 += data.pm10;
148+
149+
successes += 1;
150+
}
151+
}
152+
153+
data.pm25 = sum_pm25 / successes;
154+
data.pm10 = sum_pm10 / successes;
155+
156+
if (successes != n) {
157+
data.error = 1;
158+
} else {
159+
data.error = 0;
160+
}
161+
}
162+
137163
void hackAIR::clearData(hackAirData &data) {
138164
data.pm25 = 0;
139165
data.pm10 = 0;

src/hackair.h

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,14 @@ class hackAIR {
6565
void begin();
6666

6767
/**
68-
* Read data from the sensor and process packages. Mainly used for digital/serial
69-
* sensors.
68+
* Read data from the sensor.
7069
*/
71-
void refresh(hackAirData &data);
70+
void readData(hackAirData &data);
71+
72+
/**
73+
* Read data from the sensor n times and return the average reading.
74+
*/
75+
void readAverageData(hackAirData &data, uint8_t n);
7276

7377
/**
7478
* Empties a hackAir data structure

0 commit comments

Comments
 (0)