Library for interfacing with the Parallax Ping))) sensor.
ping.cpp@3:0c337c262d84, 2014-07-28 (annotated)
- Committer:
- d34d
- Date:
- Mon Jul 28 00:16:34 2014 +0000
- Revision:
- 3:0c337c262d84
- Parent:
- 1:72fbcb01291d
- Child:
- 5:cbe07c09c64c
Cleaned up timing of the pulse and added helper methods to convert time in uS to distance traveled in centimeters or inches.
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 | 0:99ee7c741e9d | 4 | mBusy(0), mValid(0), mContinuous(0), mTimer(), mRawReading(0) { |
d34d | 0:99ee7c741e9d | 5 | mEvent.rise(this, &Ping::start); |
d34d | 0:99ee7c741e9d | 6 | mEvent.fall(this, &Ping::stop); |
d34d | 0:99ee7c741e9d | 7 | } |
d34d | 0:99ee7c741e9d | 8 | |
d34d | 0:99ee7c741e9d | 9 | bool Ping::startReading() { |
d34d | 0:99ee7c741e9d | 10 | return this->startReading(false); |
d34d | 0:99ee7c741e9d | 11 | } |
d34d | 0:99ee7c741e9d | 12 | |
d34d | 0:99ee7c741e9d | 13 | bool Ping::startReading(bool continuous) { |
d34d | 0:99ee7c741e9d | 14 | mContinuous = continuous; |
d34d | 0:99ee7c741e9d | 15 | if (mBusy) return false; |
d34d | 0:99ee7c741e9d | 16 | |
d34d | 0:99ee7c741e9d | 17 | mSignalIo.output(); |
d34d | 3:0c337c262d84 | 18 | mSignalIo.write(0); |
d34d | 3:0c337c262d84 | 19 | wait_us(3); |
d34d | 3:0c337c262d84 | 20 | mSignalIo.write(1); |
d34d | 3:0c337c262d84 | 21 | wait_us(3); |
d34d | 3:0c337c262d84 | 22 | mSignalIo.write(0); |
d34d | 0:99ee7c741e9d | 23 | mSignalIo.input(); |
d34d | 0:99ee7c741e9d | 24 | |
d34d | 0:99ee7c741e9d | 25 | return true; |
d34d | 0:99ee7c741e9d | 26 | } |
d34d | 0:99ee7c741e9d | 27 | |
d34d | 0:99ee7c741e9d | 28 | void Ping::start() { |
d34d | 0:99ee7c741e9d | 29 | mBusy = true; |
d34d | 0:99ee7c741e9d | 30 | mValid = false; |
d34d | 3:0c337c262d84 | 31 | mTimer.reset(); |
d34d | 0:99ee7c741e9d | 32 | mTimer.start(); |
d34d | 0:99ee7c741e9d | 33 | } |
d34d | 0:99ee7c741e9d | 34 | |
d34d | 0:99ee7c741e9d | 35 | void Ping::stop() { |
d34d | 0:99ee7c741e9d | 36 | mBusy = false; |
d34d | 0:99ee7c741e9d | 37 | mValid = true; |
d34d | 0:99ee7c741e9d | 38 | // The time it takes is for a round trip. We divide by two to get the time for one way. |
d34d | 3:0c337c262d84 | 39 | mRawReading = mTimer.read_us() >> 1; |
d34d | 0:99ee7c741e9d | 40 | mTimer.stop(); |
d34d | 0:99ee7c741e9d | 41 | mCallback.call(mRawReading); |
d34d | 1:72fbcb01291d | 42 | if (mContinuous) mMeasureDelayTicker.attach_us(this, &Ping::nextMeasurement, 5000); |
d34d | 1:72fbcb01291d | 43 | } |
d34d | 1:72fbcb01291d | 44 | |
d34d | 1:72fbcb01291d | 45 | void Ping::nextMeasurement() { |
d34d | 1:72fbcb01291d | 46 | mMeasureDelayTicker.detach(); |
d34d | 1:72fbcb01291d | 47 | this->startReading(mContinuous); |
d34d | 0:99ee7c741e9d | 48 | } |