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);
}
}