Example Code for Arduino-IR Distance Detection

Last revision 2025/12/20

This article offers a detailed guide on implementing IR distance detection using Arduino, including hardware and software setup, wiring diagrams, and sample code for precise distance measurement.

Wiring Diagram

sen0143_connection

Sample Code


// connect gp2d120x to A1
#define pin A1

void setup () {
 Serial.begin (9600);
 pinMode(pin, INPUT);
}

void loop () {
  uint16_t value = analogRead (pin);
  double distance = get_IR (value); //Convert the analog voltage to the distance
  Serial.println (value);                 //Print the data to the arduino serial monitor
  Serial.print (distance);
  Serial.println (" cm");
  Serial.println ();
  delay (500);                            //Delay 0.5s
}

//return distance (cm)
double get_IR (uint16_t value) {
  if (value < 16)  value = 16;
  return 2076.0 / (value - 11.0);
}

Was this article helpful?

TOP