Compare last sensor value with new one

Hi everyone,

i want to turn on a fan in the bathroom when the humidity there changes by more or equals 10%. In normal code it would be very simple:

if(sensor.bathroom_humidity.current_state - sensor_bathroom_humidity.last_state >= 10) {
    turn_on(fan.bathroom_fan)
}

I know that there is “trigger.from_state.state” but in my understanding it is only available in the service_template section of actions.
So how could I implement something like this in the condition of my automation?

You could use sensor.bathroom_humidity as the trigger, but then it depends on how often the sensor is updated. If its every few seconds, you are probably not going to see a sufficient increase to meet a 10% increase.

  trigger:
    - platform: state
      entity_id: sensor.bathroom_humidity
  condition:
    - condition: template
      value_template: "{{ trigger.to_state.state | float - trigger.from_state.state | float > 10.0 }}"

You might be better off using a trend sensor.

You could monitor the sensors changes over a few minutes and set it threshold to 10% over 5 minutes for example.

1 Like
automation:
  trigger:
    platform: state
    entity_id: sensor.bathroom_humidity
  condition:
    condition: template
    value_template: "{{ (trigger.to_state.state|int - trigger.from_state.state|int) >= 10 }}"
  action:
    service: fan.turn_on
    entity_id: fan.bathroom_fan

The sensor updates just every minute. I am currently migrating from openhab to Home Assistant and there I have found out that 10% between two changes is a good threshold.

Thanks for the quick reply!