Fumiya Fujisawa / Ping

Dependents:   CatPot_SensorRight CatPotI2CSlavetest CatPotI2CSlavetest CatPot_SensorRight_F ... more

Fork of Ping by Joel Rosiene

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers Ping.cpp Source File

Ping.cpp

00001 #include "Ping.h"
00002 
00003 #include "mbed.h"
00004 
00005 Ping::Ping(PinName Trig_PIN, PinName Echo_PIN)
00006         : _event(Echo_PIN)
00007         , _trig(Trig_PIN),_echo(Echo_PIN)
00008         , _timer()
00009         {
00010             _event.rise(this,&Ping::_Starts);
00011             _event.fall(this,&Ping::_Stops);
00012             _SPEED_OF_SOUND_CM = 33;
00013         } 
00014         
00015 void Ping::_Starts(void)
00016 {
00017       _Valid = false;  // start the timere, and invalidate the current time.
00018       _Busy = true;
00019       _timer.start();
00020       _Time = _timer.read_us();      
00021 }
00022 
00023 void Ping::_Stops(void)
00024 {
00025       _Valid = true;  // When it stops, update the time
00026       _Busy = false;
00027       _Time = _timer.read_us()-_Time;
00028 }
00029 
00030 void Ping::Send()
00031 {
00032      
00033      _trig.write(0);  // see the ping documentation http://www.parallax.com/Portals/0/Downloads/docs/prod/acc/28015-PING-v1.6.pdf
00034      wait_us(3);
00035      _trig.write(1);
00036      wait_us(3);
00037      _trig.write(0);
00038      
00039 }
00040 void Ping::Set_Speed_of_Sound(int SoS_ms )
00041 {
00042      _SPEED_OF_SOUND_CM = SoS_ms;
00043 }
00044 
00045 int Ping::Read_cm()
00046 // -1 means not valid.
00047 {
00048     if(_Valid && ~_Busy) 
00049         return ((_Time*_SPEED_OF_SOUND_CM)/1000/2);
00050     else 
00051         return -1;
00052 }