### Complete Working Example with Error Handling (C++) Source: https://context7.com/adafruit/adafruit_vl53l1x/llms.txt This code snippet provides a complete working example of using the Adafruit VL53L1X distance sensor with Arduino. It includes proper initialization, error handling, a measurement loop, and graceful shutdown. It utilizes the Adafruit_VL53L1X and Wire libraries. ```cpp #include "Adafruit_VL53L1X.h" #include #define IRQ_PIN 2 #define XSHUT_PIN 3 #define MEASUREMENT_INTERVAL 50 Adafruit_VL53L1X vl53 = Adafruit_VL53L1X(XSHUT_PIN, IRQ_PIN); unsigned long lastMeasurement = 0; void setup() { Serial.begin(115200); while (!Serial) delay(10); Serial.println("Adafruit VL53L1X Distance Sensor"); Serial.println("==============================="); // Initialize I2C Wire.begin(); Wire.setClock(400000); // 400kHz I2C // Initialize sensor if (!vl53.begin(0x29, &Wire)) { Serial.print("ERROR: Sensor initialization failed! Error code: "); Serial.println(vl53.vl_status); while (1) { digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); delay(500); } } // Verify sensor ID uint16_t sensorID = vl53.sensorID(); if (sensorID != 0xEACC) { Serial.print("ERROR: Invalid sensor ID: 0x"); Serial.println(sensorID, HEX); while (1) delay(10); } Serial.print("Sensor ID: 0x"); Serial.println(sensorID, HEX); // Configure sensor if (!vl53.setTimingBudget(50)) { Serial.println("WARNING: Failed to set timing budget"); } Serial.print("Timing budget: "); Serial.print(vl53.getTimingBudget()); Serial.println(" ms"); // Start ranging if (!vl53.startRanging()) { Serial.print("ERROR: Failed to start ranging! Error code: "); Serial.println(vl53.vl_status); while (1) delay(10); } Serial.println("Ranging started successfully"); Serial.println(); } void loop() { // Non-blocking measurement if (millis() - lastMeasurement >= MEASUREMENT_INTERVAL) { if (vl53.dataReady()) { int16_t distance = vl53.distance(); if (distance == -1) { Serial.print("ERROR: Distance measurement failed! Error code: "); Serial.println(vl53.vl_status); } else { // Valid measurement Serial.print("Distance: "); Serial.print(distance); Serial.println(" mm"); // Classify distance if (distance < 100) { Serial.println(" Status: VERY CLOSE"); } else if (distance < 500) { Serial.println(" Status: CLOSE"); } else if (distance < 1000) { Serial.println(" Status: MEDIUM"); } else { Serial.println(" Status: FAR"); } } // Clear interrupt for next measurement if (!vl53.clearInterrupt()) { Serial.println("WARNING: Failed to clear interrupt"); } lastMeasurement = millis(); } } } ``` -------------------------------- ### Start and Stop VL53L1X Ranging Measurements Source: https://context7.com/adafruit/adafruit_vl53l1x/llms.txt Configures and starts continuous ranging measurements on the VL53L1X sensor. It also allows setting the timing budget for measurements and includes a function to stop ranging. This requires the Adafruit_VL53L1X and Wire libraries. ```cpp void setup() { Serial.begin(115200); Wire.begin(); Adafruit_VL53L1X vl53 = Adafruit_VL53L1X(); if (!vl53.begin(0x29, &Wire)) { Serial.println("Sensor init failed!"); while (1); } // Start ranging operations if (!vl53.startRanging()) { Serial.print("Couldn't start ranging: "); Serial.println(vl53.vl_status); while (1) delay(10); } Serial.println("Ranging started"); // Set timing budget (valid values: 15, 20, 33, 50, 100, 200, 500 ms) if (!vl53.setTimingBudget(50)) { Serial.println("Failed to set timing budget"); } Serial.print("Timing budget: "); Serial.println(vl53.getTimingBudget()); } void loop() { // Perform measurements } void stopSensor() { // Stop ranging when done if (!vl53.stopRanging()) { Serial.println("Failed to stop ranging"); } } ``` -------------------------------- ### Perform VL53L1X Sensor Calibration (C++) Source: https://context7.com/adafruit/adafruit_vl53l1x/llms.txt This C++ function demonstrates how to perform offset and crosstalk calibration for the Adafruit VL53L1X sensor. It guides through placing targets, initiating calibration, and setting/reading calibration values. This requires the Adafruit VL53L1X library and an active I2C connection. ```cpp void performCalibration() { Adafruit_VL53L1X vl53 = Adafruit_VL53L1X(); VL53L1X* sensor = &vl53; vl53.begin(0x29, &Wire); vl53.startRanging(); // Offset calibration // Place a grey 17% reflectance target at 100mm Serial.println("Place target at 100mm and wait..."); delay(5000); int16_t offsetValue = 0; int8_t status = sensor->VL53L1X_CalibrateOffset(100, &offsetValue); if (status == 0) { Serial.print("Offset calibration successful: "); Serial.print(offsetValue); Serial.println(" mm"); } else { Serial.print("Offset calibration failed: "); Serial.println(status); } // Crosstalk calibration // Point sensor at dark target beyond max range or cover lens Serial.println("Cover lens and wait..."); delay(5000); uint16_t xtalkValue = 0; status = sensor->VL53L1X_CalibrateXtalk(600, &xtalkValue); if (status == 0) { Serial.print("Xtalk calibration successful: "); Serial.print(xtalkValue); Serial.println(" cps"); } else { Serial.print("Xtalk calibration failed: "); Serial.println(status); } // Manually set calibration values (from previous calibration) sensor->VL53L1X_SetOffset(-25); sensor->VL53L1X_SetXtalk(150); // Read current calibration values int16_t currentOffset; uint16_t currentXtalk; sensor->VL53L1X_GetOffset(¤tOffset); sensor->VL53L1X_GetXtalk(¤tXtalk); Serial.print("Current offset: "); Serial.println(currentOffset); Serial.print("Current xtalk: "); Serial.println(currentXtalk); } ``` -------------------------------- ### Advanced Configuration with ROI and Thresholds for VL53L1X in C++ Source: https://context7.com/adafruit/adafruit_vl53l1x/llms.txt This example configures Region of Interest (ROI) for focused measurements and distance thresholds for interrupts on the VL53L1X sensor. It uses the Adafruit_VL53L1X library and Wire, with inputs for ROI size (min 4x4), threshold windows (in mm), and mode (short/long range), outputting current settings via serial. Limitations: Smaller ROI narrows field of view but may require calibration; long mode performs better in low light up to 4m. ```cpp void advancedConfiguration() { Adafruit_VL53L1X vl53 = Adafruit_VL53L1X(); VL53L1X* sensor = &vl53; vl53.begin(0x29, &Wire); // Set ROI (Region of Interest) // X and Y define the size of the measurement area // Smaller ROI = narrower field of view, more focused beam // Minimum ROI size = 4x4 uint16_t roiX = 8, roiY = 8; sensor->VL53L1X_SetROI(roiX, roiY); // Get current ROI uint16_t currentX, currentY; sensor->VL53L1X_GetROI_XY(¤tX, ¤tY); Serial.print("ROI: "); Serial.print(currentX); Serial.print("x"); Serial.println(currentY); // Set distance threshold for interrupt generation // Window modes: 0=below low, 1=above high, 2=out of window, 3=in window uint16_t lowThresh = 100; // 100mm uint16_t highThresh = 300; // 300mm uint8_t windowMode = 2; // Trigger when out of 100-300mm range sensor->VL53L1X_SetDistanceThreshold(lowThresh, highThresh, windowMode, 1); // Set distance mode (1=short, 2=long) // Short mode: max 1.3m, better ambient immunity // Long mode: up to 4m in darkness sensor->VL53L1X_SetDistanceMode(2); vl53.startRanging(); } ``` -------------------------------- ### Configuring Interrupt Polarity for VL53L1X Sensor in C++ Source: https://context7.com/adafruit/adafruit_vl53l1x/llms.txt This code sets up interrupt polarity for the VL53L1X sensor to match hardware, enabling new data detection via high or low signals. It depends on the Adafruit_VL53L1X library, Wire, and digital pin 2 for interrupts, with boolean inputs for polarity and outputs via serial. Limitations: Requires proper ISR setup and clearing interrupts to avoid false triggers. ```cpp void setupInterrupts() { Adafruit_VL53L1X vl53 = Adafruit_VL53L1X(-1, 2); vl53.begin(0x29, &Wire); // Set interrupt polarity // true = active high (default) // false = active low if (!vl53.setIntPolarity(false)) { Serial.println("Failed to set interrupt polarity"); } // Read current interrupt polarity bool polarity = vl53.getIntPolarity(); Serial.print("Interrupt polarity: "); Serial.println(polarity ? "Active High" : "Active Low"); // Clear any pending interrupts vl53.clearInterrupt(); vl53.startRanging(); } // Interrupt service routine volatile bool dataReady = false; void dataReadyISR() { dataReady = true; } void setupWithInterrupt() { pinMode(2, INPUT); attachInterrupt(digitalPinToInterrupt(2), dataReadyISR, FALLING); Adafruit_VL53L1X sensor = Adafruit_VL53L1X(-1, 2); sensor.begin(0x29, &Wire); sensor.setIntPolarity(false); sensor.startRanging(); } void loopWithInterrupt() { if (dataReady) { dataReady = false; int16_t dist = vl53.distance(); Serial.println(dist); vl53.clearInterrupt(); } } ``` -------------------------------- ### Initialize VL53L1X Sensor with I2C Source: https://context7.com/adafruit/adafruit_vl53l1x/llms.txt Initializes the VL53L1X sensor via I2C communication and verifies its ID. This function performs a hardware reset and sets up the sensor for operation. It requires the Wire library and defines pins for shutdown and interrupt. ```cpp #include "Adafruit_VL53L1X.h" #include #define XSHUT_PIN 3 #define IRQ_PIN 2 Adafruit_VL53L1X vl53 = Adafruit_VL53L1X(XSHUT_PIN, IRQ_PIN); void setup() { Serial.begin(115200); Wire.begin(); // Initialize sensor with default I2C address 0x29 if (!vl53.begin(0x29, &Wire)) { Serial.print("Error on init: "); Serial.println(vl53.vl_status); while (1) delay(10); } // Read and verify sensor ID (should be 0xEACC) Serial.print("Sensor ID: 0x"); Serial.println(vl53.sensorID(), HEX); } void loop() { // Main code here } ``` -------------------------------- ### Configuring Timing Budget for VL53L1X Sensor in C++ Source: https://context7.com/adafruit/adafruit_vl53l1x/llms.txt This snippet demonstrates how to adjust the timing budget of the Adafruit VL53L1X sensor to balance measurement accuracy and speed. It requires the Adafruit_VL53L1X library and Wire library, with inputs as budget values in milliseconds (15-500 ms) and outputs the current budget via serial. Limitations include shorter budgets reducing accuracy while longer ones slow down measurements. ```cpp void setupTimingBudget() { Adafruit_VL53L1X sensor = Adafruit_VL53L1X(); sensor.begin(0x29, &Wire); sensor.startRanging(); // Valid timing budgets: 15, 20, 33, 50, 100, 200, 500 ms // Shorter budget = faster measurements but less accurate // Longer budget = slower measurements but more accurate // Fast mode (less accurate) sensor.setTimingBudget(15); // Balanced mode (recommended for most applications) sensor.setTimingBudget(50); // High accuracy mode (best for static measurements) sensor.setTimingBudget(200); // Get current timing budget uint16_t currentBudget = sensor.getTimingBudget(); Serial.print("Current timing budget: "); Serial.print(currentBudget); Serial.println(" ms"); } ``` -------------------------------- ### Monitor VL53L1X Signal Quality and Ambient Light (C++) Source: https://context7.com/adafruit/adafruit_vl53l1x/llms.txt This C++ function continuously monitors the Adafruit VL53L1X sensor's performance, reporting distance, range status, signal rate, ambient light levels, and SPAD count. It includes basic quality assessment logic and requires the Adafruit VL53L1X library and an active I2C connection. ```cpp void monitorSignalQuality() { Adafruit_VL53L1X vl53 = Adafruit_VL53L1X(); VL53L1X* sensor = &vl53; vl53.begin(0x29, &Wire); vl53.startRanging(); vl53.setTimingBudget(100); while (1) { if (vl53.dataReady()) { int16_t distance = vl53.distance(); // Get range status (0=valid, 1=sigma fail, 2=signal fail, 7=wraparound) uint8_t rangeStatus; sensor->VL53L1X_GetRangeStatus(&rangeStatus); // Get signal rate in kcps (kilo counts per second) uint16_t signalRate; sensor->VL53L1X_GetSignalRate(&signalRate); // Get ambient light rate in kcps uint16_t ambientRate; sensor->VL53L1X_GetAmbientRate(&ambientRate); // Get number of active SPADs uint16_t spadCount; sensor->VL53L1X_GetSpadNb(&spadCount); // Get signal per SPAD uint16_t signalPerSpad; sensor->VL53L1X_GetSignalPerSpad(&signalPerSpad); Serial.print("Distance: "); Serial.print(distance); Serial.print(" mm | Status: "); Serial.print(rangeStatus); Serial.print(" | Signal: "); Serial.print(signalRate); Serial.print(" kcps | Ambient: "); Serial.print(ambientRate); Serial.print(" kcps | SPADs: "); Serial.println(spadCount); // Quality assessment if (rangeStatus == 0 && signalRate > 1000) { Serial.println("Measurement quality: GOOD"); } else if (rangeStatus == 1) { Serial.println("Measurement quality: POOR (sigma fail)"); } else if (rangeStatus == 2) { Serial.println("Measurement quality: POOR (signal fail)"); } vl53.clearInterrupt(); } delay(100); } } ``` -------------------------------- ### Temperature Compensation with VL53L1X (C++) Source: https://context7.com/adafruit/adafruit_vl53l1x/llms.txt This code snippet demonstrates how to perform temperature compensation with the Adafruit VL53L1X distance sensor. It checks for significant temperature changes and recalibrates the sensor when necessary to maintain measurement accuracy. It depends on an external temperature sensor and the Adafruit_VL53L1X library. ```cpp void handleTemperatureChanges() { Adafruit_VL53L1X vl53 = Adafruit_VL53L1X(); VL53L1X* sensor = &vl53; vl53.begin(0x29, &Wire); vl53.startRanging(); float lastCalibrationTemp = 25.0; float currentTemp = 25.0; // In main loop while (1) { // Read temperature from external sensor currentTemp = readTemperatureSensor(); // If temperature changed by more than 8°C if (abs(currentTemp - lastCalibrationTemp) > 8.0) { Serial.println("Temperature changed significantly, recalibrating..."); // Stop ranging before calibration vl53.stopRanging(); // Perform temperature update if (sensor->VL53L1X_StartTemperatureUpdate() == 0) { Serial.println("Temperature calibration complete"); lastCalibrationTemp = currentTemp; } else { Serial.println("Temperature calibration failed"); } // Restart ranging vl53.startRanging(); } // Normal measurement loop if (vl53.dataReady()) { int16_t dist = vl53.distance(); Serial.println(dist); vl53.clearInterrupt(); } delay(100); } } // Placeholder for external temperature sensor float readTemperatureSensor() { return 25.0; } ``` -------------------------------- ### Read VL53L1X Distance Measurements Source: https://context7.com/adafruit/adafruit_vl53l1x/llms.txt Reads distance measurements from the VL53L1X sensor in millimeters. It checks for data readiness using dataReady() and retrieves the distance value. Errors are reported, and the interrupt is cleared after each successful reading. Requires Adafruit_VL53L1X and Wire libraries. ```cpp #include "Adafruit_VL53L1X.h" Adafruit_VL53L1X vl53 = Adafruit_VL53L1X(3, 2); void setup() { Serial.begin(115200); Wire.begin(); if (!vl53.begin(0x29, &Wire)) { Serial.println("Init failed!"); while (1); } vl53.startRanging(); vl53.setTimingBudget(50); } void loop() { int16_t distance; // Check if new data is ready if (vl53.dataReady()) { // Read distance measurement distance = vl53.distance(); if (distance == -1) { // Error occurred during measurement Serial.print("Measurement error: "); Serial.println(vl53.vl_status); } else { // Valid distance reading Serial.print("Distance: "); Serial.print(distance); Serial.println(" mm"); } // Clear interrupt to prepare for next reading vl53.clearInterrupt(); } delay(50); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.