Arduino code when ultrasonic sensor detect object after 5 min buzzer will turn on, after 5 min, if ultrasonic sensor detect object motor will turn on, other wish motor will not turn on
// Define the pins for ultrasonic sensor, buzzer, and motor
const int trigPin = 10; // Trig pin of ultrasonic sensor
const int echoPin = 9; // Echo pin of ultrasonic sensor
const int buzzerPin = 2; // Buzzer pin
const int motorPin = 5; // Motor pin
// Define the distance threshold to detect an object
const int objectThreshold = 280; // Adjust this value as needed
// Define variables to track time
unsigned long startTime = 0;
unsigned long detectionTime = 0;
void setup() {
// Initialize the serial communication for debugging
Serial.begin(9600);
// Initialize the pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(motorPin, OUTPUT);
// Turn off the motor and buzzer initially
digitalWrite(buzzerPin, LOW);
digitalWrite(motorPin, LOW);
}
void loop() {
// Calculate the distance using the ultrasonic sensor
long duration;
int distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2; // Calculate distance in cm
// Print the distance for debugging
Serial.print("Distance: ");
Serial.println(distance);
// Check if an object is detected
if (distance < objectThreshold) {
// If an object is detected, start the timer
if (startTime == 0) {
startTime = millis();
}
// Check if 5 minutes have passed since the object detection (for testing i set it 2 sec.)
if (millis() - startTime >= 2000) {
// Turn on the buzzer
digitalWrite(buzzerPin, HIGH);
}
// Check if 10 minutes have passed since the object detection (for testing i set it 4 sec.)
if (millis() - startTime >= 4000) {
// Turn on the motor
digitalWrite(motorPin, HIGH);
}
} else {
// Reset the timer and turn off the buzzer and motor
startTime = 0;
digitalWrite(buzzerPin, LOW);
digitalWrite(motorPin, LOW);
}
}
My Question : This code is not work my expectation , if i need any change please suggest.