#define LED_PIN 5 #define SENSOR_PIN 4 #define THRESHOLD_DROP 1.05 // Trigger if signal drops 5% of baseline #define MIN_DURATION 10 // Microseconds #define MAX_DURATION 1000000 // 1 second unsigned long lastBaselineUpdate = 0; const unsigned long baselineInterval = 1000; // ms int baseline = 0; void setup() { Serial.begin(9600); pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, HIGH); // LED always on baseline = readSensorBaseline(); Serial.print("Initial baseline: "); Serial.println(baseline); } void loop() { // Update baseline every 1 second if (millis() - lastBaselineUpdate >= baselineInterval) { int newBaseline = readSensorBaseline(); // Optional: Only update if no ball is detected if (newBaseline < baseline * 1.1) { baseline = newBaseline; //Serial.print("Updated baseline: "); //Serial.println(baseline); } lastBaselineUpdate = millis(); } int sensorValue = analogRead(SENSOR_PIN); unsigned long startTime = 0; // Trigger if signal rises (since your signal is normally low) if (sensorValue > baseline * THRESHOLD_DROP) { startTime = micros(); while (analogRead(SENSOR_PIN) > baseline * THRESHOLD_DROP) { if ((micros() - startTime) > MAX_DURATION) break; } unsigned long duration = micros() - startTime; if (duration >= MIN_DURATION && duration <= MAX_DURATION) { Serial.print("Ball detected! Duration: "); Serial.print(duration); Serial.println(" us"); } } delayMicroseconds(100); } int readSensorBaseline() { const int samples = 10; long total = 0; for (int i = 0; i < samples; i++) { total += analogRead(SENSOR_PIN); delay(5); // Small delay between samples } return total / samples; }