I am using a 2n2222 to trigger a 5V relay in an automation home project, this relay will be on for a long time sometimes, I want to know if this is secure and how can I know this.
What are you switching on the other side?
lamps (lamps, all of kinds)
120v?
Please post a circuit diagram, and some information about the power distribution and relay specs.
Less knowing exactly what you have it's sort of impossible to answer your question. I can tell you this. The 2N2222 transistor is a current device which apparently you are using as a switch. That's nice but like all transistors it has its limits. Whatever you are switching we can call a load and how much current the load draws is a key player. You never mentioned that? Things like links to part numbers and schematics go a long way in answering questions.
Thanks
Ron
Yes, because a 2n2222 is a standard part. A "5V relay" isn't.
Link to image: new-schema hosted at ImgBB — ImgBB
no not like that
2N2222 is an NPN which you correctly drew - thank you.
An NPN should be used to switch the low side and due to the coil inductance you should put in a flyback diode to protect the transistor. The base of the transistor needs a resistor to control the amount of current unless you want to burn out the arduino pin.
Due to 127VAC load I would suggest use of optocoupler or some way to isolate the potentially dangerous line voltage from your low voltage circuit.
As for the flyback diode and resistor, thank you very much, because I didn't know that. But as for the optocoupler, I tried to put a 4n35, but it was unable to activate the 5v relay.
place the optocoupler between the relay and ground.
With optoisolator:
larryd has a better idea... I didn't look up the datasheet on the opto... it may not switch as much current as I originally thought.... it's good for up to about 200 mA, that's not bad and should work for those little chinese relays.
If I wanted to turn On/Off AC devices using a uC I would just use a SSR (Solid State Relay) having a control voltage of 3 ~ 30 VDC. They are common and for light loads inexpensive. A Google of "240 VAC 10 Amp SSR" will bring up a few dozen hits and adding Amazon will reflect SSRs off the boat. Just choose based on your current/voltage load and allow some overhead. The SSR allows a wiode control voltage range and includes opto-coupler isolation all in one nice simple package.
Ron
Thanks very much larryd, woframore and Ron_Blain, the last circuit posted by larryd worked. Thanks very much everyone !!!