Convert AC input to digital on/off

I’ve managed to hook up an AC doorbell to a digital pin of an ESP32 via a PC817 optocoupler. This appears to work, however since the doorbell is AC, when it is pressed the optocoupler is activating at the frequency of the AC supply. Hence the ESPHome binary sensor is flicking on/off as the button is pressed.

Before I try a HW approach using diodes and a capacitor to rectify (?) the signal coming out of the optocoupler, is there a software solution I can use via ESPhome? Perhaps a template sensor on top of a pulse sensor that stays on? Or perhaps a sensor that waits for a stable signal before transmitting?

Or should I approach this via HW?

In ESPhome use a debounce time filter for your sensor.

binary_sensor:
  - platform: gpio
    pin: D2
    name: Doorbell
    filters:
      - delayed_off: 100ms

The sensor wont turn off until 100 milliseconds after the change of state. If the off pulses due to the AC waveform are shorter than that they will be filtered out.

Worst case your AC signal is 50Hz so if you are only using 1/2 the cycle to turn to opto LED on it will be on for 10ms then off for 10ms.

60Hz would be even faster.

So 100ms should definitely do the trick while hardly being noticeable when the button is finally let go.

1 Like

I just found the debounce section in the docs. Many thanks for the solution.

1 Like

Hi shall you post the schematic for the connection?

Or rectify the A/C and place a small capacitor (1uF) in parallel with the output of the rectifier.

That is also an acceptable solution. But if you can do it in software without additional hardware the bean counters will love you long time. Well… at least until the next audit.