ESPHome switch not working right (for me, anyway)

I’ve defined a switch to turn the blue LED on and off on my D1 mini ESP-32. It was easy to do and I can turn it on and off manually from either the ESPHome web interface or the HA interface.

switch:
  - platform: gpio
    pin: GPIO2
    name: "BlueLED"
    inverted: false
    id: blueled
    on_turn_on:
    - logger.log: "Switch Turned On!"
    on_turn_off:
    - logger.log: "Switch Turned Off!"

The log entry works when I manually switch it.
My trouble is that I want it to turn on and off to show activity at a glance. Knowing that the LED will go on and off manually, I inserted this piece of code into one of my template sensors:

  - platform: template        #power consumption (Watt)
    name: "Measured Sub Panel Power Watts"            
    id: power
    lambda: !lambda |-
      return 118 * (id(current_s0).state + id(current_s3).state + id(current_s4).state + id(current_s5).state + id(current_s6).state + id(current_s7).state);
      id(ctr) +=1;
      if (id(ctr) >=100) {
        if (id(blueled).state)  {
          id(blueled).turn_off(); 
        } else {
          id(blueled).turn_on();
          } 
        id(ctr) = 0;
        id(blueled).turn_off(); # debug after manually turning on
      }
    accuracy_decimals: 2
    update_interval: 5s
    device_class: power
    state_class: measurement
    unit_of_measurement: W      # Total Watts of ALL clamps

This template should get updated every 5 minutes so I put a counter there to ensure I would see it since it would be a very fast cycle. I’ve tried setting the count to 2, 5 10, 100, 1000, but it does not seem to affect the LED at all. I even put just the “turn_off” only and turned the LED on manually to see if it would turn it off. No luck so far.
I’ve tried alternate syntax such as switch.turn_off: blueled; but that didn’t work either.

Any ideas how to do this properly?

I was really hoping that someone would tell me why this does not work. Anyone?

The first line of your lambda contains a return statement meaning that none of the code below it will get executed.

1 Like

Unbelievable - I can’t believe it was that simple and that I was so naive. Thank you @rdehuyss as this was driving me crazy!

1 Like