BayEOS-Arduino  1.8.0_0.0.4
SRF02.cpp
1 #include "SRF02.h"
2 
4 const int READ_DURATION = 70;
5 const int RESULT_REGISTER = 0x02;
6 const int DEVICE_ADDRESS = 0x70;
7 
8 SRF02::SRF02(int deviceId, int mode)
9 { this->_deviceId = deviceId;
10  this->_mode = mode;
11  Wire.begin();
12 }
13 
14 // Default Constructor
16 { this->_deviceId = DEVICE_ADDRESS;
17  this->_mode = SRF02_CENTIMETERS;
18  Wire.begin();
19 }
20 
22  sendCommand(_deviceId, _mode);
23  delay(READ_DURATION);
24  setRegister(_deviceId, RESULT_REGISTER);
25  return readData(_deviceId, 2);
26 }
27 
28 
29 void SRF02::sendCommand (int deviceId, int command) {
30  // start I2C transmission:
31  Wire.beginTransmission(deviceId);
32  // send command:
33  Wire.write((byte)0x00);
34  Wire.write((byte)command);
35  // end I2C transmission:
36  Wire.endTransmission();
37 }
38 
39 void SRF02::setRegister(int deviceId, int thisRegister) {
40  // start I2C transmission:
41  Wire.beginTransmission(deviceId);
42  // send address to read from:
43  Wire.write(thisRegister);
44  // end I2C transmission:
45  Wire.endTransmission();
46 }
47 
48 
49 /*
50  readData() returns a result from the SRF sensor
51 */
52 int SRF02::readData(int deviceId, int numBytes) {
53  int result = 0; // the result is two bytes long
54  // send I2C request for data:
55  Wire.requestFrom(deviceId, numBytes);
56  // wait for two bytes to return:
57  while (Wire.available() < 2 ) {
58  // wait for result
59  }
60  // read the two bytes, and combine them into one int:
61  result = Wire.read() * 256;
62  result = result + Wire.read();
63  return result;
64 }
int getDistance()
Definition: SRF02.cpp:21
int _mode
Definition: SRF02.h:44
int _deviceId
Definition: SRF02.h:42
SRF02()
Definition: SRF02.cpp:15