Skip to content

Commit

Permalink
filter noisy measurements
Browse files Browse the repository at this point in the history
  • Loading branch information
gluap committed Jul 12, 2021
1 parent 46a04a2 commit 004cc39
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/sensor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -320,8 +320,10 @@ bool HCSR04SensorManager::collectSensorResult(uint8_t sensorId) {
}
sensor->rawDistance = dist;
sensor->median->addValue(dist);
sensorValues[sensorId] =
sensor->distance = correctSensorOffset(medianMeasure(sensor, dist), sensor->offset);
uint16_t distance = medianMeasure(sensor, dist);
if (MAX_SAMPLE_DISTANCE_DEVIATION > range(sensor->distances, MEDIAN_DISTANCE_MEASURES))
sensorValues[sensorId] =
sensor->distance = correctSensorOffset(distance, sensor->offset);

log_v("Raw sensor[%d] distance read %03u / %03u (%03u, %03u, %03u) -> *%03ucm*, duration: %zu us - echo pin state: %d",
sensorId, sensor->rawDistance, dist, sensor->distances[0], sensor->distances[1],
Expand Down Expand Up @@ -472,3 +474,18 @@ uint16_t HCSR04SensorManager::median(uint16_t a, uint16_t b, uint16_t c) {
}
return c;
}


uint16_t HCSR04SensorManager::range(uint16_t values[], uint16_t size) {
uint16_t minval = values[0];
uint16_t maxval = values[0];
for (uint16_t i = 1; i<size; ++i) {
if (values[i]<minval) {
minval = values[i];
}
if (values[i] > maxval) {
maxval = values[i];
}
}
return maxval - minval;
}
2 changes: 2 additions & 0 deletions src/sensor.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ const uint32_t MICRO_SEC_TO_CM_DIVIDER = 58; // sound speed 340M/S, 2 times back


const uint16_t MEDIAN_DISTANCE_MEASURES = 3;
const uint16_t MAX_SAMPLE_DISTANCE_DEVIATION = 10;
const uint16_t MAX_NUMBER_MEASUREMENTS_PER_INTERVAL = 35; // is 1000/SENSOR_QUIET_PERIOD_AFTER_START_MICRO_SEC
extern const uint16_t MAX_SENSOR_VALUE;

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

0 comments on commit 004cc39

Please sign in to comment.