Help with Platform template and if statement with floating values

Hi all!
Newbie to Home Assistant but slowly getting there.

I’m trying to set up a template sensor with 3 states but i’m not getting the result i’m expecting.

Wee bit of background:
I have a sensor under my bed for detecting when I’m in bed. It feeds a voltage reading to HAS and depending on what that rating is i want to set one of 3 states on the template sensor.

1- If the voltage is lower than 1.00v then state “In Bed”
2- If the voltage is higher than 1.60v then state “Empty”
3- If the voltage is between 1.00v and 1.60v then state “Sitting”

I’ve attempted to do this with the code below which, although it doesn’t cause any errors, always returns “In Bed” regardless of what the voltage is at. Hopefully this is something daft I’m missing but any help would be greatly appreciated!

sensor:

Cav Bed Occupied Sensor

- platform: template
  sensors:
    cav_bed_status:
        friendly_name: "Cav Bed Status"
        value_template: >-
            {% if states('senor.cav_bed_sensor') | float < 1.00 %}
                In Bed
            {% elif states('senor.cav_bed_sensor') | float > 1.60 %}
                Empty
            {% elif states('senor.cav_bed_sensor') | float > 1.00 and states('senor.cav_bed_sensor') | float < 1.60 %}
                Sitting
            {% else %}
                Error
            {% endif %}

Typographical error.

You entered:
senor.cav_bed_sensor
instead of:
sensor.cav_bed_sensor.

Jeezo, I know I said it would be simple but seriously!

Thanks so much. Can’t believe I didn’t notice that!

I believe your value_template has a blind spot or two. If sensor.cav_bed_sensor is 1 or 1.6 then it doesn’t meet any of the first three tests and results in Error.

I think the second and third tests ought to be greater than or equal to the specified value.

I’ve incorporated the modifications in this, slightly revised, version:

- platform: template
  sensors:
    cav_bed_status:
        friendly_name: "Cav Bed Status"
        value_template: >-
            {% set bed = states('sensor.cav_bed_sensor') | float %}
            {% if bed < 1 %} In Bed
            {% elif bed >= 1.6 %} Empty
            {% elif 1 <= bed < 1.6 %} Sitting
            {% else %} Error
            {% endif %}

The following format may initially look confusing but the trick is to read it left to right:

1 <= bed < 1.6
  • One is less than or equal to bed.
  • Bed is less than 1.6

If you don’t like it, change it to bed >= 1 and bed < 1.6

2 Likes

I had actually removed the equals just incase they were causing the issues but have since added them back.

I actually really like your suggestion though with using the simple “bed” tag and the more straightforward replacement for the and line. I didn’t realise I could do them like that so that will make things much easier in future. Thanks again!