Uso de Sensor de Ultrasonidos
Diff: UltraSonidos.cpp
- Revision:
- 0:3b305cf58a40
- Child:
- 1:42d7fd2a719e
diff -r 000000000000 -r 3b305cf58a40 UltraSonidos.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/UltraSonidos.cpp Thu Feb 24 18:50:00 2011 +0000 @@ -0,0 +1,48 @@ +#include "UltraSonidos.h" +#include "mbed.h" + + +UltraSonidos::UltraSonidos(PinName pin) : _pinDigital(pin) { + +} + +long UltraSonidos::read(){ + +long duration; + + _pinDigital.output(); + _pinDigital = 0; + wait_ms(2); + _pinDigital = 1; + wait_ms(15); + _pinDigital = 0; + wait_ms(20); + + _pinDigital.input(); + duration = pulseIn(_pinDigital); + + // convert the time into a distance + + return microsegundosAcentimetros(duration); + + + + +} + +int UltraSonidos::pulseIn(DigitalInOut& pingPin) { + Timer tmr; + while (!pingPin); // wait for high + tmr.start(); + while (pingPin); // wait for low + return tmr.read_ms(); +} + + +long UltraSonidos::microsegundosAcentimetros(long microsegundos) +{ + // The speed of sound is 340 m/s or 29 microseconds per centimeter. + // The ping travels out and back, so to find the distance of the + // object we take half of the distance travelled. + return microsegundos / 29 / 2; +} \ No newline at end of file