Skip to Content

Arduino Code 

Object detection using Arduino and IR sensor


// Pin definitions

const int irSensorPin = 2;     // IR sensor output connected to digital pin 2

const int ledPin = 13;         // Onboard LED or external LED on pin 13


void setup() {

  pinMode(irSensorPin, INPUT);    // Set IR sensor pin as input

  pinMode(ledPin, OUTPUT);        // Set LED pin as output

  Serial.begin(9600);             // Start serial communication

}


void loop() {

  int sensorValue = digitalRead(irSensorPin);  // Read IR sensor output


  if (sensorValue == LOW) {

    // Object detected

    Serial.println("Object Detected!");

    digitalWrite(ledPin, HIGH);  // Turn on LED

  } else {

    // No object

    Serial.println("No Object.");

    digitalWrite(ledPin, LOW);   // Turn off LED

  }


  delay(200);  // Small delay for stability

}