inevitab 发表于 2024-4-26 19:04:34

磁保持继电器插座LED灯状态显示的问题

插座只有一个led灯,希望可以显示连接状态,也可以显示继电器状态。


代码如下:
output:
- platform: gpio
    id: led1
    pin:
      number: GPIO2
      inverted: True

light:
- platform: status_led
    name: "Switch state"
    id: status_led1
    output: led1
    internal: True

switch:
- platform: gpio
    name: "电源开关"
    pin: GPIO13
    inverted: true
    id: relay
    restore_mode: RESTORE_DEFAULT_ON
    on_turn_on:
      - output.turn_on: led1
      - switch.turn_off: ina
      - switch.turn_on: inb
      - delay: 100ms
      - switch.turn_off: ina
      - switch.turn_off: inb
      - delay: 100ms
    on_turn_off:
      - output.turn_off: led1
      - switch.turn_on: ina
      - switch.turn_off: inb
      - delay: 100ms
      - switch.turn_off: ina
      - switch.turn_off: inb
      - delay: 100ms
   
- platform: gpio
    pin: GPIO4
    id: ina
- platform: gpio
    pin: GPIO5
    id: inb


但是发现,有时候断电再上电,LED状态和继电器状态并不对应。

于是改了下代码,每隔5秒查询一次继电器状态,再更改LED状态,代码如下:

output:
- platform: gpio
    id: led1
    pin:
      number: GPIO2
      inverted: True

light:
- platform: status_led
    name: "Switch state"
    id: status_led1
    output: led1
    internal: True

switch:
- platform: gpio
    name: "电源开关"
    pin: GPIO13
    inverted: true
    id: relay
    restore_mode: RESTORE_DEFAULT_ON
    on_turn_on:
      - output.turn_on: led1
      - switch.turn_off: ina
      - switch.turn_on: inb
      - delay: 100ms
      - switch.turn_off: ina
      - switch.turn_off: inb
      - delay: 100ms
    on_turn_off:
      - output.turn_off: led1
      - switch.turn_on: ina
      - switch.turn_off: inb
      - delay: 100ms
      - switch.turn_off: ina
      - switch.turn_off: inb
      - delay: 100ms
   
- platform: gpio
    pin: GPIO4
    id: ina
- platform: gpio
    pin: GPIO5
    id: inb

interval:
- interval: 5s
    then:
      if:
      condition:
          api.connected:
      then:
          if:
            condition:
            switch.is_on: relay
            then:
            - output.turn_on: led1
            else:
            - output.turn_off: led1


这样确实是可以了。

请问还有更好的实现办法吗?

alei643 发表于 2024-4-27 11:58:24

可以借鉴插排指示灯,从负载侧引出220接LED,再串个限流电阻,如果硬件上不好实现,可以在esphome中设置一个断电存储的变量

sirakawa 发表于 2024-4-27 17:29:05

我是拿个全局变量,这个变量设置成保存到FLASH
其他地方判断继电器状态,以及通电后的状态回复都是靠这个变量解决
LED和继电器是同时操控的,正常时候肯定同步,如果LED拿去做别的了,处理完成后,根据全局变量重设一下LED状态就好

如果需要更复杂的,那就LED控制单独写一个SCRIPT,根据不同的状况设置不同的LED状态。

# 开关1,控制LED和继电器
- platform: template
    name: "switch_relay_1"
    id: "switch_relay_1"
    restore_mode: DISABLED
    optimistic: true
    on_turn_on:
      - globals.set:
          id: global_relay_1_state
          value: '1'
      - switch.turn_on: switch_relay_1_led
      - switch.turn_on: switch_relay_1_on
    on_turn_off:
      - globals.set:
          id: global_relay_1_state
          value: '0'
      - switch.turn_off: switch_relay_1_led
      - switch.turn_on: switch_relay_1_off
页: [1]
查看完整版本: 磁保持继电器插座LED灯状态显示的问题