const int trigPin = 10;
const int echoPin = 11;
const int ledPin = 7;
const long minDistance = 200; // 5 meters in cm
const long maxDistance = 300; // 8 meters in cm
const long minMovement = 5; // minimum movement in cm
const unsigned long ledOnTime = 3000; // LED on time in milliseconds
long lastDistance = 0;
unsigned long lastMovementTime = 0;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
long duration, distance;
// Send a pulse to the HC-SR04
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the pulse duration
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
distance = duration * 0.034 / 2;
// Print the distance for debugging
Serial.print("Lidar1 - Distance: ");
Serial.print(distance);
Serial.print("cm\t");
Serial.print("Strength: 50");
Serial.print("\t");
Serial.println("Temp: 4");
// Check if the distance is within the specified range
if (distance >= minDistance && distance <= maxDistance) {
// Check for significant movement
if (abs(distance - lastDistance) >= minMovement) {
lastMovementTime = millis(); // Update the last movement time
digitalWrite(ledPin, HIGH); // Turn on the LED
}
}
// Turn off the LED if no movement has been detected within the on time
if (millis() - lastMovementTime >= ledOnTime) {
digitalWrite(ledPin, LOW);
}
// Update the last distance
lastDistance = distance;
// Small delay to avoid excessive sensor polling
delay(100);
}