How do I update a switch state based on GPIO

Hello. I’d like to be able to change a SWITCH entity state based on GPIO state.
So the switch will reflect the true state of the GPIO state. For example, this is the code I tried:

binary_sensor:
  - platform: gpio
    name: "Relay state"
    id: statusReleu
    pin: 
      inverted: true
      number: 3
      mode:
        input: true
        pullup: true

switch:
  - platform: gpio
    id: switchTest
    name: switchTest
    pin: 
      inverted: true
      number: 3
      mode:
        input: true
        pullup: true

    on_turn_on:
      then:
        - switch.turn_on: button
        - delay: 40ms
        - switch.turn_off: button
    on_turn_off:
      then:
        - switch.turn_on: button
        - delay: 40ms
        - switch.turn_off: button
  
  - platform: output
    internal: true
    id: button
    output: trigger

output:
  - platform: gpio
    pin: 4
    id: trigger

In frontend I want to have a single switch, and it’s working as expected when I trigger it from the FE. But the issue is that when I update the GPIO 3 state, make it HIGH or LOW based on the need, my FE switch doesn’t change state.So this is the situation I encounter when I change the GPIO state:

The relay is on, but the switch entity doesn’t update its state.
What am I doing wrong? Or is there any other solution to achieve this?
Thank you.

What is the point of the binary sensor? The switch has a state that is either on or off. Why duplicate it?

The binary sensor gets input from a latching relay. So by the way the relay is working, I only can be sure if the relay is on or off by getting signal from it.

Maybe use a template switch, which allows you to use a lambda for the state of the switch.

1 Like

Yes! That was it.

Thank you so much for pointing that out.

The final code, for who might need something like this:

binary_sensor:
  - platform: gpio
    name: "Relay state"
    id: relayState
    pin: 
      inverted: true
      number: 3
      mode:
        input: true
        pullup: true

switch:
  - platform: template
    name: "Template Switch"
    lambda: |-
      if (id(relayState).state) {
        return true;
      } else {
        return false;
      }
    turn_on_action:
      - switch.turn_on: button
      - delay: 40ms
      - switch.turn_off: button
    turn_off_action:
      - switch.turn_on: button
      - delay: 40ms
      - switch.turn_off: button
  
  - platform: output
    internal: true
    id: button
    output: trigger

output:
  - platform: gpio
    pin: 4
    id: trigger