Current sensor - bi-directional - how to do calculations syntax

I have a D1 Mini running ESPHome
Connected, I have a ADS115 ADC and to that an ACS712.
This working fine and I read approx. 2.5v with no current.

The ACS712 is a bi-directional current sensor

Therefore at 0 amps it reads 2.5V
It produces 0.1V per amp up and down from 2.5V

I am really struggling to work out the way to describe the formulas to return the correct value.
The calculation is not hard but I am struggling with the syntax

I have tried this with the template editor but failed

What I am hoping to get is “current 1” = the current ( like 1.2A, or -10.6A, etc )

I would appreciate some help with the syntax or if there is a better way to do this.

Here is what I have done so far

sensor:

  • platform: template
    scan interval: 1
    sensors:
    current_1:
    friendly_name: “current 1”
    value_template: >-
    {% if states(‘sensor.ads1115_channel_a0_gnd’)|float < 2.5 %} # for negative current
    {% (2.5 - x) * (-10.0) %}
    {% elif states(‘sensor.ads1115_channel_a0_gnd’)|float > 2.5 %} # for positive current
    {% (x - 2.5) * (10.0) %}
    {% elif states(‘sensor.ads1115_channel_a0_gnd’)|float == 2.5 %} # for zero current
    {% (2.5 - x) * (0.0) %}
    {% endif %}

This should do it:

value_template: "{{ states('sensor.ads1115_channel_a0_gnd')|float - 2.5 }}"

2.5v - 2.5 = 0
2.6v - 2.5 = 0.1
2.4v - 2.5 = -0.1
etc…

Also add:

unit_of_measurement: 'A'

So you can graph it.

err… you can only measure down to -2.5A. -10.6A is way out of range.

So your template should also multiply by 10 to give -25A to +25A

value_template: "{{ (states('sensor.ads1115_channel_a0_gnd') | float - 2.5) * 10 }}
1 Like

Right. No more answers from me tonight. I’m clearly having issues comprehending topics.

Hello mutt and tom

Thank you for your help

Here is the finished code and it works well

Note: due to offset errors with the ACS712 I will need to make some adjustments but the code works

I appreciate your help. Andy

# current sensors
  - platform: template
    sensors:
      current_1:
        friendly_name: "current 1"
        value_template: >-
         {% if states('sensor.ads1115_channel_a0_gnd')|float < 2.5 %}
           {{ ((2.5 - (states('sensor.ads1115_channel_a0_gnd') | float )) * -10) | round(2) }}
         {% elif states('sensor.ads1115_channel_a0_gnd') | float > 2.5 %}
           {{ (((states('sensor.ads1115_channel_a0_gnd') | float - 2.5)) * 10) | round(2) }}
         {% elif states('sensor.ads1115_channel_a0_gnd') | float == 2.5 %}
           {{ (((states('sensor.ads1115_channel_a0_gnd') | float - 2.5)) * 0) | round(2) }}
         {% endif %}