Getting messy values from Sharp IR sensor

Greetings! I am trying to use a Sharp IR sensor 2Y0A21 to measure the distance 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 sensible units 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()
{
Serial.begin(9600);
}

void loop()
{
distance = analogRead(pin);
Serial.println(distance);
delay(100);
}

//Help will be much appreciated!

I have no idea what units these numbers are in

The units are voltage. They are non-linear readings. You will have to build your own calibration curve.

I'm getting messy numbers that increase as an object comes closer to the sensor and decrease as the object moves away.

The Sharp sensors that I have behave in a similar fashion. To make matters worse, the curve depends on the reflective material.

You may want to read the following:
http://acroname.com/robotics/info/articles/sharp/sharp.html

Ah I see, so the numbers correspond to the graph. Is there a formula I can use to convert these numbers into calculating the distance instead of voltage? Or perhaps a formula to just get more stable values where the voltage reads 0 when an object is right in front of it and increases and the object is moved away from it. Numbers that I can work with.

What is the application?
You should start with the behavior that is needed. Lets suppose this is a small robot that should avoid bumping into a wall.
The rules:

  1. < 1.5v full speed ahead
  2. 1.5v - 2.5v slow down
  3. 2.8v stop and turn

Of course I just made it up. The point is you may not need any conversion depending on the application.
If you really need distance you can use an algebraic equation or a lookup table with interpolation. I prefer lookup tables, which can be setup directly from test measurements. Simple interpolation will improve accuracy if needed.