Arduino Sharp GP2D120 IR sensor data question

Greetings all,

I am trying to interface the arduino to a sharp GP2D120 rangefinder,
and am having difficulties with the code.

What I want to do is average ten or so samples, store that average
inside of another array of roughly 50 samples, and then write some
code to indicate if the sensor data is increasing or decreasing real
time.

Here's what I've written so far :

// This program will read, average
// sensor data.

//AVGING ROUTINE WORKS!
//Standard Deviation dropped from 8 to 1.

const int pinone = 1;
int sensor1[50];
int metasense[50];
int avgsens;
int senstotal;
int cnt=1;
int cntcnt = 1;
int metacnt=1;
int up, down;

void setup()
{
Serial.begin(9600);
}

void loop()
{
//AVERAGES SENSOR INPUT
sensor1[metacnt] = analogRead(1);
senstotal += sensor1[metacnt];
if (cnt % 50 == 0)
{
avgsens = (int)(senstotal / 50);
metasense[cntcnt] = avgsens;
//Serial.println(metasense[cntcnt]);
senstotal = 0;
metacnt = 0;
//delay(100);
}
for (int j = 1; j==50; j++)
{
Serial.println(metasense[1]);
delay(1000);
}
if (cntcnt%50==0)
{
cntcnt=0;
}
//Serial.println(avgsens);
cnt++;
cntcnt++;
metacnt++;

//DETERMINE WEATHER THE POINTS SLOPE UP
//OR DOWN?
}

I've tried writing a routine to count when
metasense > metasense[i+1] and vice-versa,
and then simply comparing the cases and clearing
the variables, but this does not work.
Can anyone else suggest some code to figure
this out?
Much appreciated.
Charlie

Why not store sample deltas instead of actual samples.

For example:
Sample = 156.
Next Sample, 156 - Store 0.
continue. Next sample, 155. Store -1.

Your array (if the sensor distance is increasing) would be something like:
0,-1,2,2,3,3,3,4,5,6,7,8 ... etc.

Then, you can compare at any point in time with either the start (or any other position) to determine if the distance is increasing or decreasing.

Also, I found that I couldn't trust the sensor values from loop iteration to loop iteration, and I had to read 10 samples each time in the loop to get a more precise result. (I'm measuring liquid in a tank...) I don't know if it is the trouble reading liquid or the timing of reading the sensor between its samples, but this was the only way I could get a reliable reading:

#define OVERSAMPLING 10
int AverageSample()
{
  int iSample=0;
  for(int i=0;i<OVERSAMPLING;i++)
  {
    iSample += analogRead(SensorPort);
    delay(15);
  }
  return iSample/OVERSAMPLING;
}
void loop()
{
    int iSample = AverageSample();
    // work with the value, convert it to centimeters, etc..
}

When I tried what you are, like this:

void loop()
{
    int iSample = analogRead(SensorPort);
    // average out the last 10 reads.
    // work with the value, convert it to centimeters, etc..}

and try to average those samples, the values would be +-10cms or more sometimes within 5ms.