Sharp 2Y0D1
Sparkfun 2Y0A21
Datasheet
Tutorial Link


#include <MIDI.h>
#include <SoftwareSerial.h>
 
/*
  voltage output from Sharp 2Y0821 analog ir sensor .24 - 3.10
  move hand between roughly 3" away to 24"
  voltage drops the further away your hand is
*/
 
int debug = 1;      //print val to serial port
int mode = 0;
int vccPin = 0;
const int sampleSize = 20;
int tails = 4;
 
float lowV = .24;
float highV = 3.10;
int sample[sampleSize];
int ir = 0;
long irSum = 0;
 
int irCCVal = 0;
int irCCch = 1;
int irCCctl = 20;
 
void setup() {
  if(mode == 0){
    Serial.begin(9600);
  }else{
    MIDI.begin();
  }
  multimeter();
}
 
void loop() {
 
  irSensor();
 
  irMap2Midi();
 
  if(mode){
    MIDI.sendControlChange(irCCctl, irCCVal, irCCch);
  }else{
    delay(500);
  }
 
}
void irMap2Midi(){
  ir = constrain(ir, (int)lowV, (int)highV);
  irCCVal = map(ir, (int)lowV, (int)highV, 0, 127);
 
  if(!mode){
    Serial.print("irCCVal = ");
    Serial.println(irCCVal);
  }
}
void irSensor(){
  for(int i=0;i<sampleSize;i++){
    sample[i] = analogRead(vccPin);
    //Serial.println(sample[i]);
  }
 
  for(int i=0;i<sampleSize;i++){
    for(int j=0;j<sampleSize;j++){
      if(sample[j] > sample[j+1]){
        int temp = sample[j];
        sample[j] = sample[j+1];
        sample[j+1] = temp;
      }
    }
  }
 
  for(int  i = tails; i <= sampleSize-tails; i++){
    irSum += sample[i];
    //Serial.println(i);
  }
  //Serial.println(irSum);
 
  int div = (sampleSize - tails) - tails;
  //Serial.println(div);
  ir = (int)(irSum / div);
  irSum = 0;
  //Serial.println(ir);
 
  if(!mode){
    //Serial.print("val = ");
    //Serial.println(ir);
  }
 
}
 
void multimeter(){
  lowV = (lowV / 5.0) * 1023;
  highV = (highV / 5.0) * 1023;
}