Working with Timer and VL53L1X

Hello all, need your help for a sec

I'm trying to create a code that measure distance using VL53L1X based on push button and do something if it fit certain distance, meanwhile the timer in the background will do a countdown for 20s and after reaching 0 it will do another thing.
But things can't seem to be working properly as the sensor only measure in a period and proceed to do nothing and wait until the countdown reach 0.

Code attached below

#include <Wire.h>
#include <VL53L1X.h>
#include <Countimer.h>
VL53L1X sensor;
Countimer timer;

bool condition;
bool firstloop = true;
unsigned int h = 0, m = 0, s = 20;

void complete()
{
  delay(500);
  digitalWrite(6,LOW);
  delay(500);
  digitalWrite(7,HIGH);
  	exit(0);
}

void setup() {
  // put your setup code here, to run once:

pinMode(2, INPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
Serial.begin(115200);
  
digitalWrite(8, HIGH);

timer.setCounter(h,m,s,timer.COUNT_DOWN,complete);
timer.setInterval(refresh_time,1000);

 while (!Serial) {}
  Wire.begin();
  Wire.setClock(400000); // use 400 kHz I2C

  sensor.setTimeout(500);
  if (!sensor.init())
  {
    Serial.println("Failed to detect and initialize sensor!");
    while (1);
  }
  sensor.setDistanceMode(VL53L1X::Long);
  sensor.setMeasurementTimingBudget(50000);

  sensor.startContinuous(50);
}

void refresh_time()
{
  Serial.println(timer.getCurrentTime());
}


void loop() {
  
  timer.run();

  if(digitalRead(2) == HIGH && firstloop == true){ 
    doThisOnce();
    firstloop = false;
    }
  if(digitalRead(2) == HIGH){
       timer.start();
  }
}


void doThisOnce()
{ 
  int16_t dist;
  dist = sensor.read();

    digitalWrite(9, HIGH);
    delay(5000);

    if ((dist <= 500) && (dist >= 100)){  
    Serial.print("CLOSE");
    Serial.print(dist);
    digitalWrite(6, HIGH);
    delay(500);  
    }
    
    else{
      digitalWrite(6, LOW);
    }
}

Is your button (pin 2) wired correctly?
Are your LEDs wired correctly?
Do you see any LED activity?
Do you see "CLOSE" or any distance? "Nothing" is not descriptive.

Put some Serial.print(); lines in doThisOnce(), refresh_time(), and complete()... to tell you where your program is running.

Show a drawing of your project.

the button already wired correctly and the arduino already run the program, LED also light up. But the sensor only measure distance once, not continuously during the whole 20s countdown.

Schematic attached below.

Remove the timer. Adjust the VL53L1X to your needs. Re-introduce the timer.

Four times through doThisOnce() is ten seconds... and you have no debounce on your button press.

This indicates "it does not run."

You know what, it's already fixed by declaring

int16_t dist = sensor.readRangeContinuousMillimeters();

inside the measuring void

thank you for the response

Makes sense.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.