From 4811ab82390ed0e3aeacf718779f0e5d3d86338f Mon Sep 17 00:00:00 2001 From: Michael Mandl Date: Sun, 15 Oct 2017 13:11:46 +0200 Subject: [PATCH] Handle echo pulse edges in correct order. only emit a new distance value if echo pulse edges trigger in the right order. Fixes #1 --- .gitignore | 1 + source/distancethread.cpp | 12 ++++++------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index b30f005..be1f801 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ build*/ *.user +.*.swp diff --git a/source/distancethread.cpp b/source/distancethread.cpp index 308a448..2cabf73 100644 --- a/source/distancethread.cpp +++ b/source/distancethread.cpp @@ -2,7 +2,7 @@ #include volatile unsigned int timestampHigh = 0; -volatile unsigned int timestampLow = 0; +volatile unsigned int pulseLength = 0; DistanceThread::DistanceThread() { @@ -19,9 +19,10 @@ void DistanceThread::run() { timestampHigh = micros(); } - else + else if (timestampHigh != 0) { - timestampLow = micros(); + pulseLength = micros() - timestampHigh; + timestampHigh = 0; } }); @@ -32,10 +33,9 @@ void DistanceThread::run() digitalWrite(m_triggerPin, LOW); delayMicroseconds(40); - unsigned int delayUS = timestampLow - timestampHigh; - if (delayUS < 25e3) + if (pulseLength < 25e3) { - emit distanceUpdated(delayUS / 0.58); + emit distanceUpdated(pulseLength / 0.58); } delay(100);