Simple counter template sensor

Hello,

I’m trying to create a counter sensor that every minute increments its value with 1. The only reason to make this sensor is for learning purposes.

I have this code:

sensor:
  - platform: template
    sensors:
      test:
        entity_id:
          - sensor.time
        value_template: >
          {% if states('sensor.test') | int(default=0) == 0 %}
            {% set acum = 1 %}
          {% else %}
            {% set acum = states('sensor.test') | int(default=0) + 1 %}
          {% endif %}
          {{ acum }}

The problem is that the sensor doesn’t get updated every minute, and I don’t get the point …

Any help will be welcome.

I don’t know why the code I wrote does not work, but this one works:

template:
  - trigger:
    - platform: time_pattern
      # You can also match on interval. This will match every 1 minutes
      minutes: "/1"
    sensor:
      - name: "test"
        state: >
          {% if states('sensor.test') | int(default=0) == 0 %}
             {% set acum = 1 %}
          {% else %}
            {% set acum = states('sensor.test') | int(default=0) + 1 %}
          {% endif %}
          {{ acum }}

So, the problem seems related to updating the sensor.

“entity_id: xxx” has been deprecated for sensors a long time ago.

I’m surprised you didn’t get a notification in your logs about it. But then again maybe its been so long that they don’t even give the warning anymore.

the only way a sensor gets updated is if one of the referenced entities changes state and since the only entity you referenced is itself then it never gets updated.

you could have added the following to the template and it should update every minute (I think…):

        value_template: >
          {% set update = states.('sensor.time') %}
          {% if states('sensor.test') | int(default=0) == 0 %}
            {% set acum = 1 %}
          {% else %}
            {% set acum = states('sensor.test') | int(default=0) + 1 %}
          {% endif %}
          {{ acum }}

What are you intending to learn by creating a sensor that mimics the system clock?

The sensor I wanted to make was not as simple as a counter, but as it din’t update, I stripped down the code until the simplest one.

Now I know how sensors update :slight_smile:

The sensor I want to make is what I describe in this post: https://community.home-assistant.io/t/getting-last-n-values-of-a-sensor-to-create-a-weighted-mean-sensor/367699/4?u=miguelpucela

I’d like to create a sensor with the exponentially descreasing weighted average of another sensor. The problem I see is that new value of the sensor will depend on previous value. If HA is restarted, sensor value with the historic evolution is lost. I suppose this can be avoided by saving the sensor’s actual state in an input_number.

Maybe what’s needed isn’t a Template Sensor but an automation.

1 Like

Thank for your feedback. You’re right, it’s better an automation. I’ll try it.