Saturday, January 22, 2011

IR distance sensor on Arduino

The next little device is an IR distance sensor. It comes on a tiny, easy to use board. It operates on 5V and the output voltage which is sent out of the signal pin gets lower the closer an object gets. Theses little sensors are used on robots to measure the distance to an obstacle or to sense edges. The on-board IR LED emits light which is reflected and sensed by an IR sensitive phototransistor. The setup is pretty easy so I don't even need to provide a schematic. Just connect the Vin pin of the board to the 5V port of the Arduino and the GND pin to GND. You can connect the signal pin to any analog port of the Arduino. That's all there is to it.

The source code is straight forward too:
#define signal 0

int adcRawValue;
//You have to determine your normal reflection to set an upper bound.
int normalReflectionValue;

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

void loop() {
  adcRawValue = analogRead(signal);
  //If you get higher values due to interferences, fallback to your upper bound.
  if(adcRawValue > 500) {
    adcRawValue = 500;
  }
  //I mapped my boundaries inverse to a 0-100 scale. (500 = 0; 0 = 100)
  //The closer the Object gets, the lower the ADC value.
  Serial.println(map(adcRawValue, 500, 0, 0, 100));
  delay(50);
}
Here is a demo reading when hovering my finger over the sensor:

No comments:

Post a Comment