Dev Joshi
/
SRF02_libv2
Library for the SRF02 ultrasonic rangefinder
Diff: SRF02.cpp
- Revision:
- 0:862f11d627f9
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/SRF02.cpp Sun Jul 10 16:40:35 2011 +0000 @@ -0,0 +1,52 @@ + + +/*Library for SRF02 ultrasonic range finder*/ +#include "SRF02.h" + + + +SRF02::SRF02(PinName sda, PinName scl, int addr) : m_i2c(sda, scl), m_addr(addr){ + //no initialisation code required here + } + +SRF02::~SRF02(){ + +} + +float SRF02::measurecm() { + float result = dosonar(0x51); + return result; +} + +float SRF02::measureus() { + float result = dosonar(0x52); + return result; +} + +float SRF02::measurein() { + float result = dosonar(0x50); + return result; +} + + +float SRF02::dosonar(char rangetype){ + //local variables + const char m_addr = 0xE0; //srf02 default slave address + char commandsequence[2]; + + // Get range data from SRF02 in cm + // Send Tx burst command over I2C bus + commandsequence[0] = 0x00; // Command register + commandsequence[1] = rangetype; // Ranging results type + m_i2c.write(m_addr, commandsequence, 2); // Request ranging from sensor + wait(0.07); // Average wait time for sonar pulse and processing + // Read back range over I2C bus + commandsequence[0] = 0x02; // + m_i2c.write(m_addr, commandsequence, 1, 1); // + m_i2c.read(m_addr, commandsequence, 2); // Read two-byte echo result + //combine upper and lower bytes in to a single value + float range = ((commandsequence[0] << 8) + commandsequence[1]); + return range; + +} +