Template Help! create a sensor if an entity is increasing or decreasing over a 2 minute period

Hi, please could I ask the community for some help. Without using the Trend function.
I have a sensor called sensor.temperature and need to know if the value is increasing or decreasing over a 2 minute period.

I even used chat got but it does not work, #not surprised

Any help will be greatly appreciated.

binary_sensor:
  - platform: template
    sensors:
      temperature_change:
        friendly_name: "Temperature Change"
        value_template: >
          {% set duration = 120 %}  # Set the duration in seconds (2 minutes)
          {% set threshold = 0.5 %}  # Set the threshold for significant change

          {% set start_time = as_timestamp(now()) - duration %}
          {% set end_time = as_timestamp(now()) %}

          {% set start_temp = states('sensor.temperature') %}
          {% set end_temp = state_attr('sensor.temperature', 'unit_of_measurement') %}

          {% set change = (end_temp | float - start_temp | float) / duration * 60 %}

          {% if change > threshold %}
            increasing
          {% elif change < -threshold %}
            decreasing
          {% else %}
            stable
          {% endif %}

Binary sensor templates must resolve to true or false.

Either adjust your template or choose a template sensor instead of a binary template sensor.

You should also be using the new template format for new sensors.

Why??? This is what the trend sensor is for isn’t it?

1 Like

Thanks tom_I

Like this? any other pointers?

  - sensor:
      - name: temperature_change
        state: >- 
          {% set period = 120 %}  # 2 minutes in seconds
          {% set entity = 'sensor.ave_tank_temp' %}  
          {% set state1 = state_attr(entity, 'last_updated') %}
          {% set state2 = as_timestamp(now()) %}
          {% set diff = (state2 - state1) | int %}
          {% set temperature1 = states(entity) | float %}
          {% set temperature2 = state(entity) | float %}
          {% set change = temperature2 - temperature1 %}
          {% if diff < period %}
            {% set result = 'unknown' %}
          {% elif change > 0 %}
            {% set result = 'increasing' %}
          {% elif change < 0 %}
            {% set result = 'decreasing' %}
          {% else %}
            {% set result = 'unchanged' %}
          {% endif %}
          {{ result }}
1 Like

See Nick’s answer.
You won’t succeed just with a single template, because you won’t be able to get a state “from the past” (unless you save it in a helper).