Slightly revised version of the SRF02 library created by Craig A. Evans
Fork of SRF02 by
SRF02.cpp
- Committer:
- andreykotov91
- Date:
- 2016-05-08
- Revision:
- 4:5e3954a62b23
- Parent:
- 3:f05c1d276665
File content as of revision 4:5e3954a62b23:
/** @file SRF02.cpp @brief Member functions implementations */ #include "mbed.h" #include "SRF02.h" SRF02::SRF02(PinName sdaPin, PinName sclPin) { i2c_ = new I2C(sdaPin,sclPin); // create new I2C instance and initialise i2c_->frequency(400000); // I2C Fast Mode - 400kHz led_ = new DigitalOut(LED_RED); } int SRF02::getDistanceCm() { char data[2]; // need to send CM command to command register data[0] = CMD_REG; data[1] = CM_CMD; int ack = i2c_->write(SRF02_W_ADD,data,2); if (ack) error(); // if we don't receive acknowledgement, flash error message // this will start the sensor ranging, the datasheet suggests a delay of at least 65 ms before reading the result wait_ms(70); // we can now read the result - tell the sensor we want the high byte char reg = RANGE_H_REG; ack = i2c_->write(SRF02_W_ADD,®,1); if (ack) error(); // if we don't receive acknowledgement, flash error message // if we read two bytes, the register is automatically incremented (H and L) ack = i2c_->read(SRF02_R_ADD,data,2); if (ack) error(); // if we don't receive acknowledgement, flash error message // high byte is first, then low byte, so combine into 16-bit value return (data[0] << 8) | data[1]; } void SRF02::error() { while(1) { led_->write(1); wait(0.1); led_->write(0); wait(0.1); } }