Traffic counter

Hello! I would like to create person detector counter using ultrasonic sensor.
Currently, I have binary sensor that is switching to true every time the distance is below 1m. But I cannot wrap my head around the counting part. My configuration looks like this:

globals:
 - id: count
   type: int
   restore_value: yes
   initial_value: '0'

binary_sensor:
  - platform: template
    name: "person"
    id: person
    lambda: |-
      if (id(ultrasonic1).state < 1) {
        return true;
      } else {
        return false;
      }

sensor:
  - platform: ultrasonic
    id: ultrasonic1
    trigger_pin: D1
    echo_pin: D2
    name: "Ultrasonic Sensor"
    update_interval: 1s
  - platform: template
    name: "test"
    lambda: |-
      if (id(person).state = 'ON') {
        return id(count) += 1;
      } else {
        return id(count);
      }

The numbers are somehow increasing, but it doesn’t seem to follow the actual template true/false switching and is updated only from time to time.
Any help would be appreciated.

Nobody? :frowning: I think it should be easy in esphome, I just can’t figure it out.
I also need to be able to reset the counter, but I hope this should do the trick:

  - platform: gpio
    pin:
      number: D5
      mode: INPUT_PULLUP
      inverted: yes
    name: "button1"
    id: button1
    device_class: window
    on_release:
      then:
        - lambda: |-
            id(count) = 0;

If you’re planning on using this data for indoor presence detection you need to know the direction of movement. Installing a second sensor and checking the order of them turning on should do the trick. A problem with this set up, however, is you can’t reliably distinguish if that’s a single person or a group of people in front of the sensor, therefore I personally gave up the idea. Now, back to your original question - I would not rely on esphome to hold the counter value and treat the sensor as ethereal - you don’t want to lose the counter data on reboots, do you? Instead, I’d create a template sensor în home assistant or use a custom HACS module for working with variables. I hope this helps.

Found this: Counter - Home Assistant