Convert VL53L0X 'NaN' readings to specific value

Hello,

I am upgrading my garage door sensor from an ultrasonic HC-SR04 sensor to a TOF VL52L0X sensor. The sensor measures the distance from the ceiling down to the bottom.

The sensor works fine with ESPHome and home assistant, but it only has a range of max 2m. For my purpose this is ok, as I just want to measure like 10cm (garage door is open), 1.4m (garage door is closed and the car is in the garage) and everything above 1.4m equals garage door is closed with no car inside.

But: The sensor sits about 2.5m above the ground, so every measurement above 2m is giving me a “NaN” reading. I created a template sensor in home assistant to convert these readings to 2m, but I also want to filter the sensor beforehand via a moving quantile, so I don’t get any peaks (see my previous post HC-SR04 Ultrasonic Sensor peaks).

Now, because the sensor is returning NaN as a value when it measures more than 2m, it won’t be calculated within the quantile. So when the sensors goes from 10cm to more then 2m, the value returned through the quantile to home assistant will still be 10cm.

Is there any way to tell the sensor “if value=nan then value=2.0”?

I tried using the calibrate_linear filter but that did not work.

Last option would be to switch to the VL53l1X.

I hope you understand my problem :smiley:

Thanks!

Use filter-out? I don’t know if you can use NaN as the number to filter…

Yes, I can use NaN as the number, but then I am not getting any readings and the sensor won’t update at all.

Look at the esphome docs for template sensor.

Or the lambda filter:

Good call, I missed that.

Yes, that’s it!

Now my code looks like the following and it works like a charm:

sensor:
  - platform: vl53l0x
    name: "garagentor"
    update_interval: 1s
    long_range: true
    filters:
      - lambda: if (isnan(x)) {  return 2.0; } return x; 
      - quantile:
          window_size: 10

Thank you!

4 Likes