Skip to content

Commit 004cc39

Browse files
committed
filter noisy measurements
1 parent 46a04a2 commit 004cc39

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/sensor.cpp

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,10 @@ bool HCSR04SensorManager::collectSensorResult(uint8_t sensorId) {
320320
}
321321
sensor->rawDistance = dist;
322322
sensor->median->addValue(dist);
323-
sensorValues[sensorId] =
324-
sensor->distance = correctSensorOffset(medianMeasure(sensor, dist), sensor->offset);
323+
uint16_t distance = medianMeasure(sensor, dist);
324+
if (MAX_SAMPLE_DISTANCE_DEVIATION > range(sensor->distances, MEDIAN_DISTANCE_MEASURES))
325+
sensorValues[sensorId] =
326+
sensor->distance = correctSensorOffset(distance, sensor->offset);
325327

326328
log_v("Raw sensor[%d] distance read %03u / %03u (%03u, %03u, %03u) -> *%03ucm*, duration: %zu us - echo pin state: %d",
327329
sensorId, sensor->rawDistance, dist, sensor->distances[0], sensor->distances[1],
@@ -472,3 +474,18 @@ uint16_t HCSR04SensorManager::median(uint16_t a, uint16_t b, uint16_t c) {
472474
}
473475
return c;
474476
}
477+
478+
479+
uint16_t HCSR04SensorManager::range(uint16_t values[], uint16_t size) {
480+
uint16_t minval = values[0];
481+
uint16_t maxval = values[0];
482+
for (uint16_t i = 1; i<size; ++i) {
483+
if (values[i]<minval) {
484+
minval = values[i];
485+
}
486+
if (values[i] > maxval) {
487+
maxval = values[i];
488+
}
489+
}
490+
return maxval - minval;
491+
}

src/sensor.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ const uint32_t MICRO_SEC_TO_CM_DIVIDER = 58; // sound speed 340M/S, 2 times back
5353

5454

5555
const uint16_t MEDIAN_DISTANCE_MEASURES = 3;
56+
const uint16_t MAX_SAMPLE_DISTANCE_DEVIATION = 10;
5657
const uint16_t MAX_NUMBER_MEASUREMENTS_PER_INTERVAL = 35; // is 1000/SENSOR_QUIET_PERIOD_AFTER_START_MICRO_SEC
5758
extern const uint16_t MAX_SENSOR_VALUE;
5859

@@ -132,6 +133,7 @@ class HCSR04SensorManager {
132133
static uint32_t microsBetween(uint32_t a, uint32_t b);
133134
static uint32_t microsSince(uint32_t a);
134135
static uint16_t millisSince(uint16_t milliseconds);
136+
static uint16_t range(uint16_t values[], uint16_t size);
135137
static void updateStatistics(HCSR04SensorInfo * const sensor);
136138
uint16_t startReadingMilliseconds = 0;
137139
uint8_t primarySensor = 1;

0 commit comments

Comments
 (0)