TOF10120 Template

I’ve created a template to allow usage of the time of flight distance sensor tof10120 with an esp ESP8266 TYWE3S but any ESP with UART should work

The code reads the distance data (mm) being sent from the tof10120 via uart, parses the value and publishes this to a sensor which can be used in home assistant. In my case the RX pin in the ESP was “3” but this may vary for your esp.

esphome:
  name: tof10120

esp8266:
  board: esp01_1m

# Enable Home Assistant API
api:
  password: ""

ota:
  password: ""

wifi:
  ssid: "your_wifi_ssid"
  password: "your_wifi_password"

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Test Esphome Fallback Hotspot"
    password: "fallbackpassword"

captive_portal:

logger:
  level: VERBOSE #makes uart stream available in esphome logstream
  baud_rate: 0 #disable logging over uart

uart:
 - id: uart_bus1
   rx_pin: 3 #This is the TX pin on the esp8266 (tywe3s) https://developer.tuya.com/en/docs/iot/wifie3smodule?id=K9605ua1cx9tv
   baud_rate: 9600
   debug:
     direction: BOTH
     dummy_receiver: true
     after:
      delimiter: "\r\n" #the data is sent in the format XXmm\r\n where XX is an integer value between 0-2000
     sequence:
        - lambda: |-
            static unsigned long lastUpdate = 0;
            #We limit the update rate to 1000ms to reduce sensor update events on home assistant
            if (millis() - lastUpdate >= 1000) {
              lastUpdate = millis();
              UARTDebug::log_string(direction, bytes);
              int distance = 0;
              std::string str(bytes.begin(), bytes.end());
              if (sscanf(str.c_str(), "%dmm", &distance) == 1 ) {
                id(temp1).publish_state(distance);
              }
            }
sensor:
  - platform: template
    name: "Distance Value"
    id: "temp1"
    unit_of_measurement: "mm"
    device_class: "distance"

2 Likes

Nice and thanks for sharing.

I’m curious and can’t see where the update interval is set?

Does the sensor default to sending values at some high rate, and then you further throttle them in your lambda?

I believe data requests would normally be managed on the Tx?

BTW you could also alternatively put a throttle filter on your template sensor and simplify your lambda a bit (same same though I guess)

Hi Mahko_Mahko,

I’ve put the 1 second throttle filter in the lambda

if (millis() - lastUpdate >= 1000) {

I tried adding it in the sensor but it didn’t seem to have any effect and the updates were being sent many times per second to HASSIO, I would say roughly every 100ms

sensor:
  - platform: template
    name: "Distance Value"
    id: "temp1"
    unit_of_measurement: "mm"
    device_class: "distance"
    filters:
      - throttle: 1s

So you tried it like that ^^^^ ?

Yep that’s what I tried first but didn’t seem to do anything