codigo srf02 arduino

Download Codigo SRF02 Arduino

If you can't read please download the document

Upload: pedro-rios

Post on 04-Dec-2015

18 views

Category:

Documents


10 download

DESCRIPTION

Código para hacer funcionar el sensor SRF02 con Arduino

TRANSCRIPT

/*SRF02 sensor readerlanguage:Wiring/Arduino*/#include #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 0x02void 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 than 30cm sends 0 to the servo{ sensorReading = 0;}}