Arduino Uno with Sharp GP2D12 Range Sensor help please

I have a SharpGP2D12 connected to my arduino uno via analog in 1. I tested the range sensor with my multimeter and am getting the correct values. When I run my code however, I get really weird values. I wrote this code to try and convert the values into centimeters. I put the code and the output below, if anyone has any ideas I would greatly appreciate it, not sure why the values are incorrect.

It actually worked earlier and I think I might have messed up the code somehow and I have gone too far to undo it... I have no idea what is going on now. Some of the stuff below is code also for another function just look at the range stuff.

//function prototypes
void readrange(); // range sensor
//void accel(); // accelerometer

  const int xPin = 9;
  const int yPin = 10;
  int analogInPin = A1;

void setup() {
  
  Serial.begin(9600); 
  pinMode(analogInPin,INPUT);
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
  
  
}

void loop() { // call functions
readrange();
//accel();
}


void readrange(){

  float sensorValue; // value of sensor      
  int tmp; // temporary variable for storing value

tmp = analogRead(analogInPin);

if(tmp < 3){
  Serial.println("incorrect value");
}
 sensorValue = (6787.0 /((float)tmp - 3.0)) - 4.0;

Serial.println(sensorValue);
delay(300); // delay so it is readable
}

output while having the sensor looking at something sitting still about 10 cm away;
124.06
31.35
2.65
incorrect value
-2266.33
2.65
2.99
incorrect value
-2266.33
2.65
66.70
incorrect value
-2266.33
4.42
incorrect value
-2266.33
2.65
incorrect value
-2266.33
2.65
etc...

Guys I just figured it out, I just apparently had to power it off of the arduino... I couldn't use batteries or my power supply. I guess these range sensors are really particular.

cprovost:
Guys I just figured it out, I just apparently had to power it off of the arduino... I couldn't use batteries or my power supply. I guess these range sensors are really particular.

I seem to recall these modules create noise on the +5vdc line as they draw current in pulses and can benefit with a capacitor mounted right on the sensor, wired across the +5vdc to ground pins. Try a 20 to 100 ufd electrolytic cap and see if that won't work better on your external power. If you are using a small 9vdc battery then that in itself is a problem as they don't have good current capacity, better to use 6 AA alkaline cells in series.

Lefty

cprovost:
Guys I just figured it out, I just apparently had to power it off of the arduino... I couldn't use batteries or my power supply. I guess these range sensors are really particular.

You should be able to power the sensor itself with a separate power source, but if you do this, you NEED to connect the grounds of the two power sources (ie Arduino's ground and the sensor's ground). Without a common ground, The ADC input is just going to read noise.