
270 MAKING THINGS TALK
»
/*
SRF02 sensor reader
language: Wiring/Arduino
Reads data from a Devantech SRF02 ultrasonic sensor.
Should also work for the SRF08 and SRF10 sensors as well.
Sensor connections:
SDA - Analog pin 4
SCL - Analog pin 5
*/
// include Wire library to read and write I2C commands:
#include <Wire.h>
// the commands needed for the SRF sensors:
#define sensorAddress 0x70
#define readInches 0x50
// use these as alternatives if you want centimeters or microseconds:
#define readCentimeters 0x51
#define readMicroseconds 0x52
// this is the memory register in the sensor that contains the result:
#define resultRegister 0x02
void setup()
{
// start the I2C bus
Wire.begin();
// open the serial port:
Serial.begin(9600);
}
void loop()
{
// send the command to read the result in inches:
sendCommand(sensorAddress, readInches);
// wait at least 70 milliseconds for a result:
delay(70);
// set the register that you want to read the result from:
setRegister(sensorAddress, resultRegister);
// read the result:
int sensorReading = readData(sensorAddress, 2);
// print it:
Serial.print("distance: ");
Serial.print(sensorReading);
Serial.println(" inches");
// wait before next reading:
delay(70);
}
This sketch sends
commands to the SRF02
sensor to take distance readings and
return them to the microcontroller.
NOTE: If you have trouble ...