// Pin Definitions
const int TRIG_PIN = 16;
const int ECHO_PIN = 17;
const int LED_PIN = 23;
// Constants
const int TARGET_DISTANCE = 50;
const int TOLERANCE = 1; // Allows for 49, 50, or 51cm
const long DURATION_REQUIRED = 10000; // 5 seconds
// Variables
unsigned long detectionStartTime = 0;
bool isDetecting = false;
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
}
void loop() {
// 1. Measure Distance
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
int distance = duration * 0.034 / 2;
// 2. Strict Range Logic
// This checks if the distance is specifically between 49 and 51
if (distance >= (TARGET_DISTANCE - TOLERANCE) && distance <= (TARGET_DISTANCE + TOLERANCE)) {
if (!isDetecting) {
detectionStartTime = millis(); // Start timing
isDetecting = true;
Serial.println("Object held at exactly 50cm. Timing...");
} else {
if (millis() - detectionStartTime >= DURATION_REQUIRED) {
digitalWrite(LED_PIN, HIGH); // Turn on after 5 seconds of stability
}
}
} else {
// Distance is < 49 or > 51, so we reset everything
isDetecting = false;
digitalWrite(LED_PIN, LOW);
// Optional: Print distance for debugging
if (distance > 0) {
Serial.print("Out of range: ");
Serial.println(distance);
}
}
delay(100);
}