Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
sr04.cpp
- Committer:
- dereklmc
- Date:
- 2013-06-08
- Revision:
- 2:295fd882bb12
- Parent:
- 0:77ccdb02e2cc
- Child:
- 3:270ca55f4e0c
File content as of revision 2:295fd882bb12:
#include "sr04.h"
#include "mbed.h"
// PTD2 is RX - data in
// PTD3 is TX - data out
// TX -> trigger echo -> RX
SR04::SR04(PinName trigger, PinName echo)
: _trigger(trigger), _echo(echo) {
// Attach interrupts
_echo.rise(this, &SR04::_rising);
_echo.fall(this, &SR04::_falling);
_ticker.attach(this, &SR04::_startRange, 0.1);
}
void SR04::_startRange() {
// send a trigger pulse, 10uS long
_trigger = 1;
wait (0.00001);
_trigger = 0;
}
// Clear and start the timer at the begining of the echo pulse
void SR04::_rising(void) {
_timer.reset();
_timer.start();
}
// Stop and read the timer at the end of the pulse
void SR04::_falling(void) {
_timer.stop();
/*
* Distance:
* uS / 58 = centimeters
* uS / 148 = inches
* range = high level time * velocity (340M/S) / 2
*/
_dist = _timer.read_us()/58.0; // distance in centimeters
}
float SR04::read(void) {
// spin until there is a good value
return (_dist);
}
SR04::operator float() {
return read();
}
