TMF8820 without delay

Wondering if anyone has tried using the TMF8820 without delays. I removed the delay in example 2 and changed it to millis but if I have any code outside the millis if statement the sensor seems to not read values. I want to use the sensor with arduino cloud which doesn’t like delays.

  • Use a state machine approach: Instead of relying on delays, implement a simple state machine that manages the sensor’s different states (initializing, measuring, processing, etc.). This can help ensure the sensor has enough time to complete each operation without blocking other code execution.
  • Adjust the timing: Even when using millis(), make sure you’re allowing enough time between measurements. The sensor might need a certain minimum time between readings to function correctly.
  • Check the sensor’s busy state: Many ToF sensors have a way to check if they’re busy processing a measurement. Implement this check in your code to ensure you’re not trying to start a new measurement while the previous one is still being processed.
  • Use interrupts: If the TMF8820 supports interrupt-driven operation, consider using that instead of polling. This can be more efficient and allow for better integration with other code.
  • Optimize other code: Ensure that any code outside the sensor reading routine is as efficient as possible. Heavy processing elsewhere might interfere with the sensor’s timing requirements.

Something like this might be a good starting scaffold to try:

#include <Wire.h>
#include <SparkFun_TMF8820_Arduino_Library.h>

TMF8820 myTMF8820;

const unsigned long SENSOR_INTERVAL = 100; // Adjust as needed
unsigned long previousMillis = 0;
bool measurementStarted = false;

void setup() {
  Wire.begin();
  Serial.begin(115200);
  
  while (!Serial)
    ;

  if (myTMF8820.begin() == false) {
    Serial.println(F("TMF8820 not detected. Check wiring. Freezing..."));
    while (1)
      ;
  }
  
  // Configure the sensor for your specific needs
  myTMF8820.setMeasurementMode(TMF8820_MEAS_MODE_SINGLE);
  myTMF8820.setCalibrationMode(TMF8820_CALIBRATION_FACTORY);
}

void loop() {
  unsigned long currentMillis = millis();

  // Your other non-blocking code here
  // ...

  // Check if it's time to take a sensor reading
  if (!measurementStarted && (currentMillis - previousMillis >= SENSOR_INTERVAL)) {
    startMeasurement();
    measurementStarted = true;
    previousMillis = currentMillis;
  }

  // Check if measurement is complete
  if (measurementStarted && myTMF8820.isDataReady()) {
    readSensorData();
    measurementStarted = false;
  }

  // More of your non-blocking code here
  // ...
}

void startMeasurement() {
  myTMF8820.startMeasurement();
}

void readSensorData() {
  uint16_t distance = myTMF8820.getDistance();
  uint16_t confidence = myTMF8820.getConfidence();
  
  Serial.print(F("Distance: "));
  Serial.print(distance);
  Serial.print(F(" mm, Confidence: "));
  Serial.println(confidence);
}