Used command byte to return distance in inches.

Dependents:   2ndYearProject-DistanceSensor

Fork of SRF02 by Craig Evans

Files at this revision

API Documentation at this revision

Comitter:
ll13j7b
Date:
Sun Mar 27 22:48:51 2016 +0000
Parent:
1:8e6587d88773
Commit message:
version 1.1

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
--- a/SRF02.cpp	Sun Mar 08 14:21:40 2015 +0000
+++ b/SRF02.cpp	Sun Mar 27 22:48:51 2016 +0000
@@ -44,7 +44,36 @@
     return (data[0] << 8) | data[1];
 }
 
-void SRF02::error()
+int SRF02::getDistanceInch()
+{
+    char data[2];
+    
+    // need to send CM command to command register
+    data[0] = CMD_REG;
+    data[1] = INCH_CMD; // setting the new command byte to inches 
+    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,&reg,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() // error message ( flashing LED )
 {
     while(1) {
         leds->write(15);
--- a/SRF02.h	Sun Mar 08 14:21:40 2015 +0000
+++ b/SRF02.h	Sun Mar 27 22:48:51 2016 +0000
@@ -71,6 +71,12 @@
     * 
     */
     int getDistanceCm();
+    /** Read distance in inches
+    *
+    * @returns distance in inches (int)
+    * 
+    */
+    int getDistanceInch();
 
 private:
     /** Hangs in infinite loop flashing 'blue lights of death'