PING Library
PING.cpp
- Committer:
- mshoemaker
- Date:
- 2010-02-11
- Revision:
- 0:ae8d48256ff1
File content as of revision 0:ae8d48256ff1:
#include "PING.h" #include "mbed.h" /* * Constructor */ PING::PING(PinName trigger) : _trigger(trigger) { // Attach interrupts _ticker.attach(this, &PING::_startRange, 0.1); } void PING::_startRange() { // send a trigger pulse, 20uS long _trigger.output(); // set pin to output trigger pulse _trigger = 0; // ensure pin starts low wait_us(2); // wait two microseconds _trigger = 1; // send trigger pulse by setting pin high wait_us(5); // keep sending pulse for 5 microseconds _trigger = 0; // set pin low to stop pulse _trigger.input(); // pulseIn while (!_trigger); // wait for high _timer.reset(); _timer.start(); while (_trigger); // wait for low _timer.stop(); _dist = _timer.read_us(); //provides echo time in microseconds } // returns distance in meters // The speed of sound is 340 m/s or 58 microseconds per meter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. float PING::read(void) { // spin until there is a good value return (_dist/29/2); } // returns distance in inches // According to Parallax's datasheet for the PING))), there are // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // second). This gives the distance travelled by the ping, outbound // and return, so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf float PING::read_in(void) { // spin until there is a good value return (_dist/74/2); } PING::operator float() { return read(); }