logo elektroda
logo elektroda
X
logo elektroda

Controlling a 12V relay directly from a 5V MCU using a Zener diode and a PNP transistor

petrykcom 2727 46

TL;DR

  • A 5V MCU can drive a 12V or 24V relay directly using a PNP high-side switch and one Zener diode.
  • The Zener sits between the PNP base and MCU pin, so a LOW output turns the transistor on and a HIGH output keeps it off.
  • For 12V, a 9.1V Zener fits; for 24V, 20V or 22V works, with the condition VCC-5.7V < Vz < VCC-0.7V.
  • The circuit tolerated ±5% Zener variation and supply changes, but it still needs a 1N4148 flyback diode and a sensible base resistor, such as 1kΩ.
Generated by the language model.
ADVERTISEMENT
This content has been translated flag-pl » flag-en View the original version here
📢 Listen (AI):
  • #31 21893897
    viayner
    Level 43  
    Posts: 10575
    Help: 1557
    Rate: 2009
    Welcome,
    Andrzej_Tomaszewski wrote:
    ....
    The uC pin controls several components in series and there is a +12Vdc potential on the other side. In my opinion this is not correct.

    here I agree, if the GPIO pin is in the H state without any 'pull' e.g. OC or OD output, then the resistance of this output to ground will be equal to infinity, so the anode of the Zener diode hangs in 'air' and we have a potential of 12V here, i.e. we have 12V on GPIO, which is strongly unhealthy for most circuits.
    Of course, in real-world conditions it doesn't have to be like this, well, and the components have some finite resistance after all, but this is not a good approach in my opinion, balancing on the limit.
    Regards
  • ADVERTISEMENT
  • #32 21893942
    pawlik118
    Level 33  
    Posts: 2410
    Help: 201
    Rate: 596
    Andrzej_Tomaszewski wrote:
    pawlik118 wrote:
    the approach is unusual

    agreement

    pawlik118 wrote:
    it may arouse resistance to the unknown

    And what is the unknown here? Unless the arrangement is unknown because it is unused because it is incorrect.

    pawlik118 wrote:
    from an electronic point of view it is correct

    The uC pin controls several components in series and there is a +12Vdc potential on the other side. In my opinion this is incorrect.


    Let's assume we have a (relay) supply of 12V and a zener diode at 8.2V. The voltage the processor "sees" is 12-8.2=3.8V. This is just right, as the processor is powered by 5V.
    The fact that "somewhere" further down the line there is 12V is irrelevant.
  • #33 21893949
    HD-VIDEO
    Level 43  
    Posts: 7966
    Help: 1257
    Rate: 1850
    From the calculations yes and in the actual system how much will it be?
  • #34 21893971
    Andrzej_Tomaszewski
    Level 13  
    Posts: 270
    Help: 2
    Rate: 338
    pawlik118 wrote:
    Assume we have a (relay) supply of 12V and a zener diode at 8.2V. The voltage the processor "sees" is 12-8.2=3.8V. This is just right, as the processor is powered by 5V.
    The fact that "somewhere" further down the line there is 12V is irrelevant.


    Your calculations for ideal components, mainly assuming zero current of the Zener diode below the threshold are ok. But in this circuit, disconnect the uC leg and measure with a voltmeter the voltage at the anode of the Zener diode relative to ground.
  • ADVERTISEMENT
  • #35 21893990
    pawlik118
    Level 33  
    Posts: 2410
    Help: 201
    Rate: 596
    >>21893971 The voltage drop across the diode depends on the current flowing through it. The current in turn must not exceed Ue-b / Re-b. This can be counted, measured. It is not a contact operation, and zener diodes do not have such a large spread of parameters. I deal with this on a daily basis.
  • #36 21894205
    mkpl
    Level 37  
    Posts: 5648
    Help: 306
    Rate: 847
    The circuit looks like a dig at the early years of MCU production. Still from the days where the processor port was an open manifold type with a small pull-up. Often an external pull-up was done. The trouble was that it was hard to put out a current-efficient high state that reliably quenched the NPN transistor. Added to this was the behaviour in the reset state. Such a processor in reset mode had a high state on its leads that would drive the relays with the NPN transistor.
  • ADVERTISEMENT
  • #37 21894966
    Janusz_kk
    Level 39  
    Posts: 5700
    Help: 216
    Rate: 1431
    Someone mentioned the optotransistor, this is the best and simplest solution.
    It eliminates all the disadvantages and you can control the low level (as in the figure) or the high level by changing the diode control.

    Schematic: LTV-817 optocoupler driving relay K1 with flyback diode D13, supplies +VCC and GND

    Added after 1 [minute]:

    The optotransistor in the darlington has sufficient current for most relays and even large ones.
  • #38 21894977
    HD-VIDEO
    Level 43  
    Posts: 7966
    Help: 1257
    Rate: 1850
    And this for this AT

    petrykcom wrote:
    When the microcontroller (the one I just needed and many others) is switched on, there is a logical 1 at its output, so when the power is switched on for a short while until the IO is initialised, the relay controlled by the NPN transistor would be switched on
  • #39 21894983
    Janusz_kk
    Level 39  
    Posts: 5700
    Help: 216
    Rate: 1431
    HD-VIDEO wrote:
    As for this AT

    But what, because I don't understand.
  • #40 21897273
    elukam
    Level 17  
    Posts: 377
    Help: 8
    Rate: 149
    An optocoupler is used for galvanic isolation and not for amplification or signal inversion. That is what a triode, or transistor, is used for. Just because something is "suitable" for something does not yet mean that it should be used. Lame solutions should not be promoted, especially in an educational context.
    In general, discussing this idea is akin to trying to grill a cockroach impaled on a stick with such reverence as if it were at least a decent pork chop. These arrangements are not worthy of attention or discussion, only of pointing out why they are weak.
  • #41 21897314
    viayner
    Level 43  
    Posts: 10575
    Help: 1557
    Rate: 2009
    Hello,
    elukam wrote:
    Transistor is used for galvanic isolation and not for amplification or signal inversion. That is what a triode, or transistor, is for. Just because something is "suitable" for something does not yet mean that it should be used. Lame solutions should not be promoted, especially in an educational context.
    In general, discussing this idea is akin to trying to grill a cockroach impaled on a stick with such reverence as if it were at least a decent pork chop. This arrangement is not worthy of attention or discussion but only of pointing out why it is poor.

    Perhaps a colleague should study the principle of the optocoupler and its applications, especially those not requiring isolation at first glance.
    I agree with colleague @Janusz_kk that using it to control a relay is a good choice and even "even more right", as thanks to the isolation we can separate the power supply and avoid possible overvoltages, for example. Contrary to appearances, this is quite common in industrial equipment.
    In this case, education is not only about showing weaknesses, but also about showing potential advantages, possible improvements, analysis of the circuit, etc., as just pointing out the flaws will not teach anything if someone does not know why it is wrong.
    Regards

    Regards
  • ADVERTISEMENT
  • #42 21897404
    Janusz_kk
    Level 39  
    Posts: 5700
    Help: 216
    Rate: 1431
    elukam wrote:
    The optocoupler is used for galvanic isolation and not for amplification or signal inversion.

    Mate
    elukam wrote:
    Transoptor is for galvanic isolation and not for amplification or signal inversion. That is what a triode, or transistor, is for. Just because something is "suitable" for something does not yet mean that it should be used.

    Mate, sorry but you're babbling nonsense, an optocoupler is a full-fledged transistor only the gate is controlled slightly differently than usual.
    So your whole thesis is gone.
    elukam wrote:
    In general, discussing this idea is akin to trying to grill a cockroach impaled on a stick with such aesthesia

    The discussion is needed because the author's solution is, from the point of view of electronics and operational reliability, hopeless. Such a thing can be done by an amateur but not by an electronics technician who has the ambition to be a professional.
    And this is written to you by an electronics engineer with 50 years of experience still repairing industrial electronics, which means that I have seen many different solutions, but not this one.
  • #43 21897420
    elukam
    Level 17  
    Posts: 377
    Help: 8
    Rate: 149
    No one here is raising the need for power or interference isolation. In the general case, optocouplers are not used to control relay coils and only special optoisolators are actually suitable for this. Such a solution is more expensive, takes up more space, and is insecure due to the uncertainty of the optoisolator's transmittance. Finally, it puts quite a heavy load on the digital port unnecessarily. Of course, you can special, better etc etc but here the idea was to have a simple, cheap and reliable circuit.
    The use of an opto-isolator does not guarantee safety from interference. Safety from interference is guaranteed by the designer's knowledge.
    Why this circuit is weak has already been written, and what it should be replaced with has also already been written.
    Any improvement of any circuit inevitably involves complicating it. This is why real professional equipment is so packed with "meat".
    A circuit should be complicated only when necessary and only to the extent necessary. You should start with the optimal solution and not with a poor one and then improve (or rather repair) it, if at all possible.
    A good design is one that works correctly with as few harsh boundary conditions as possible. Ideally, under all conditions. A great many amateur circuits work only because the parameters of the components used and the operating conditions have happily "aligned". These are bad solutions, even though they work.
    Janusz_kk wrote:
    the transistor is a full-fledged transistor only the gate is controlled a little differently than usual.
    As you can see, servicing automation even for a lifetime does not make a person an electronics engineer. So does a badge on a suit or a position held. And not to be surprised, I know that this is rather the rule. It's just a pity that such 'revelations' become part of the online knowledge resource that students try to draw on. And then we are surprised that everything goes downhill.
  • #44 21897447
    Janusz_kk
    Level 39  
    Posts: 5700
    Help: 216
    Rate: 1431
    elukam wrote:
    As you can see servicing automation even for a lifetime does not make a person an electronics engineer.

    I think you mean yourself, I don't comment any more because I don't want to get banned by you. i can only recommend learning and reading pdfs because even this is going poorly for you, compare the parameters of a darlington optocoupler with a digital output from a prck as proposed by the author or a regular npn transistor.
  • #45 21905745
    filipcichowskidev
    Level 11  
    Posts: 72
    Help: 4
    Rate: 125
    >>21897404

    The previous speaker was right about the main application. You are confusing the optocoupler with the phototransistor itself. An optocoupler is not a single transistor, but a complete circuit (transmitting diode + detector) enclosed in a single housing, designed precisely to provide galvanic isolation. Yes, there is usually a transistor at the output, but due to the huge non-linearity of optical transmission, using an optocoupler as a classical signal amplifier is not worthwhile.

    Congratulations on 50 years in industrial automation service, that's an impressive result. Regardless of seniority, the physics of the components remains the same - and confusing a complete optoisolator circuit with a single transistor is simply a factual error.
  • #46 21905755
    Janusz_kk
    Level 39  
    Posts: 5700
    Help: 216
    Rate: 1431
    filipcichowskidev wrote:
    The previous speaker was right about the main application.

    I see you are not letting go, you must have the final say.
    filipcichowskidev wrote:
    You are confusing the optocoupler with the phototransistor itself.

    I'm not confusing anything, it's you who doesn't understand electronics.
    filipcichowskidev wrote:
    Of course, there is usually a transistor at the output, but due to the huge non-linearity of the optical transmission, using an optocoupler as a classical signal amplifier misses the point.

    And that's why you're babbling nonsense, here non-linearity has no meaning, but you don't get it.
    filipcichowskidev wrote:
    Regardless of seniority, the physics of the components remains the same - and confusing a complete optoisolator circuit with a single transistor is simply a factual error.

    and you plunge even further with such 'wisdom'. Go into philosophy rather than electronics, you'll do better.
    For my part EOT, because I don't want to get banned by a philosopher like you.

    Moderated By Felini:

    3.1.9. Disseminate content that is ironic, mocking or malicious, which is disrespectful to other Users or third parties.

  • #47 21905775
    filipcichowskidev
    Level 11  
    Posts: 72
    Help: 4
    Rate: 125
    >>21905755

    Incredibly rude response considering I responded in a factual manner. I advise against treating people this way, it doesn't get you anywhere.

    You know very little about me. Well I design electronics for satellites on a daily basis, several of my developments are already flying in orbit, so think before you start insulting me.

    You are recommending that I practice philosophy, so I assume that you have experience in this matter yourself.

    Contemplate and think why the arrangement you cite with a relay in the emitter will work, but is not optimal.

    The correct answer: the transistor in this configuration will not be able to enter deep saturation and you will have unnecessary power loss on it.

    A little humility won't hurt and may help.

    And you can only get banned for your rudeness, I don't tell you to treat people like pigs in a pigsty.
