support Sharp GP2Y0A02YK0F

////////////////////////////////////////////////
// This Arduino example demonstrates bidirectional operation of a 
// Sharp GP2Y0A02YK0F distance sensor.
////////////////////////////////////////////////

#include "math.h"

unsigned long now       = 0;

const byte ir_num       = 1;
int ir_pin[]            = { A0 };
const byte read_num     = 40;
int reads[ ir_num ][ read_num ];        // the reads from the analog input

int ir_read( int i ){
  static int read_id[] = { 0, 0 };      // the index of the current reading
  static int total[]   = { 0, 0 };      // the running total
  static int average[] = { 0, 0 };      // the average
  total[ i ] = total[ i ] - reads[ i ][ read_id[ i ] ];
  reads[ i ][ read_id[ i ] ] = analogRead( ir_pin[ i ] );
  total[ i ] = total[ i ] + reads[ i ][ read_id[ i ] ];
  read_id[ i ]++;
  if( read_id[ i ] >= read_num ) read_id[ i ] = 0;
  average[ i ] = total[ i ] / read_num;
  return average[ i ];
}

void ir_parse(){
  static int ir_val[] = { 0, 0 };      // variable to store the value coming from the sensor
  static unsigned long ir_start = 0;
  static int ir_step  = 40;
  static int ir_min   = 170;
 
  if( now - ir_start > ir_step ){
    ir_val[ 0 ] = constrain( ir_read( 0 ) - ir_min, 0, 800 );
    if( ir_val[ 0 ] > 0 )Serial.println( ir_val[ 0 ] );
  }
}

//////////////////////////////////////////////////////////////////////////////

void setup() {
  for ( int i = 0; i < ir_num; i++ ) {
    for ( int thisReading = 0; thisReading < read_num; thisReading++ ) {
      reads[ i ][ thisReading ] = 0;
    }
  }  
  Serial.begin(9600);
  Serial.println( "start sharp setup" );
}

//////////////////////////////////////////////////////////////////////////////
void loop(){
  now = millis();
  ir_parse();
}