Electronic – driving a relay with transistor and Opto-isolator

microcontrolleropto-isolatorrelay

enter image description here
I am very new in electronics. I am controlling a relay with stm32 micro controller. For the isolation I have used a 4N33 opto-isolator. As my relay coil needs around 250 mA, I used a mps222 transistor. I figured that the logic gets inverted when I used the gpio as the source voltage for the opto-isolator led. I just used a pull up instead and connected the other end of the led part to the gpio. Gpio is open drain, I will drain around 3mA in the pin.
I do not have the R2 resistor grounded at this moment.
My problem is if in case my stm gets disconnected then my relay will be turned on – which I want to avoid. Could anyone please tell me if adding this R2 will fix the issue?

enter image description here

Best Answer

You can do it like this. Remember, BJT transistor is a current controlled device, that's why you can stack them on top of each other to form a Darlington pair.

Your optocoupler will have a current transfer ratio of ~400% at 3mA LED current, this makes 12mA running thru Q1. For Q2 you need a transistor with hfe greater than 250mA/12mA=20 MPS2222 seems to have hfe of 75 at base 10mA current, so you should be ok.

schematic

simulate this circuit – Schematic created using CircuitLab

schematic

simulate this circuit

Edit on MCU pin mode

From your comments I get that you don't get exactly how push-pull and open drain output stages operate. While it's discussed in this question, I'll just give a short description.

Plase note, that in most stm32 MCUs outputs can be configured as open drain or push pull and whole combination of internal pull ups and pull downs. This is versatile and usefull.

Now, what open drain is - it's just a transistor with it's drain (collector) unconnected - you can hook up your load to this drain (D1 in my schematic). You use open drain when you want to switch current. It can only sink current, not source it.

When the open drain pin is off, no current flows into the pin, the voltage at it is undefined, it is said to be "floating". When the pin is on, it just ties to the ground whatever it is connected to it.

schematic

simulate this circuit

When something outside of the pin wants to read voltage (like high impedance input), you solve this by hooking up a pull up resistor to open drain. Now, while the pin is off, output will be high as the resistor is pulling it, when the pin is on, the internal transistor slams bottom side of pullup resistor to ground.

Push-pull output actively sources and sinks current, when it's on - current flows out of the pin, when it's off - current flows into it. You usually don't use pullups or pulldowns with push-pull output.

schematic

simulate this circuit