Map values in template

Can this be done somehow ?
I’dd like to convert an analog value from a modbus sensor to a percentage value.

value_template: '{{map(sensor.Sensor1, 28650, 4940, 0, 100)}}'

So the value from the sensor is 0 to 1 ???

“{{ states(‘sensor.mysensor’) | float * 100 }}”

Not sure what the : 28650 and 4940 represent

Yeah you’re going to have to explain what you want. That template means nothing.

Sorry bit confusing maybe.

28650 is max value of wago analog plc input
4940 is min value of wago input
28650 would translate to 0
4940 would translate to 100

The value of sensor 1 would then be (mapped) to a percentage readout.

map(sensor.Sensor1, 28650, 4940, 0, 100)

Based on those requirements, the formula is:

(28650 - x)/237.1

I don’t know where you are using the value_template but here’s one way to implement the formula:

{{ (28650 - states('sensor.sensor1')|float) / 237.1 }}

You can test it in Developer Tools > Template.

2 Likes

Bare the stupidity with me. :sleeping:
I believe the map() is a c++ function, but completly missed the reformat to this formula. Will test it later today.

Thank you very much for the hint!

If after trying my suggestion it proves to answer your question, please mark my post (above) with the Solution tag. It will automatically place a check-mark next to the topic’s title which indicates to other users that this topic has an accepted Solution. It also automatically places a link beneath your post that leads to the Solution post. All of this helps other users who may be looking for an answer to a similar question.

i was trying to do somthing similar but with voltage for my home solar battery, ive tried

- platform: template
  sensors:
    testtesttest:
      friendly_name: "Testtesttest"
      unit_of_measurement: '%'
      value_template: >
        {{ state_attr('sensor.voltronic_battery_voltage', 'V')|float|min(49)|max(57.4) }}

but it just displays 57.4% constantly

but following this i got it working

my min value for the battery needs to be 49v and the max will be 57.4v so that would be the 0-100% scale but the sensor.voltronic_battery_voltage can be anywhere between those voltage values say 55volts which would need to be converted into a percentage

worked out by

min value (49.0) diveded by 100 = 0.49
max battery value (57.4) divided by 100 = 0.574

then i done 0.49-0.574 = -0.084

then i done the above formula

ended up with

- platform: template
  sensors:
    testtesttest:
      friendly_name: "Testtesttest"
      unit_of_measurement: '%'
      value_template: >
        {{ (49 - states('sensor.voltronic_battery_voltage')|float) / -0.084 | round(1)}}