📢 Listen (AI):

FAQ

TL;DR: At 24V with Rb = 1kΩ, the MCU pin may sink about 23mA, and one commenter called the idea “not very elegant but it works.” This FAQ is for engineers deciding whether a Zener-plus-PNP relay driver solves startup-safe 5V MCU control of 12V or 24V relays better than NPN, level-shifter, or optocoupler alternatives. [#21893578]

Why it matters: If a legacy 8051-family MCU briefly presents a logic-high-like state at reset, the wrong relay driver can energize loads at power-up.

Approach Parts discussed Main benefit Main drawback
PNP high-side + Zener transistor + Zener + base resistor Can keep relay off during certain 8051 startup states Sensitive to rail tolerance and GPIO behavior
Classic NPN low-side NPN + resistor Familiar, simple, widely used May turn relay on during reset in some 8051 cases
Common-base level shifter 2 transistors + resistor(s) More robust level shifting More parts than the Zener trick
Optocoupler / module optocoupler + driver stage Isolation, less dependence on coil rail stability More components and cost

Key insight: The thread’s consensus is not that the Zener-plus-PNP circuit never works. The real takeaway is that it only makes sense for narrow startup-behavior problems in older MCU families, and even then several participants prefer more robust alternatives.

Quick Facts

  • The proposed Zener window is 6.3V < Vz < 11.3V for a 12V rail and 18.3V < Vz < 23.3V for a 24V rail, derived from keeping the PNP off at 5V and on at 0V. [#21893011]
  • Suggested nominal Zeners were 9.1V for 12V rails and 20V or 22V for 24V rails; the post names BZX55C9V1, BZX55C20, and BZX55C22. [#21893011]
  • The original sizing advice was Rb = 1kΩ as a default, 2.2kΩ to reduce MCU pin current, and 470Ω for collector currents above about 100mA. [#21893011]
  • One practical warning is that at 24V with Rb = 1kΩ, the author estimated about 23mA into the MCU pin in LOW state, which sits near the lower edge of the cited 20–40mA typical GPIO range. [#21893011]
  • The flyback diode was specified as 1N4148, connected across the relay coil with cathode to collector and anode to GND, even though it was omitted from the ASCII sketch for readability. [#21893011]

How do I choose the Zener diode voltage for driving a 12V or 24V relay from a 5V MCU with a PNP transistor?

Choose Vz so it conducts when the MCU outputs 0V and stops conducting at 5V. The thread gives this range: VCC - 5.7V < Vz < VCC - 0.7V. For 12V, that means 6.3V to 11.3V, with 9.1V recommended. For 24V, that means 18.3V to 23.3V, with 20V or 22V suggested. A 20V Zener gives more turn-on margin, while 22V gives more turn-off margin. [#21893011]

Why would someone use a PNP high-side relay driver with a Zener diode instead of the classic NPN low-side transistor circuit?

They use it to avoid relay activation during power-up on some older MCUs. The author says certain controllers, including AT89C2051-class parts, can present a startup condition that would turn on a classic NPN low-side relay stage before I/O initialization. The Zener-plus-PNP approach makes the relay active on MCU LOW, not HIGH, so the default startup behavior can be safer for that narrow use case. Several participants still judged the classic NPN or two-transistor alternatives better overall. [#21893158]

What base resistor value should I use in this Zener-plus-PNP relay driver, and when should Rb be changed from 1kΩ to 2.2kΩ or 470Ω?

Start with 1kΩ. The original post calls 1kΩ a universal value, suggests 2.2kΩ to reduce the current the MCU must sink, and suggests 470Ω when collector current exceeds about 100mA. In practice: 1. Use 1kΩ for ordinary relay coils. 2. Raise to 2.2kΩ if GPIO current margin is tight. 3. Drop to 470Ω only when the PNP needs more base drive for heavier loads. [#21893011]

Why does this relay control method matter with AT89C2051 or AT89S8252 microcontrollers during power-up and reset?

It matters because these older 8051-family parts were discussed as problematic during reset and early startup. Multiple posters linked the idea specifically to AT89C2051 and AT89S8252, where a classic NPN relay stage can briefly energize the relay before firmware initializes the port. That makes the topology relevant when a short unwanted relay pulse could cause a fault, especially in legacy industrial controllers. [#21893165]

What is a common-base level shifter circuit, and how could it replace the Zener diode approach in relay control?

“Common-base level shifter” is a transistor stage that translates one logic voltage to another, keeping the base at a fixed reference while the signal passes through the emitter-collector path. In the thread, it was proposed as a long-used alternative that handles “unruly” MCU outputs better than the Zener trick. Several users preferred it because it avoids depending on a narrowly chosen Zener voltage and is less sensitive to supply variation. [#21893324]

What is an open-collector (OC) or open-drain (OD) output, and why was it mentioned in the discussion about GPIO safety?

“Open-collector” or “open-drain” output is a switching output stage that actively pulls low but does not actively drive high, so an external pull-up defines the HIGH level. It was mentioned because one poster argued that if the GPIO is effectively high-impedance in HIGH state, the Zener anode can float upward toward 12V, which raises safety concerns for the MCU pin. That criticism targeted the schematic’s behavior, not just its math. [#21893897]

How should the flyback diode be connected across a relay coil in this PNP high-side circuit, and why was 1N4148 suggested?

Connect the flyback diode directly across the relay coil, with cathode to the transistor collector and anode to GND. The original post explicitly recommends 1N4148 and says the diode is essential, even though it was omitted from the ASCII drawing for readability. Its job is to clamp the coil’s inductive kick when the relay turns off and protect the switching transistor. [#21893011]

PNP with Zener diode vs NPN transistor vs optocoupler module like LTV817 or HL-525: which relay driver approach is better for 5V-to-12V or 24V control?

The better approach depends on the failure you must prevent. The thread treats the Zener+PNP stage as workable but niche, the NPN stage as the normal simple option, and the LTV817/HL-525 optocoupler style as better when you want galvanic isolation and less dependence on a stabilized coil rail. One participant also preferred a shared P-channel MOSFET power gate for all coils over changing every single relay driver. [#21893669]

Why do some users report getting about 11V on the GPIO in LTspice when simulating this circuit, and what does that say about the schematic?

They report it because the schematic representation was disputed and likely misleading. One user said LTspice showed about 11V on the GPIO, while another clarified that the image posted later was only a redraw of the original ASCII art and was not analyzed or corrected. That means the simulation result says as much about the ambiguous drawing as about the intended circuit. [#21893524]

Which 8051-family MCU pin behavior during reset is relevant here, and how do the AT89C2051 ports actually behave at startup?

The relevant behavior is that some 8051-family ports do not act like modern push-pull GPIO at reset. In the thread, users say the AT89C2051 startup state is effectively an input with a pull-up, not a strong logic-high output, and another poster says there is “only a weak one or a strong zero.” That distinction matters because startup relay behavior depends on weak pull-up current, not just voltage level. [#21893669]

How much current does the microcontroller pin really sink in this circuit at 12V or 24V, and is that safe for typical AVR, PIC, or 8051 GPIO limits?

The original estimate is about 23mA at 24V with Rb = 1kΩ, ignoring Zener dynamic resistance. The same post says this sits within a typical 20–40mA GPIO limit for many MCUs, including AVR, PIC, and 8051-class devices, but recommends 2.2kΩ if you want more safety margin. That makes the circuit plausible, but it leaves little headroom on weak or legacy ports. [#21893011]

What happens in the real circuit, not just in ideal calculations, if I disconnect the MCU pin and measure the Zener anode voltage with a voltmeter?

In the real circuit, the node may not stay at a safe logic-level voltage. One participant challenged the idealized math and said to physically disconnect the MCU pin and measure the Zener anode to ground, implying the node can rise due to leakage and non-ideal Zener behavior. Another poster separately warned that the anode can effectively “hang in air,” which is the core practical objection to the design. [#21893971]

How can I stop relays from briefly turning on during MCU reset without using this Zener diode trick?

Use a driver topology that blocks relay power until firmware is alive. The thread suggests three practical alternatives: 1. Use a two-transistor stage instead of the Zener trick. 2. Use a common-base level shifter. 3. Gate the relay supply with a shared circuit, such as a watchdog-controlled stage or a P-channel MOSFET, then enable it only after initialization. Those methods target the reset glitch directly. [#21893578]

When is it better to use a hardware watchdog or a P-channel MOSFET relay power gate instead of changing the individual relay driver topology?

Use them when many relays share the same risky startup condition. One poster recommended a hardware watchdog that applies power to all relays only when it sees a square wave on one MCU pin. Another described using a P-channel MOSFET plus LTV817 so one control line disconnects power to every coil until initialization finishes. That can simplify a multi-relay design more than redesigning each channel. [#21893669]

What supply-voltage tolerance problems can make all relays switch on in this design, and how stable does the 12V or 24V rail need to be?

If the supply rises enough, the Zener threshold window can shift from “relay off” to “relay on.” One critic warned that “just a jump of a few V” could switch on all relays, especially on a 24V industrial rail. The author answered that the rail must be stabilized and cited using a 7812 regulator in practice. So this design needs a controlled coil supply more than a classic low-side NPN stage does. [#21893158]
Generated by the language model.
ADVERTISEMENT