I’m measuring the water level in my pond using a pressure sensor.
I have a defined a text_sensor and am feeding it with information about the water level. For example if it’s between 119 and 124cm I set the text_sensor to “low”.
I want to make this text_sensor a bit more advanced so that it shows how many cm it is above 114cm (a critical level it must not drop below).
The above code produces the following result for the text_sensor:
“low: 6.800000cm above critical”
My problem is that I don’t manage to find a way to get rid of all the excess zero’s (I want to only have a precision of 0.1cm, which is why in the code above, I multiply by 10, then round it to an integer, and then divide it again by 10).
Sorry to revive an old thread, but I’ve been trying to solve this exact same issue for a while. Unfortunately, this doesn’t seem to be working for me. I’ve copied the exact same code, but during compiling it gives me this error on the ‘return’ line:
could not convert 'buf' from 'char [128]' to 'esphome::optional<std::__cxx11::basic_string<char> >'
Based on some googling, I came across SLIGHTLY similar issues that make me wonder if it’s due to an ESPHome update between this post and now. I’m guessing it’s something simple like changing the variable type for ‘buf’, but nothing I’ve tried has worked. Any insight? My C++ is rough at best, so apologies if it’s something beyond simple. Thank you very much in advance!
Have a look at my code below, there are some differences. For example you are not using ‘x’ and in the sprint you are not using ‘distance’.
Perhaps that had something to do with your error.
Sorry for the late reply and thanks, for some reason I didn’t get a notification!
I originally kept the ‘distance’ variable and subbed in my sensor reading in place of ‘x’ but it gave me the same error. No matter what I’ve done, I’ve always gotten the same compile error on the return line. It just seems to be a variable issue that the sprintf function doesn’t produce the right type of variable that ESPHome wants for a text sensor.