For a rudder position sensor in my boat I would like the value to be set to the numbers I have when it’s between 5 and 95, to “bottom” if it’s less than 5 (which in my setup will be 0) and “top” if it’s more than 5 (which here is 100). Is this possible? Here’s the template sensor code:
Thanks for answering! But either there’s something I don’t understand, or you misunderstood me. I don’t think that code can show “Bottom” and “Top” (I set it in quotation marks to show that it was the text words I meant).
Sorry, I misunderstood your issue. I thought that you meant that the bottom value should be 0 and the top value should be 100, but you want it the other way around.
However, my proposal might still be of interest, because I think that with the original code the rounded output value will be 95 with an input value between 95 and 97 ( 5 * round( 97 / 5 ) = 95 ).
Only with an input value of 98 to 100 the output value will be 100.
And similar an input value between 3 and 5 will output 5.
So you will get Top with values between 98 and 100 and Bottom with values between 0 and 2.
Or is this what you want?
I don’t think it is possible to have a sensor with a conditional data type output, so sometimes an int like 20 or 80 and sometimes a string like Bottom or Top.
What are you doing with the output of the sensor? Is it only printed on a display?
So would it function if the output would be a string always, so also when the output is for instance 50?
If so, then something like this might work (again not tested):
@thusassistint It won’t compile. I get this conversion error, and I have no idea how to convert the float numbers to a string:
motorheis-oppsett-tekstsensor.yaml: In lambda function:
motorheis-oppsett-tekstsensor.yaml:91:33: error: could not convert 'motorheisposisjon->esphome::template_::TemplateSensor::<anonymous>.esphome::sensor::Sensor::state' from 'float' to 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'}
*** [.pioenvs\motorheis\src\main.cpp.o] Error 1
Edit: I wonder if this can be done with an if - then in the text sensor, so if the value is 0 then bottom, if the value is 100 then top else the value that comes in?
It now takes into accounts the filters, but with six decimals, so it’s 0.000000 and 100.000000 instead of 0 and 100. I tried to put in accuracy_decimals: 0
before the filters, but that didn’t help either. Kind of weird that there are no filters that works this way. Maybe because as it says about accuracy decimals:
This does not impact the actual value reported to Home Assistant, it just sets the number of decimals to use when displaying it.
I actually managed to think myself into the second version by myself, from the first, before I saw your edit! And now it works as it should, so thank you very much!