Library for interfacing with the Parallax Ping))) sensor.
ping.cpp@5:cbe07c09c64c, 2014-07-29 (annotated)
- Committer:
- d34d
- Date:
- Tue Jul 29 02:34:02 2014 +0000
- Revision:
- 5:cbe07c09c64c
- Parent:
- 3:0c337c262d84
Add user defined delay between continuous readings.
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
d34d | 0:99ee7c741e9d | 1 | #include "ping.h" |
d34d | 0:99ee7c741e9d | 2 | |
d34d | 3:0c337c262d84 | 3 | Ping::Ping(PinName signalPin) : mSignalIo(signalPin), mEvent(signalPin), |
d34d | 5:cbe07c09c64c | 4 | mBusy(0), mValid(0), mContinuous(0), |
d34d | 5:cbe07c09c64c | 5 | mDelayBetweenReadings(DEFAULT_MEASUREMENT_DELAY_US), mTimer(), mRawReading(0) { |
d34d | 0:99ee7c741e9d | 6 | mEvent.rise(this, &Ping::start); |
d34d | 0:99ee7c741e9d | 7 | mEvent.fall(this, &Ping::stop); |
d34d | 0:99ee7c741e9d | 8 | } |
d34d | 0:99ee7c741e9d | 9 | |
d34d | 0:99ee7c741e9d | 10 | bool Ping::startReading() { |
d34d | 0:99ee7c741e9d | 11 | return this->startReading(false); |
d34d | 0:99ee7c741e9d | 12 | } |
d34d | 0:99ee7c741e9d | 13 | |
d34d | 0:99ee7c741e9d | 14 | bool Ping::startReading(bool continuous) { |
d34d | 0:99ee7c741e9d | 15 | mContinuous = continuous; |
d34d | 0:99ee7c741e9d | 16 | if (mBusy) return false; |
d34d | 0:99ee7c741e9d | 17 | |
d34d | 0:99ee7c741e9d | 18 | mSignalIo.output(); |
d34d | 3:0c337c262d84 | 19 | mSignalIo.write(0); |
d34d | 3:0c337c262d84 | 20 | wait_us(3); |
d34d | 3:0c337c262d84 | 21 | mSignalIo.write(1); |
d34d | 3:0c337c262d84 | 22 | wait_us(3); |
d34d | 3:0c337c262d84 | 23 | mSignalIo.write(0); |
d34d | 0:99ee7c741e9d | 24 | mSignalIo.input(); |
d34d | 0:99ee7c741e9d | 25 | |
d34d | 0:99ee7c741e9d | 26 | return true; |
d34d | 0:99ee7c741e9d | 27 | } |
d34d | 0:99ee7c741e9d | 28 | |
d34d | 0:99ee7c741e9d | 29 | void Ping::start() { |
d34d | 0:99ee7c741e9d | 30 | mBusy = true; |
d34d | 0:99ee7c741e9d | 31 | mValid = false; |
d34d | 3:0c337c262d84 | 32 | mTimer.reset(); |
d34d | 0:99ee7c741e9d | 33 | mTimer.start(); |
d34d | 0:99ee7c741e9d | 34 | } |
d34d | 0:99ee7c741e9d | 35 | |
d34d | 0:99ee7c741e9d | 36 | void Ping::stop() { |
d34d | 0:99ee7c741e9d | 37 | mBusy = false; |
d34d | 0:99ee7c741e9d | 38 | mValid = true; |
d34d | 0:99ee7c741e9d | 39 | // The time it takes is for a round trip. We divide by two to get the time for one way. |
d34d | 3:0c337c262d84 | 40 | mRawReading = mTimer.read_us() >> 1; |
d34d | 0:99ee7c741e9d | 41 | mTimer.stop(); |
d34d | 0:99ee7c741e9d | 42 | mCallback.call(mRawReading); |
d34d | 5:cbe07c09c64c | 43 | if (mContinuous) mMeasureDelayTicker.attach_us(this, &Ping::nextMeasurement, mDelayBetweenReadings); |
d34d | 1:72fbcb01291d | 44 | } |
d34d | 1:72fbcb01291d | 45 | |
d34d | 1:72fbcb01291d | 46 | void Ping::nextMeasurement() { |
d34d | 1:72fbcb01291d | 47 | mMeasureDelayTicker.detach(); |
d34d | 1:72fbcb01291d | 48 | this->startReading(mContinuous); |
d34d | 0:99ee7c741e9d | 49 | } |