IR Sensor + Servos

Hello! I am trying to use a servo and an IR sensor to work together with the goal being for the ir sensor to detect obstacles in front of it and stop spinning the servos accordingly. Since I am only using one servo for now (will later use two and add a chassis for wheels + the body of the robot), I wanted to make sure the ir sensor was detecting objects so I added in a print statement. No matter the object in front of it, the ir sensor only ever says "no object detected, servo spinning". I have double checked my wiring for the sensor and I don't seem to see any problem.

picture: (kind of hard to see)


Schematic:

image

Code:


#include <Servo.h>

// Pin configuration
const int irSensorPin = 2;  // Connect the IR sensor to digital pin 2
const int servoPin = 9;     // Connect the continuous servo to digital pin 9

// Object detection threshold distance in centimeters
const int detectionThreshold = 2;

Servo myServo;

void setup() {
  pinMode(irSensorPin, INPUT);
  myServo.attach(servoPin);
  
  // Initialize the servo to a starting position
  myServo.write(180);  // Set the servo to spin in one direction
  
  Serial.begin(9600);
}

void loop() {
  // Read the IR sensor value
  int irSensorValue = digitalRead(irSensorPin);

  if (irSensorValue == HIGH) {
    // Object detected within 2 cm, stop the servo
    myServo.write(90);  // Stop the continuous rotation
    Serial.println("Object detected! Servo stopped.");
  } else {
    // No object detected, spin the servo continuously
    myServo.write(180);  // Set the servo to spin in one direction
    Serial.println("No object detected. Servo spinning.");
    delay(1000);  // Adjust delay as needed for your application
  }
}

From your schematic you do not have the right sensor. A retroreflective sensor might work but it will be dependent on the reflective surface it is detecting. Your existing sensor has no light source other then room ambient. How does it determine if there is something in front of it. This is generally done with some form of reflection from the object being sensed such as light, sound, RADAR, etc.

Does the sensor return LOW when an object is detected?

Ohh, I was confusing an IR sensor with a distance sensor- when I shine a light on the sensor now it does detect it, thank you !

1 Like

I believe that sensor puts out an analog voltage that indicates distance.
Connect it to A0 and do an analogRead(A0) and print the values.
See what happens when you move you hand back and forth in front of the sensor

1 Like