0

I am working of on a Wemos R1 D2 board with VL53L0X Laser Sensor. I need to stop my program after calculating an average of 50 readings but as soon as I try while(1) { } or any other method my output produces garbage.

void loop()
{
  float initial=0,inside=0,outside=0,sum=0,x;
  for (int i = 0; i < 10; i++) {
    x = sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
    sum = sum + x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
  while(1) {};
  Serial.flush();
}
  • I don't see the number 50 anywhere in your code. What happens if you don't try to pause it? Is the output OK then? – Nick Gammon Jul 3 at 6:09
3

ESP8266 based boards do not like being tied up for too long without being able to service any WiFi based tasks.

Having a while(1){} effectively ties up the processor indefinitely. This causes a watchdog reset, and the serial port will print garbage (actually it's the chip's boot message). You don't show your Serial setup.

The ESP8266 can service its WiFi tasks at the end of loop(), during a delay() or if the yield() function is called.

I would suggest adding a delay() or yield() to your while block will fix the problem.

0

There is nothing immediately obviously wrong with your program, but what happens if you do it a bit more "normally"?

By normally, just do nothing after the 10th (or 50th) time through, instead of the infinite loop you are currently executing.

int cntr = 0;
float initial=0,inside=0,outside=0,sum=0,x;

void loop()
{
  if (cntr < 10 /* or 50 */) {
    cntr++;
    x=sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) {
      Serial.print(" TIMEOUT");
    }
    sum=sum+x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
}

My reason for suggesting this is that when I tried an ESP board, there was an enourmous amount of bloatware included in the generated code. There may well be other stuff that needs to happen in the background between calls to the loop method. But you are preventing that from happening with your infinite loop.

However, clearly something is happening in the background because your infinite loop is somehow generating, as you put it, "garbage".

You did not publish the details of sensor library or its methods. Could there be any side affects there? What pins does the sensor connect to?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.