Help, need to invert an adc value in ESPHome

Hi everyone.
I’ve looked for a few hours to a solution to this.

I’ve built this circuit:

and it works fine, but as expected its inverted, i.e. daylight shows 0% and dark shows 100%.

I thought there would be an easy way to do this, but several hours later, I’ve not figured it out.
I thought it would just be a case of inserting a NOT, or ! somewhere, but no luck.

Heres the yaml I have specifically for the adc.

sensor:
  - platform: adc
    pin: A0
    name: "Daylight"
    icon: "mdi:sun-wireless-outline"
    update_interval: 120s 
    filters:
      - multiply: 100
    unit_of_measurement: "%"

I suspect I need to use templating or Lambda, but I’m not a wizz with either.
Any help would be appreciated.
Thanks for your time,
Ian.

Just swap the positions of the LDR and resistor in your circuit.

If you had used this component instead:

You could have changed upstream/downstream, but the result would be in Ohms not %.

Thanks Tom.
To be honest, I did originally have the LDR and resistor reversed. I was using something like a 600R resistor. It worked, but was a bit sensitive to light. It was still showing 100% even on very cloudy days.
I guess I just need to sit down and work out the upper and lower thresholds.

After setting up in this “inverted” manner, I noticed straight away that I was getting good balanced readings between light, cloudy and dark - and so was hoping to just invert the adc value.

If there is no other way, then I will just work out the correct resistor value.

Thanks for your time,
Ian.
PS, I didn’t know there was a resistance calculator thing in ESPHome.

LDRs reduce in resistance as more light falls on them.

If they are connected “upstream” of the fixed resistor this means the voltage at the junction goes up with increasing light level. The opposite occurs if connected “downstream” of the fixed resistor (the junction will be pulled towards ground → lower voltage with increasing light).

The best value for your fixed resistor, to give the largest voltage swing, can be calculated from the light and dark resistances of your LDR:

Rfixed = sqrt( Rdark x Rlight )
1 Like