Electrical – How to safely use RPi GPIO to detect if computer is on

5vgpioopto-isolatorraspberry pi

schematic

simulate this circuit – Schematic created using CircuitLab

I have a Raspberry Pi that I want to use to detect if my desktop computer is on, by detecting if the 5V rail is powered. I have in the past used optocouplers to short pins on the motherboard together with the RPi, but when I tried to use my pc817 optocouplers for this purpose, they kept releasing magic smoke.

Am I doing something wrong? I was directly connecting one end of the optocoupler to the 5V wires in a USB cable I took apart and the other end of the optocoupler to the GPIO.

Thanks in advance! Neil

Best Answer

First, your magic smoke comes from the fact that one should not supply a diode (here, the photocoupler's input diode) directly with a voltage source (in this case, the USB's 5V). You must add a series resistor to limit the current through said diode.

Schematic taken from The Raspberry Pi Hobbyist Blog

Schematic taken from The Raspberry Pi Hobbyist Blog, Ignore the resistor value.

According to the datasheet of your photocoupler, the input diode can sustain 50mA of current, but works fine with 5mA. i will aim for that current.

Again from the datasheet, the forward voltage drop of the diode is typically 1.2V, which leaves us with 5V-1.2V = 3.8V across our resistor.

Following Ohm's law, 3.8V/0.005A = 760 Ohms. Since this value is non-standard, we will use a 820 Ohms resistor, which will in turn give us 3.8/820= 4.6mA through our diode, close enough.

Conclusion : add a 820 Ohms serie resistor between your USB's 5V and your photocoupler and everything should work fine.