
//arduino3

#include <Wire.h>
#include <Adafruit_VL53L0X.h>

// Create an instance of the VL53L0X sensor
Adafruit_VL53L0X lox = Adafruit_VL53L0X();

// Define the pin for the output LED/signal
#define LED_PIN 13 

// Define the distance threshold in millimeters
#define THRESHOLD_DISTANCE 275

void setup() {
  Serial.begin(115200); // Start serial communication
  pinMode(LED_PIN, OUTPUT); // Set pin 13 as an output

  // Wait until serial port opens for native USB devices
  while (!Serial) {
    delay(1); 
  }
  Serial.println("VL53L0X Distance Alert");

  // Initialize the sensor
  if (!lox.begin()) {
    Serial.println(F("Failed to find VL53L0X sensor! Check wiring."));
    while (1);
  }
  Serial.println(F("VL53L0X sensor initialized."));

  // Optional: configure the sensor for long range or high speed mode if needed
  // lox.setMeasurementTimingBudget(20000); // for high speed (20ms)
}

void loop() {
  VL53L0X_RangingMeasurementData_t measure;

  // Perform a ranging test (false means no debug data printout)
  lox.rangingTest(&measure, false); 

  // Check if the measurement is valid
  if (measure.RangeStatus != 4) { // RangeStatus 4 means out of range/phase failure
    Serial.print("Distance (mm): ");
    Serial.println(measure.RangeMilliMeter);

    // Check if the distance is less than the threshold
    if (measure.RangeMilliMeter < THRESHOLD_DISTANCE) {
      digitalWrite(LED_PIN, HIGH); // Pull pin 13 HIGH
    } else {
      digitalWrite(LED_PIN, LOW); // Pull pin 13 LOW
    }
  } else {
    Serial.println("Out of range");
    digitalWrite(LED_PIN, LOW); // Turn off pin 13 if no valid reading
  }

  delay(100); // Wait between measurements
}
