Sharp IR sensor 2Y0A21

Greetings! I am trying to use a Sharp IR sensor 2Y0A21 to measure the distance (in cm) of objects. With the code I'm using, I'm getting messy numbers that increase as an object comes closer to the sensor and decrease as the object moves away. I have no idea what units these numbers are in (if they are in any) and it would be helpful if someone could help me convert these numbers into cm (10 TO 80 CM) unit or at least display the numbers in the opposite direction since it's kind of backwards as I have it now.

Here is my code:

int pin = 0;                
int distance = 0;                

void setup()

void loop()
 distance = analogRead(pin);      

//Help will be much appreciated!

Give us a list of example numbers and actual distances to us to try and answer the question.


You're reading an analog pin so those readings will be based on the volts output the sensor, and will be from 0 to 1023. The datasheet will show a curve of volts out vs distance: you could either build a lookup table of pairs from the graph, or see if there's some arithmetic relationship.

I found this relationship through Google, but not sure if it's for that model:

Distance (cm) = 4800/(SensorValue - 20)