blabla
Revision 0:8ae0145ae26e, committed 2018-06-21
- Comitter:
- twjfransen
- Date:
- Thu Jun 21 11:39:58 2018 +0000
- Commit message:
- bla
Changed in this revision
sonar.cpp | Show annotated file Show diff for this revision Revisions of this file |
sonar.h | Show annotated file Show diff for this revision Revisions of this file |
diff -r 000000000000 -r 8ae0145ae26e sonar.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sonar.cpp Thu Jun 21 11:39:58 2018 +0000 @@ -0,0 +1,50 @@ +#include "sonar.h" + +Sonar::Sonar(PinName trig, PinName echo) + :_trig(trig) + ,_echo(echo) +{ + _timer.start(); + _echo.rise(callback(this, &Sonar::echoBegin)); + _echo.fall(callback(this, &Sonar::echoEnd)); + _pinged = false; +} + +void Sonar::echoBegin() +{ + _timer.reset(); + _begin = _timer.read_us();} + +void Sonar::echoEnd() +{ + _end = _timer.read_us(); + _distance = (_end - _begin)/58.3; + _pinged = true; +} + +float Sonar::getDistance() +{ + _trig = 1; + wait_us(10); + _trig = 0; + while(!_pinged){printf("");} + _pinged = false; + return _distance; +} + +void Sonar::pulse() +{ + _trig = 1; + wait_us(10); + _trig = 0; +} + +void Sonar::autoPulse(bool on_off, float frequency_ms /*=1*/) +{ + if (on_off) { + _ticker.attach(callback(this, &Sonar::pulse), frequency_ms/1000); + } + else { + _ticker.detach(); + } +} \ No newline at end of file
diff -r 000000000000 -r 8ae0145ae26e sonar.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sonar.h Thu Jun 21 11:39:58 2018 +0000 @@ -0,0 +1,24 @@ +#include "mbed.h" + +class Sonar{ + public: + Sonar(PinName trig, PinName echo); + float getDistance(); + float getLastDistance() {return _distance;} + void autoPulse(bool on_off, float frequency_ms = 1); + void pulse(); + + private: + Ticker _ticker; + Timer _timer; + DigitalOut _trig; + InterruptIn _echo; + + int _begin; + int _end; + float _distance; + bool _pinged; + + void echoBegin(); + void echoEnd(); +}; \ No newline at end of file