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:
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
}
}