Help with virtual switch with Esp01

Hello , I have an esp01 and a button connected to the reset pin. A virtual switch should toggle when I press the reset button and then , the esp01 should return in deepsleep. However , the switch toggles only sometimes but not always and it can takes up to 2 minutes to toggle the switch . Here is my code :

esphome:
  name: device-1
  friendly_name: Wifi Button
  on_boot:
    priority: -100.0
    then:
              - switch.toggle: my_startup_switch
              
esp8266:
  board: esp01_1m

# Enable logging
logger:

# Enable Home Assistant API
api:
  encryption:
    key: "______________________________________-"

ota:
  password: "____________"

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Device-1 Fallback Hotspot"
    password: "_____________"

captive_portal:

switch:
  - platform: gpio
    pin: 4 
    name: "my startup switch"
    id: my_startup_switch

deep_sleep:
  id: deep_sleep_1
  run_duration: 25s

(I replaced the sensitives areas by lines)
Could anyone help me with my problem and say me what’s causing this?

first mistake i see is that you must add:

fast_connect: true

to the wifi section. This will cause faster reconnect to your wifi network, because it disables wifi scanning at each reconnect, but connects to first ssid it sees when it wakes up.

Hello, I still have the same problem even after adding the fast connect option.

Also , after about 5 seconds later , I am able to see the logs but the virtual switch can take up to 5 minutes before toggling.

I think what you are trying to do is that when you press the physical button the esp01 turns on and when it connects to HA an automation on HA runs and esp01 can go back to deep sleep.
If this is your use case I would suggest use mqtt rather than api. You can run your automation on HA using the mqtt trigger of the birth message the esp01 will publish when it connects to HA. With the use of setting a fixed ip address for esp01 and fast connect it should take <10 seconds from pressing button to automation begin to run.

Thanks! I’ll try that!