Pedro Enrique Vidal Peñas / UltraSonidos
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers UltraSonidos.cpp Source File

UltraSonidos.cpp

00001 #include "UltraSonidos.h"
00002 #include "mbed.h"
00003 
00004 
00005 UltraSonidos::UltraSonidos(PinName pin) : _pinDigital(pin) {
00006   
00007 }
00008 
00009 long UltraSonidos::read(){
00010 
00011 long duration;
00012 
00013   _pinDigital.output();
00014   _pinDigital = 0;
00015   wait_ms(2);
00016   _pinDigital = 1;
00017   wait_ms(5);
00018   _pinDigital = 0;
00019 
00020 
00021   _pinDigital.input();
00022   duration = pulseIn(_pinDigital);
00023 
00024   // convert the time into a distance
00025   
00026   return microsegundosAcentimetros(duration);
00027   
00028   
00029   
00030 
00031 }
00032 
00033 int UltraSonidos::pulseIn(DigitalInOut& pingPin) {
00034     Timer tmr;
00035     while (!pingPin); // wait for high
00036     tmr.start();
00037     while (pingPin); // wait for low
00038     return tmr.read_ms();
00039 }
00040 
00041 
00042 long UltraSonidos::microsegundosAcentimetros(long microsegundos)
00043 {
00044   // The speed of sound is 340 m/s or 29 microseconds per centimeter.
00045   // The ping travels out and back, so to find the distance of the
00046   // object we take half of the distance travelled.
00047   return microsegundos / 29 / 2;
00048 }