Esp8266 like a wifi button

Esp8266 as a wifi button

Hi,
i’m new with home assistant and I’d like to create an automation that toggle my switch when I push the button on my Esp8266.

I just flashed the esp8266 firmware with EspHome.

My problem is that I can’t create an automation that trigger the light switch when I click the button on my esp8266.

Here is the code:

---CODE INSIDE MY ESP8266:---
 
binary_sensor:
  - platform: gpio
    pin: 4
    name: "PulsanteD2"
    device_class: lock
---AUTOMATION CODE THAT DOESN'T WORK:---
 
alias: Turn On
description: ''
mode: single
trigger:
    - platform: state
      entity_id: binary_sensor.pulsanted2
      from: 'off'
      to: 'on'
condition: []
  action:
    - service: switch.toggle
      entity_id: switch.1000a595a6
 

What does the esphome log say when you press the button?

What does state of the binary sensor say when you press the button?

It’s a little bit strange, because i don’t see anything in the log and the binary_sensor show the status “locked or unlocked” but random.

Sounds like it is floating, what exactly is your wiring?

The wiring is port D2 with GND. I saw that the port D2 on my nodemcuv3 is the GPIO 4.

In my esphome code says that my board is esp01_1m.

That is correct. So your button shorts D2 to ground? I think you need pullup GPIO Binary Sensor — ESPHome

So like this:

binary_sensor:
   - platform: gpio
     pin:
  number: 4
  inverted: false
   mode:
    input: true
    pullup: true
name:
"PulsanteD2"

I tried with this code, but when I release the button, the state goes to off

No, your indentation is wrong. See the example I pointed you to.

Thank you so much for the example, but I don’t know if I understood what to do.

So I set “pullup” to false and now when I click the button, the state goes from on to off and stop it…

I created the automation that when I click the button the light goes on.

Now the problem is how to stuck the state of the button on “ON” when I push the button and “OFF” when I push again the button

The toggle automation in your first post should do that.

I don’t know why but the automation doens’t work with switch.toggle.
So I created 2 automation, 1 to turn on the light and 2nd to turn off the light.

But when I press the button, the state of the binary_sensor goes to On and again to off

You are really confusing me. Please post your current config for both the esphome and the HA automation.

I’m sorry about that :sweat: I have a bad english grammar.
Anyway I just saw that it was a eWelink bug, so the switch.toggle didn’t work fine.
So I found that there is a script that basically Turn on the switch when the switch is off and vice-versa.

So I created the automation that when I push the button then execute the script.