Go Down

Topic: ir sensor in inches? (Read 691 times) previous topic - next topic

Cryper

hey guys,

using a IR SHARP Sensor P2Y0A21YK0F (0-80cm). two part question.
i need to make the serialprint give me back a distance reading in inches. the code below is for centimeters. the sensors data sheet tells me the distance 65 should be changed to about 27. i believe the voltage stays the same. And second part is to work in some smoothing. i'm pasting the code for that below after the first code set.

appreciate any advice you guys can run by me.
thanks,
Cryper


credit: this code belongs to the owner of this webpage
http://luckylarry.co.uk/arduino-projects/arduino-using-a-sharp-ir-sensor-for-distance-calculation/comment-page-1/#comment-4824



int IRpin = 1;                                    // analog pin for reading the IR sensor
void setup() {
 Serial.begin(9600);                             // start the serial port
}
void loop() {
 float volts = analogRead(IRpin)*0.0048828125;  
// value from sensor * (5/1024) - if running 3.3.volts then change 5 to 3.3
 float distance = 65*pow(volts, -1.10);          
// worked out from graph 65 = theretical distance / (1/Volts)S - luckylarry.co.uk

 Serial.println(distance);                       // print the distance
 delay(100);                                     // arbitary wait time.
}


and my smoothing code


int sensor = 0;
int distRead = 0;
int distAvg = 0;
int runningtotal = 0;
int i = 0;

void setup()
{
 // initialize serial communication with computer:
 Serial.begin(9600);                  
 // initialize all the readings to 0:
}

void loop() {
 
 {
   for (i=0; i < 10; i++)
 {
   distRead = analogRead(sensor);
   runningtotal += distRead;
 }
 distAvg = (runningtotal / 10);
}
 Serial.println(distAvg, DEC);              
 delay(4000);
}

Big Oil

To go from centimeters to inches divide the centimeters by 2.54

For the smoothing for loop, when you take the samples you could put a bit of time between each sample like delay(10); but maybe you don't have to do that.  Those for loops will run 290,000 times a second though.  Be sure to reset runningtotal back to 0 after you calculate the average.

AWOL

Quote
Those for loops will run 290,000 times a second though

No, it won't, because it's got an "analogRead" in it.    ;)
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Cryper

As usual you guys never disappoint! Thank you oh wise sages  of the code! ::)

Go Up