I want to use a Raspberry Pi 4 to turn my existing dumb doorbell into a smart one that can trigger alerts and other home automations. The doorbell is a simple chime, consisting of an electromagnet in series with a push switch and a 9V PP3 alkaline battery. When you push the button, the magnet pulls the ringer across to hit one chime; when you release it, a spring pulls it back to hit another. To tell if the doorbell has been pushed, I think need to use a GPIO input to detect whether the electromagnet solenoid has been energised. However, I need to avoid the GPIO being burnt out by either the 9V battery, or the spike of reverse voltage caused when the solenoid de-energises.
What is the best way to safely interface the solenoid circuit to the GPIO input?
To be clear, I don't want to control the solenoid, just to detect whether it has been activated. If necessary, I will software-debounce the circuit (i.e. ignore repeated triggers for a period of time after the initial trigger). I also realise that an RPi 4 is probably overkill for the task, but I already have one running other tasks conveniently close to the doorbell. My current best idea is shown below:
The idea is that the diode would take care of the reverse voltage spike from the solenoid, and R1 would limit the current from the battery to 9mA, to avoid burning out the LED in the optocoupler (4N32). R2 and R3 would then give me a nice logic input, while limiting the current to the GPIO if I accidentally misconfigure it as an output.
The electromagnet solenoid does not have an inductance marked on it, but I measure the resistance across it at 6Ω. When the button is pressed, the voltage across the coil is 4.5V, and the current through the circuit is 0.9A.
I did think about using a simple potential divider instead of the optocoupler (as per this answer), but decided that with the solenoid involved, it would be too tricky to get the output at the right level to reliably trigger HIGH on the GPIO, without taking it over 3.3V by accident. When the solenoid is energised, the load pulls down the battery voltage considerably; I thought that a divider on its own would be too sensitive to changes in the battery characteristics over time. I also discounted rewiring the doorbell so that the switch interfaced directly to one GPIO pin, then using another GPIO to control the solenoid through a relay. My wife will kill me if the doorbell doesn't still work normally if I foul up something on the software side, or decide to use the RPi for something else!
Does the optocoupler circuit look like it will work (without destroying the GPIO)? Are there any potential pitfalls I have missed? Is there a more sensible approach to detecting the doorbell press?