For some projects, you may need to control high-power devices such as a motor, valve, or any 220AC electrical device. Unfortunately, the Raspberry Pi (RPi) cannot handle the power requirements of such devices. The only way to go around this barrier is to include a control interface. We call this interface a relay, and it sits between the RPi and the high-power device.
In this tutorial, I will discuss the concept of a relay, and I will show you how to connect a relay to the RPi to control a high-power device. I will also explain how a relay works and how to control it with Python. However, I will only limit the scope of this article to electromechanical relays. Solid State Relays will be covered in future articles. Finally, I will show you how to connect a 220VAC light bulb and control it when the thermistor reading exceeds a certain threshold.
What is a Relay?
A relay is an electrically operated switch. The difference between a manual switch and a relay is that a manual switch opens or closes circuits through an operator’s physical action. On the other hand, a relay opens or closes circuits when actuated by a low power signal.
A relay consists of four main parts: the electromagnet, movable armature, switch point contacts, and a spring. I will discuss how these components work together to control a high-power current in a safe, low-voltage environment.
Uses for Relays on the RPi
There are different types of relays on the market today, and we mainly rate them depending on the actuation voltage. The most popular ones are 5VDC, 12VDC, 24VDC, and 48VDC coil relays. They can handle load currents of between 1-100 amps, depending on the rating. We use such relays for different purposes, and here are a few examples:
- They provide time delay functions.
- Relays control high voltage circuits in a low voltage environment.
- Use very low current circuits to control high current circuits.
- We can use them as protective relays (overload relays).
- Using relays allows you to control many devices with one switch.
- Ensure electric isolation between controlling and controlled circuits.
How a Relay Works
The following diagram shows the pins of a relay.
Basically, we have pins that connect to the coil (electromagnet), normally open (NO), normally closed (NC), and a common connection (comm). A relay has two main circuits—the primary circuit and the secondary circuit. The primary circuit is the controlling circuit, and it provides the required current to switch ON or OFF the relay. There is an electromagnetic coil that generates a magnetic field when there is a flow of current. This magnetic field attracts a movable armature that is in the relay core. When we remove power to the coil, the movable armature returns to its original position with the help of a small spring. At the end of the movable armature is a movable contactor.
On the other hand, there is a secondary circuit that controls. This is where we connect the load, such as pumps or valves. When the movable armature is attracted to the coil, it closes the circuit on the secondary circuit, thereby providing a direct connection between the Comm and the NO pin.
High Voltage Terminals
We refer to the relay type described above as a Single Pole Double Throw (SPDT) relay. This is because the common connection has a contact that moves between the NO and NC contacts. When the relay is OFF, i.e., when there is no power to the coil, the common contact changes position to the NC contact. Similarly, when we apply an electric current to the coil, the common contact moves from the NC contact to connect with the NO contact. In other words:
- Normally Open is a contact that does not allow current to flow in its normal state, in this case, when the coil is NOT energized. They only allow current to flow in the secondary circuit when the coil is energized.
- Normally Closed is a contact that allows current to flow in its normal state, in this case, when the coil is NOT energized. They will stop the flow of current in the secondary circuit when the coil is energized.
- Common terminal is the part of a relay that moves. It selects between the NC and NO terminals depending on the state of the coil.
How to Wire High Voltage Device to the Relay
The following circuit diagram shows how to connect a high voltage device in the normally open configuration. In this state, the switch SW is open, so no current flows in the primary circuit. Consequently, no current will flow through the relay coil, and the lamp will remain in the OFF state.
In the diagram below, we demonstrate the normally closed configuration. The common terminal will be at the normally closed contact in its normal state, thereby completing the circuit with the 220VAC source. This means that the lamp will be in the ON state.
How to Connect an SRD-5VDC-SL-C 5V Relay to RPi
Now that we have seen how the relay works, it’s time to connect it to our RPi. We will need the following components:
- A transistor as a switch
- 5VDC relay
- Raspberry Pi
Please note that we have included three components: a resistor, diode, and a transistor. There are many uses of transistors out there, but for this tutorial, we will use it to switch ON and OFF the relay. I will explain how a transistor works as a switch in future articles. But in the meantime, here is how we connect a transistor from the RPi to control a relay.
In the circuit diagram above, notice how we connect a diode between a relay’s coils (in parallel with a relay coil). We connect the diode in this configuration to prevent voltage spikes or back electromotive force (EMF) when we disconnect power from the relay.
For us to understand this principle, we need to have the basics of electromagnetic induction. To quickly recall, this is a process of using magnetic fields to produce an EMF. When a current is flowing through the relay coil, a magnetic field is created. So when the current suddenly stops flowing, the magnetic field in the coil needs to dissipate. This causes a huge EMF to build up on the open junctions of the relay coil. A diode will block the flow of back EMF when we connect it with reverse polarity, thereby protecting our circuit.
Programming the SRD-5VDC-SL-C 5V Relay with Python
In this section, we will demonstrate an example project. We will connect the SRD-05VDC-SL-C relay to a 120V-240V lamp and turn on the relay when the temperature reading from a thermistor drops below a threshold value. For that, we are going to add a thermistor (NTC 100K) and a 220VAC source to our list of components.
If you recall, there are a lot of ways to measure the temperature on the RPi (read the article here). But here, we will use an NTC thermistor without ADC. We will also need two resistors and a capacitor. Unlike the Arduino, the RPi does not have a built-in ADC so if we are using analog sensors, we are going to need a clever way of measuring resistive sensors on our RPi. Luckily, we can use the step response of RC circuits to measure the resistive devices in our circuit. The theory of this concept is exhaustive but I will summarize the basics of what we only need to know for this tutorial.
In the diagram above, we see the two charging and discharging curves of a capacitor with a square wave input. If we look at this diagram, we see that when the input voltage suddenly changes from 0 to Vs, the capacitor gradually charges up through the resistor until the voltage across it reaches the battery’s supply voltage. It takes a certain amount of time for the capacitor to fully charge. On the other hand, when the input voltage suddenly changes from Vs to 0V, the charge between the capacitor’s plates decays exponentially. It also takes a certain amount of time for the capacitor to be fully discharged. We can use the equation below to express the time constant as a function of the capacitor voltage and the supply voltage as:
In the equation above, Vc, Vs, and C are known. We will write a program that will measure the time t and R. Using these parameters, we will use the Steinhart-Hart equation to convert the resistance to a temperature value.
NTC Temperature Sensor on the RPi
To use the RC step response concept in our project, we will connect the components as shown in the diagram below. Then we follow the steps below to measure the resistance of our thermistor. This resistance is proportional to the temperature of the environment.
- Make GPIO18 an input. Make GPIO23 an output and write a value of 0 to discharge the capacitor.
- Initialize the time. Convert GPIO23 to an input pin and GPIO18 to an output pin and write a value of 1 to GPIO18. This will charge the capacitor.
- When the capacitor voltage reaches roughly 40% of Vs (RPi pin voltage) The input pin will register the input as HIGH. The time it takes for the pin to change from LOW to HIGH is proportional to the resistance of the thermistor at that time.
NTC Temperature Measurement Python
To get started, I highly suggest you make use of the “pi_analog” library which you can find here. It is a convenient library which you can use to measure resistive circuits on your RPi. Follow the instructions to install the library on your RPi.
git clone https://github.com/simonmonk/pi_analog.git cd pi_analog sudo python3 setup.py install
Now that the library is ready, we will write the Python code. If we use this library, we will only need to write a few lines of code.
from PiAnalog import * import time p = PiAnalog() while True: print("%.2f"% p.read_temp_c(3950,1000)) time.sleep(5)
This library uses Python3, so run the code above with the command
sudo python3 myFile.py. The line
print("%.2f"% p.read_temp_c(3950,1000)) calls the function
p.read_temp_c(), and it passes two parameters which are the NTC constant and the NTC resistance at 25oC. When we run this code, we get the following output:
At this stage, we have successfully managed to convert the resistance measurement of the thermistor into a temperature reading. Finally, we have to combine the thermistor and relay circuits. We will set a threshold of 30oC, and when this value is reached, it will activate a relay and turn ON the light bulb. But before that, we need to prepare the light bulb for this example.
Warning: Be extra careful when you are working with high voltage sources such as 220AC line voltage.
Setting Up the Light Bulb
To connect the light bulb to our relay:
- Select the tools which are convenient to work with. Here, I found a small light bulb stand that has a three-pin round plug.
- Then, select a portion of the cable and carefully strip about 10cm of the insulation. Be careful not to expose the copper as this may short the circuit—something that you would not want to happen especially with 220VAC..
- Carefully cut one cable as shown above.
- Finally, connect one end of the cable to the Comm and the other end to NO contact of the relay. Then connect the power and the signal pins from the RPi. We will connect pin 17 of the RPi to control the relay.
from PiAnalog import * from gpiozero import LED import time p = PiAnalog() relay = LED(17) while True: print("%.2f"% p.read_temp_c(3950,1000)) time.sleep(5) if (p.read_temp_c(3950,1000) > 30): relay.on print("relay ON") else : relay.off() print("relay OFF")
Run the code above with the command
sudo python3 myFile.py. Here, we use the LED library because it is an easy way to control the digital pins of the RPi. We connect the relay to pin 17 and we use the line
if (p.read_temp_c(3950,1000) > 30) to set a threshold of 30oC. If the temperature exceeds that threshold, the light bulb connected to 220VAC and the relay will be switched ON.