Introduction: How to Hack Digital Infra Red Switch to Make Analogic IR Distance Sensor

You will need a static digital (0-1) IR switch 
An Arduino 
And See the video :))
-------
Idea:
The idea is to change the emitter voltage and detect distance based on map function ...
-------
Code
-------
#define pIRR 10
#define pIRE 3
//speed of detection Ms
int Captspeed = 50;

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

     pinMode(pIRR, INPUT); 

     pinMode(pIRE, OUTPUT);
     pinMode(11, OUTPUT);
}

float voltMin  =1.9;
float voltMax  = 5;
void loop() {
  
    float voltage = voltMin;
    int steps = 0;
    while(voltage <= voltMax)
    {
      int av = ConvertVoltToAnalog(voltage);
      voltage += 0.1;
      analogWrite(pIRE,av);
      delay(5);
      int comingIR = digitalRead(pIRR);
      delay(1);
      if(comingIR == 0)
      {
          digitalWrite(11,HIGH);
        voltage = 99;
        break;
      
      }
        digitalWrite(11,LOW);
      steps ++; 
      delay(25);
    }
   
    float distance = 99;
    if(steps !=0 && voltage == 99)
       {
         distance = map(steps,1,31,-4,31);
         Serial.print("Distance To Object = ");
         Serial.println(distance);
     
       }
    else
     {
       Serial.println("Nothing detected!");
       digitalWrite(11,LOW); 
      }
      
   
    delay(Captspeed/2);   
    analogWrite(pIRE,0);
    delay(Captspeed/2);

}


int ConvertVoltToAnalog(int voltage)
{
   int res = 0;
   res = map(voltage,0,5,0,255);
  return res;
}

Comments