SRF02 Ultrasonic Ranger
Dependents: DISCO-F746NG_SRF02_2
Revision 0:adf5a063372d, committed 2014-07-31
- Comitter:
- yangcq88517
- Date:
- Thu Jul 31 13:52:49 2014 +0000
- Commit message:
- SRF02
Changed in this revision
SRF02.cpp | Show annotated file Show diff for this revision Revisions of this file |
SRF02.h | Show annotated file Show diff for this revision Revisions of this file |
diff -r 000000000000 -r adf5a063372d SRF02.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/SRF02.cpp Thu Jul 31 13:52:49 2014 +0000 @@ -0,0 +1,58 @@ +#include "SRF02.h" + +SRF02::SRF02(uint8_t I2C_address,PinName sda, PinName scl): i2c_bus(sda,scl) +{ + deviceAddess = I2C_address; +} + +int SRF02::GetValue(uint8_t command, uint8_t mode) +{ + char w[2]= {COMMAND_REGISTER,command}; + if (i2c_bus.write(deviceAddess,w ,2)>=0) + wait(DefaultWait); + else return -1; + char r[1] = {mode}; + if (i2c_bus.write(deviceAddess,r ,1)>=0) + if (i2c_bus.read(deviceAddess, w, 2)>=0) + return (w[0] << 8) | w[1]; + return -1; +} + +int SRF02::GetMinimumRange() +{ + return GetValue(REAL_RANGING_CENTIMETERS,Autotune); +} + +int SRF02::GetCentimeters() +{ + return GetValue(REAL_RANGING_CENTIMETERS,Range); +} + +int SRF02::GetInches() +{ + return GetValue(REAL_RANGING_INCHES,Range); +} + +int SRF02::GetMicroSeconds() +{ + return GetValue(REAL_RANGING_SECONDS,Range); +} + +bool SRF02::ChangeAddress(uint8_t newAddress) +{ + char w[2]= {COMMAND_REGISTER,0xA0}; + if (i2c_bus.write(deviceAddess,w ,2)>=0) + w[1] = 0xAA; + else return false; + if (i2c_bus.write(deviceAddess,w ,2)>=0) + w[1] = 0xA5; + else return false; + if (i2c_bus.write(deviceAddess,w ,2)>=0) + w[1] = newAddress; + else return false; + if (i2c_bus.write(deviceAddess,w ,2)>=0) { + deviceAddess = newAddress; + return true; + } + return false; +}
diff -r 000000000000 -r adf5a063372d SRF02.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/SRF02.h Thu Jul 31 13:52:49 2014 +0000 @@ -0,0 +1,42 @@ +#ifndef Smartlab_Drive_SPRF02 +#define Smartlab_Drive_SPRF02 + +#include "mbed.h" + +class SRF02 + +{ +private: + uint8_t deviceAddess; + static const int CLOCK_RATE = 100000; + + static const uint8_t COMMAND_REGISTER = 0x00; + + static const uint8_t Range = 0x02; + static const uint8_t Autotune = 0x04; + + static const uint8_t REAL_RANGING_INCHES = 0x50; + static const uint8_t REAL_RANGING_CENTIMETERS = 0x51; + static const uint8_t REAL_RANGING_SECONDS = 0x52; + + static const float DefaultWait = 0.07; + + I2C i2c_bus; + + int GetValue(uint8_t command, uint8_t mode); + +public : + SRF02(uint8_t I2C_address,PinName sda, PinName scl); + + int GetMinimumRange(); + + int GetCentimeters(); + + int GetInches(); + + int GetMicroSeconds(); + + bool ChangeAddress(uint8_t newAddress); +}; + +#endif \ No newline at end of file