How to get lowest of three values

I have three DS18B20 temperature sensors, each located on a different side of a cabinet outside. The sun often shines on one or two of the sensors, and I figured the one in the shadow would be correct.

I can do this in home-assistant with a template as simple as: {{ [a,b,c] | min }}. However in esphome the min filter returns the smallest value of a single sensor over a specified period. So how could I get the home-assistant functionality in esphome?

Sort the list and pick the first element?

Not sure how to do it in ESPHome but in HA it would be:

{{ [a,b,c]|sort[0] }}
1 Like

Thanks, but I found no simple way to do that in esphome.

Looks like a lambda.

Create an additional Template Sensor that reads the states of your three real sensors and returns their minimum value.

1 Like

You said it much better than me!

1 Like

No no. The really relevant work was yours. I just filled in some missing words. :hugs:

I’ll give this a try. Thank you!

This worked. Here’s the config that works:

  - platform: template
    name: "temperature_outside_lowest_value"
    lambda: |-
      if (id(t1).state < id(t2).state) {
        if (id(t1).state < id(t3).state) {
          return id(t1).state;
        } else {
          return id(t3).state;
        }
      } else {
        if (id(t2).state < id(t3).state) {
          return id(t2).state;
        } else {
          return id(t3).state;
        }
      }

Now I appreciate much more how convenient filters in home-assistant are.

Happy to hear!

Two tips:

  1. Using the C++ min function would reduce your whole lambda to one line. Not sure out of the back of my head if you have to prepend with std:: but I think so:
    lambda: |-
      return std::min(id(t1).state, id(t2).state, id(t3).state);
  1. You can use blanks in your names.
    name is the friendly name in HA. If you want to apply an internal name to use in lambdas, use name + id:
    name: "Lowest outside temperature"
    id: temperature_outside_lowest_value
3 Likes

Additionally, you can also hide t1, t2 and t3 sensors setting “​internal​: ​true” property if you don’t need them in Home Assistant.

2 Likes

Thanks for the tips!

That one-liner is really nice. Thank you. It works like that with two sensors, but three apparently requires brackets. Is that a list in cpp? So the working code is:

lambda: |-
      return std::min({id(t1).state, id(t2).state, id(t3).state});
2 Likes

Oh yes, you are right.
In C++ multiply values enclosed in curly braces are a way to create a prefilled array.