
SRF02 Ultrasonic range finder library
Diff: SRF02.cpp
- Revision:
- 0:f0cf55dd23f6
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/SRF02.cpp Mon May 02 18:44:46 2011 +0000 @@ -0,0 +1,76 @@ +/*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::distancecm(){ + //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] = 0x51; // Ranging results in cm + 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; + +} + +float SRF02::distancein(){ + //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] = 0x50; // Ranging results in cm + 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; + +} + +float SRF02::distanceus(){ + //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] = 0x52; // Ranging results in cm + 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; + +} + + +