Automatic sanitizer using esphome + nodemcu + ultrasonic sensor

I want to make a automatic sanitizer using esphome + nodemcu + ultrasonic sensor + sprayer with motor ,
i have successfully integrated all these items and started it and it is working but there is some problem ,

sometime when the device is restarted or switched off and on , then
the sprayer starts automatically and it does not stops ,
and
sometime the ultrasonic sensor starts to work reverse ,

please help

esphome:
  name: sanitizer_node
  platform: ESP8266
  board: nodemcuv2
  
wifi:
  networks:

    
  # Optional manual IP
  manual_ip:


  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Sanitizer Node Fallback Hotspot"
 
captive_portal:

# Enable logging
logger:

# Enable Home Assistant API
api:
  password: 

ota:
  password:
  
web_server:
  port: 80  

sensor:
  - platform: ultrasonic
    id: ultrasonic_sensor
    trigger_pin: GPIO4
    echo_pin: GPIO5
    name: "Sanitizer Sensor"
    update_interval: 1s
    filters:
      filter_out: nan
    timeout: 3m    

switch:
- platform: gpio
  pin: 
    number: GPIO14
    inverted: yes
  restore_mode: always off
  name: "Sanitizer Botton"
  id: relay1
    
binary_sensor:
    
  - platform: template
    name: "Sanitizer"
    device_class: presence
#    filters:
#      - invert:
#      - delayed_on: 100ms
#      - delayed_off: 100ms
#      - delayed_on_off: 100ms    
    lambda: |-
      if (id(ultrasonic_sensor).state < 0.9) {
        // in range
        return true;
      } else {
        // out of range
        return false;
      }     
    on_state:
      then:
        - switch.toggle: relay1  


Don’t toggle in on_state, use on_press and on_release. That will be how it’s getting reversed and maybe the other issues as well.

I’m surprised it let you compile this:

restore_mode: always off

It should be:

restore_mode: ALWAYS_OFF

no this did not solve my problem , as i cannot use on_press or on_release as it is a sensor ,

both are correct as it shows (ALWAYS_OFF) while validation .

It’s not documented.

Yes you can, you made a binary sensor.

I’m referring to the presence binary_sensor.