Earlier, we talked about the level shifter. Raspberry Pi, ESP32 etc things operate at 3.3v logic whereas, relay modules usually need near 5v TTL logic level. In our guide to control AC appliances over the internet with ESP32, you will notice that directly connecting the relay with ESP32 will not properly work – it will work over the internet but when you’ll press the pushbutton, it will go to off state and will not come back in any way. It will appear the code has a bug. Not that. The way the relay oddly getting in to off position upon button press is expected. When we are sending “signal” over the internet, no physical hardware other than relay draining the power. The relay needs marginally more current to properly function. In these situations, we need a level shifter.
For that guide, we used a traditional mechanical relay. For the final projects, we should use solid state relays.
Instead of buying a relay module, in future, you can buy the relay as a component which will reduce the cost. The circuit required to control the relay as a component is closest to the circuit we have provided to create the simple level shifter. You would be using one NPN transistor to convert the push-pull output into an open-collector output. This has the effect of inverting the digital signal, so you would need a second NPN transistor to act as an inverter.
In case of directly controlling the relay, we additionally need a diode. For our present circuit diagram, you can use any general-purpose NPN transistor such as 2N3904 or BC547. You need to supply 5v power, GND and 3.3v signal as shown. There is a slightly modified version of the above circuit :
It is good for learning purpose or when you just do not have one piece ready in hand. Probably we would advise against using transistors. Using logic gate ICs as discussed in the previous article is practical to save time. Using transistors is more complex and likely to cost more. Modules are well tested whereas building from components needs your tests.