Implemented median for distance measurement, fixes #3

This commit is contained in:
Michael Mandl 2017-10-16 08:04:08 +02:00 committed by mandlm
parent 4811ab8239
commit 140ade4ef6
2 changed files with 47 additions and 9 deletions

View file

@ -28,16 +28,49 @@ void DistanceThread::run()
while (true) while (true)
{ {
digitalWrite(m_triggerPin, HIGH); std::vector<double> values;
delayMicroseconds(10); for (int i = 0; i < 5; ++i)
digitalWrite(m_triggerPin, LOW); {
delayMicroseconds(40); digitalWrite(m_triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(m_triggerPin, LOW);
delayMicroseconds(40);
if (pulseLength < 25e3) if (pulseLength < 25e3)
{ {
emit distanceUpdated(pulseLength / 0.58); values.push_back(pulseLength);
} }
delay(100); delay(10);
}
if (!values.empty())
{
emit distanceUpdated(median(values) / 0.58);
}
delay(100);
} }
} }
template<typename VALUE_TYPE>
double DistanceThread::median(std::vector<VALUE_TYPE> values) const
{
if (values.size() == 0)
{
return 0.0;
}
size_t centerIndex = values.size() / 2;
std::nth_element(values.begin(), values.begin() + centerIndex, values.end());
if (values.size() % 2 == 1)
{
return values[centerIndex];
}
else
{
std::nth_element(values.begin(), values.begin() + centerIndex + 1, values.end());
return (values[centerIndex] + values[centerIndex + 1]) / 2.0;
}
}

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <vector>
#include <QThread> #include <QThread>
class DistanceThread : public QThread class DistanceThread : public QThread
@ -16,6 +17,10 @@ public:
protected: protected:
void run() override; void run() override;
private:
template<typename VALUE_TYPE>
double median(std::vector<VALUE_TYPE> values) const;
signals: signals:
void distanceUpdated(double distMeters); void distanceUpdated(double distMeters);
}; };