test
Fork of HCSR04 by
Diff: HCSR04.h
- Revision:
- 6:cf3e4e307d15
- Parent:
- 5:a667b621f625
--- a/HCSR04.h Mon Dec 07 09:57:48 2015 +0000 +++ b/HCSR04.h Sat Dec 10 08:26:18 2016 +0000 @@ -9,15 +9,24 @@ * #include "HCSR04.h" * * Serial pc(USBTX, USBRX); + * Timer timer; * * int main() { * HCSR04 sensor(p5, p7); * sensor.setRanges(10, 110); * pc.printf("Min. range = %g cm\n\rMax. range = %g cm\n\r", * sensor.getMinRange(), sensor.getMaxRange()); - * while(1) { + * while(true) { + * timer.reset(); + * timer.start(); + * sensor.startMeasurement(); + * while(!sensor.isNewDataReady()) { + * // wait for new data + * // waiting time depends on the distance + * } * pc.printf("Distance: %5.1f mm\r", sensor.getDistance_mm()); - * wait_ms(500); + * timer.stop(); + * wait_ms(500 - timer.read_ms()); // time the loop * } * } * @endcode @@ -32,12 +41,17 @@ */ HCSR04(PinName echoPin, PinName triggerPin); - /** Calculates the distance in cm, with the calculation time of approximatelly 23.7 ms. + /** Start the measurement. Measurement time depends on the distance. + * Maximum measurement time is limited to 25 ms (400 cm). + */ + void startMeasurement(); + + /** Returns the distance in cm. Requires previous call of startMeasurement(). * @returns distance of the measuring object in cm. */ float getDistance_cm(); - /** Calculates the distance in mm, with the calculation time of approximatelly 23.7 ms. + /** Returns the distance in mm. Requires previous call of startMeasurement(). * @returns distance of the measuring object in mm. */ float getDistance_mm(); @@ -58,6 +72,11 @@ */ float getMaxRange(); + /** Checks if the new data is ready. + * @returns true if new data is ready, false otherwise. + */ + bool isNewDataReady(); + private: InterruptIn echo; // echo pin @@ -66,6 +85,8 @@ float distance; // store the distance in cm float minDistance; // minimum measurable distance float maxDistance; // maximum measurable distance + Timeout triggerTimeout, echoTimeout; + bool newDataReady, timerStarted; /** Start the timer. */ void startTimer(); @@ -76,8 +97,7 @@ /** Initialization. */ void init(); - /** Start the measurement. */ - void startMeasurement(); + void turnOffTrigger(); }; #endif \ No newline at end of file