Library for interfacing with the Parallax Ping))) sensor.
Diff: ping.cpp
- Revision:
- 0:99ee7c741e9d
- Child:
- 1:72fbcb01291d
diff -r 000000000000 -r 99ee7c741e9d ping.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ping.cpp Sun Jul 27 19:12:34 2014 +0000 @@ -0,0 +1,42 @@ +#include "ping.h" + +Ping::Ping(PinName signalPin) : mSignalIo(signalPin, PIN_OUTPUT, PullDown, 0), mEvent(signalPin), + mBusy(0), mValid(0), mContinuous(0), mTimer(), mRawReading(0) { + mEvent.rise(this, &Ping::start); + mEvent.fall(this, &Ping::stop); +} + +bool Ping::startReading() { + return this->startReading(false); +} + +bool Ping::startReading(bool continuous) { + mContinuous = continuous; + if (mBusy) return false; + + mSignalIo.output(); + mSignalIo = 0; + wait_us(2); + mSignalIo = 1; + wait_us(10); + mSignalIo.input(); + + return true; +} + +void Ping::start() { + mBusy = true; + mValid = false; + mTimer.start(); + mStartTime = mTimer.read_us(); +} + +void Ping::stop() { + mBusy = false; + mValid = true; + // The time it takes is for a round trip. We divide by two to get the time for one way. + mRawReading = (mTimer.read_us() - mStartTime) >> 1; + mTimer.stop(); + mCallback.call(mRawReading); + if (mContinuous) this->startReading(mContinuous); +} \ No newline at end of file