How to programmatically change "unit_of_measurement" on the fly

I am making a refrigerator controller using a lily TTGO board (esp32, lcd) I want to configure my screen for either F or C temperature display.

I configure some Dallas temperature sensors. Then use a filter to do the conversion based on a flag.

I would like to change the “unit_of_measurement” as well, but that tag only accepts strings and, as much as I beat upon it, I could not figure out how to change that in yaml, or lambda per suggestions from ChatGPT (!). So I eventually rummaged around the sensor.h file and found a handy public method “set_unit_of_measurement()” which works fine.

So, is this a feature or a bug that !lambda cannot be used with the “unit_of_measurement” tag?

e.g. this works

      - lambda:  if (id(bFarenheit)) return x * (9.0/5.0) + 32.0; else return x; 
      - lambda:  id(freezer_temp).set_unit_of_measurement(id(bFarenheit)?"°F":"°C"); return x;

This does not
unit_of_measurement: !lambda id(bFarenheit)?"°F":"°C");

Is there a better way to do this?

Believe the reason is that in HA the measurements are stored and used for historical data. If unit changes, would mess up sensor’s historical data. And yes, I know that you ask how to change, not why it doesn’t have native support for changing.
Not an option for you to add an additional sensor, so one for C and one for F and let your screen switch between those?

So a template sensor in F and leave the native in C

Sounds good to me. Something new to figure out :slight_smile:


Can do something like this:

- platform: template
  id: freezer_temp_fahrenheit
  unit_of_measurement: "°F"
  lambda: |-
    return id(freezer_temp).state * 9/5. + 32;

Which updates every 60s (default), can use the update_interval to increase update speed.

Alternative is update the template sensor directly from your freezer sensor:

- platform: template
  id: freezer_temp_fahrenheit
  unit_of_measurement: "°F"
- platform: ...
  id: freezer_temp
    - sensor.template.publish:
        id: freezer_temp_fahrenheit
        state: !lambda 'return x * 9/5. + 32;'