#define IR_SENSOR_PIN A0 // Analog pin for Sharp IR sensor
#define MOTOR_PIN 9 // Digital pin for controlling the motor
void setup() {
pinMode(IR_SENSOR_PIN, INPUT);
pinMode(MOTOR_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
// Read distance from Sharp IR sensor
int distance = readDistance();
// Check if distance is less than 5 centimeters
if (distance < 5) {
// Turn on motor and run for 5 seconds
digitalWrite(MOTOR_PIN, HIGH);
delay(5000); // 5 seconds
// Stop the motor
digitalWrite(MOTOR_PIN, LOW);
}
delay(100); // Delay for stability
}
int readDistance() {
// Read analog value from IR sensor
int sensorValue = analogRead(IR_SENSOR_PIN);
// Convert analog value to distance in centimeters
// You may need to calibrate this according to your sensor and setup
float distance = 9462.0 / (sensorValue - 16.92);
// Print distance for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
return distance;
}