This Arduino sketch reads distance measurements from an SRF02 ultrasonic sensor using I2C communication. It initializes the I2C bus, sends commands to the sensor to select reading units and measurement register, reads the register value which returns the distance measurement over two bytes, and prints distances greater than 10cm. It delays between readings and sets measurements below 30cm to 0 to avoid ineffective close-range sensor readings.
Download as TXT, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
270 views
Codigo SRF02 Arduino
This Arduino sketch reads distance measurements from an SRF02 ultrasonic sensor using I2C communication. It initializes the I2C bus, sends commands to the sensor to select reading units and measurement register, reads the register value which returns the distance measurement over two bytes, and prints distances greater than 10cm. It delays between readings and sets measurements below 30cm to 0 to avoid ineffective close-range sensor readings.
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2
/*
SRF02 sensor reader
language:Wiring/Arduino */ #include <TwoWire.h> #define sensorAddress 0x70 #define readInches 0x50 // use this for cm or microsecods #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 serial port: Serial.begin(9600); } void sendCommand (int address, int command) { //start I2C transmission: Wire.beginTransmission(address); //send command: Wire.send(0x00); Wire.send(command); //end I2C transmission: Wire.endTransmission(); } void setRegister(int address, int thisRegister) { //start IC2 transmission: Wire.beginTransmission(address); //send address to read from: Wire.send(thisRegister); //end I2C transmission(); Wire.endTransmission(); } /* readData() returns a result from the SRF sensor */ int readData(int address, int numBytes) { int result = 0; // the result is two bytes long //send i2c request for data: Wire.requestFrom(address, numBytes); //wait for two bytes to return: // while (Wire.available() < 2 );{ //wait for result //} // read thew two bytes, and combine them into one int: result = Wire.receive() * 256; result = result + Wire.receive();
//return the result:
return result; } void loop() { //send the command to read the result in CM: sendCommand(sensorAddress, readCentimeters); //wait at least 70ms for a result: delay(500); //set the reigster that you want to read the result from: setRegister(sensorAddress, resultRegister); //read the result: int sensorReading = readData(sensorAddress, 2); //print it if(sensorReading > 10){ Serial.println(sensorReading); }
// wait before next reading:
delay(20); delay(20); delay(20); if (sensorReading < 30) //because sensor is innefective below 20cm, closer th an 30cm sends 0 to the servo { sensorReading = 0; } }