Closed mariopesch closed 5 months ago
Is serial monitor also ok? If yes, then here is a minimal example that averages all measured values:
#include <Wire.h>
#include <vl53l8cx_class.h>
#define LPN_PIN 4
#define I2C_RST_PIN -1
#define PWREN_PIN 2
VL53L8CX sensor_vl53l8cx_top(&Wire, LPN_PIN, I2C_RST_PIN);
void setup()
{
Serial.begin(9600);
while(!Serial) ;
if (PWREN_PIN >= 0) {
pinMode(PWREN_PIN, OUTPUT);
digitalWrite(PWREN_PIN, HIGH);
delay(10);
}
Wire.begin();
Wire.setClock(1000000); //Sensor has max I2C freq of 1MHz
sensor_vl53l8cx_top.begin();
sensor_vl53l8cx_top.init_sensor();
sensor_vl53l8cx_top.vl53l8cx_set_ranging_frequency_hz(30);
sensor_vl53l8cx_top.vl53l8cx_set_resolution(VL53L8CX_RESOLUTION_8X8);
sensor_vl53l8cx_top.vl53l8cx_start_ranging();
}
void loop()
{
Serial.println(getVl53l8cxAverage());
}
float oldVl53l8cxAverage = -1.0;
float getVl53l8cxAverage() {
VL53L8CX_ResultsData Results;
uint8_t NewDataReady = 0;
uint8_t status;
status = sensor_vl53l8cx_top.vl53l8cx_check_data_ready(&NewDataReady);
if ((!status) && (NewDataReady != 0)) {
sensor_vl53l8cx_top.vl53l8cx_get_ranging_data(&Results);
float sumDistances = 0.0;
float amountDistances = 0.0;
for(int i = 0; i < VL53L8CX_RESOLUTION_8X8*VL53L8CX_NB_TARGET_PER_ZONE; i++) {
if((&Results)->target_status[i]!=255){
sumDistances += (&Results)->distance_mm[i];
amountDistances += 1.0;
}
}
oldVl53l8cxAverage = (amountDistances>0.0) ? sumDistances/amountDistances : 0.0;
}
return oldVl53l8cxAverage;
}
Min and Max functions:
float oldVl53l8cxMin = -1.0;
float getVl53l8cxMin() {
VL53L8CX_ResultsData Results;
uint8_t NewDataReady = 0;
uint8_t status;
status = sensor_vl53l8cx_top.vl53l8cx_check_data_ready(&NewDataReady);
if ((!status) && (NewDataReady != 0)) {
sensor_vl53l8cx_top.vl53l8cx_get_ranging_data(&Results);
float min = 10000.0;
for(int i = 0; i < VL53L8CX_RESOLUTION_8X8*VL53L8CX_NB_TARGET_PER_ZONE; i++) {
if((&Results)->target_status[i]!=255){
float distance = (&Results)->distance_mm[i];
if(min > distance) {
min = distance;
}
}
}
oldVl53l8cxMin = (min==10000.0) ? 0.0 : min;
}
return oldVl53l8cxMin;
}
float oldVl53l8cxMax = -1.0;
float getVl53l8cxMax() {
VL53L8CX_ResultsData Results;
uint8_t NewDataReady = 0;
uint8_t status;
status = sensor_vl53l8cx_top.vl53l8cx_check_data_ready(&NewDataReady);
if ((!status) && (NewDataReady != 0)) {
sensor_vl53l8cx_top.vl53l8cx_get_ranging_data(&Results);
float max = 0.0;
for(int i = 0; i < VL53L8CX_RESOLUTION_8X8*VL53L8CX_NB_TARGET_PER_ZONE; i++) {
if((&Results)->target_status[i]!=255){
float distance = (&Results)->distance_mm[i];
if(max < distance) {
max = distance;
}
}
}
oldVl53l8cxMax = max;
}
return oldVl53l8cxMax;
}
Min function is probably most relevant in most use cases, compared to Max and Average.
closed via #261
Add the new ToF Sensor
@PaulaScharf can you create a minimal example with the distance on the display?