Use door sensor to toggle the switch

Hi, i have a door sensor installed in my room as well as sonoff wall switch. My room door is always closed and i want to setup an automation to switch on the light when i enter the room and switch it off when i leave the room.

Basically i want like this,
Door sensor state : close ->open (enter the room)->close , turn on light
Door sensor state : close-> open (leave the room) ->close, turn off the light

Something like sending a logic high/low to toggle the switch. However, i can’t figure it out how can i setup the automation in such way. Any advice?

hi

I use the below for my bathroom, if you change out the senor name and the light or switch id for on. The reverse for turning it off.

- alias: 'Motion Sensor Bathroom Lights On'
  trigger:
    platform: state
    entity_id: binary_sensor.visonic_z06
    to: 'on'
  action:
    service: light.turn_on
    entity_id: light.bathroom

Hi, i just figured out i can use switch.toggle instead of switch.on/off. Anyway, thanks for the suggestion.

If you’d rather the light turn on when you open the door I think something like this would work…

input_boolean:

room_occupied:
  name: Room Occupied

automation:

- alias: Turn Light and Occupation On
  initial_state: true
  trigger:
    - platform: state
      entity_id: sensor.door
      to: "on"
  condition:
  	- condition: state
  	  entity_id: switch.sonoff
  	  state: "off"
  	- condition: state
  	  entity_id: input_boolean.room_occupied
  	  state: "off"
  action:
    - service: switch.turn_on
      entity_id: switch.sonoff
    - service: input_boolean.turn_on
      entity_id: input_boolean.room_occupied

- alias: Turn Occupation Off
  initial_state: true
  trigger:
    - platform: state
      entity_id: sensor.door
      to: "on"
  condition:
  	- condition: state
  	  entity_id: switch.sonoff
  	  state: "on"
  	- condition: state
  	  entity_id: input_boolean.room_occupied
  	  state: "on"
  action:
    - service: input_boolean.turn_off
      entity_id: input_boolean.room_occupied

- alias: Turn Light Off
  initial_state: true
  trigger:
    - platform: state
      entity_id: sensor.door
      to: "off"
  condition:
  	- condition: state
  	  entity_id: switch.sonoff
  	  state: "on"
  	- condition: state
  	  entity_id: input_boolean.room_occupied
  	  state: "off"
  action:
    - service: switch.turn_off
      entity_id: switch.sonoff
1 Like

Could you share your configuration?
I can’t stop scratching my head over this simple but necessary automation when exiting the door