12. Chapter Relay & LED
In this chapter, we will learn a kind of special switch module, Relay Module.
12.1. Project Relay & Motor
In this project, we will use a Push Button Switch indirectly to control the DC Motor via a Relay.
|
Jumper Wires x11 |
||
Breadboard Power Module x1 |
9V Battery (you provide) & 9V Battery Cable |
||
Resistor 10kΩ x2 |
Resistor 1kΩ x1 |
Resistor 220Ω x1 |
|
NPN-transistor x1 |
Relay x1 |
Motor x1 |
|
Push button x1 |
LED x1 |
Diode x1 |
|
12.1.1. Component knowledge
12.1.1.1. Relay
Relays are a type of Switch that open and close circuits electromechanically or electronically. Relays control one electrical circuit by opening and closing contacts in another circuit using an electromagnet to initiate the Switch action. When the electromagnet is energized (powered), it will attract internal contacts completing a circuit, which act as a Switch. Many times Relays are used to allow a low powered circuit (and a small low amperage switch) to safely turn ON a larger more powerful circuit. They are commonly found in automobiles, especially from the ignition to the starter motor.
The following is a basic diagram of a common Relay and the image and circuit symbol diagram of the 5V relay used in this project:
Pin 5 and pin 6 are internally connected to each other. When the coil pin3 and pin 4 are connected to a 5V power supply, pin 1 will be disconnected from pins 5 & 6 and pin 2 will be connected to pins 5 & 6. Pin 1 is called Closed End and pin 2 is called the Open End.
12.1.1.2. Inductor
The symbol of Inductance is “L” and the unit of inductance is the “Henry” (H). Here is an example of how this can be encountered: 1H=1000mH, 1mH=1000μH.
An Inductor is a passive device that stores energy in its Magnetic Field and returns energy to the circuit whenever required. An Inductor is formed by a Cylindrical Core with many Turns of conducting wire (usually copper wire). Inductors will hinder the changing current passing through it. When the current passing through the Inductor increases, it will attempt to hinder the increasing movement of current; and when the current passing through the inductor decreases, it will attempt to hinder the decreasing movement of current. So the current passing through an Inductor is not transient.
The circuit for a Relay is as follows: The coil of Relay can be equivalent to an Inductor, when a Transistor is present in this coil circuit it can disconnect the power to the relay, the current in the Relay’s coil does not stop immediately, which affects the power supply adversely. To remedy this, diodes in parallel are placed on both ends of the Relay coil pins in opposite polar direction. Having the current pass through the diodes will avoid any adverse effect on the power supply.
12.1.2. Circuit
Use caution with the power supply voltage needed for the components in this circuit. The Relay requires a power supply voltage of 5V, and the DC Motor only requires 3.3V. Additionally, there is an LED present, which acts as an indicator (ON or OFF) for the status of the Relay’s active status.
Schematic diagram
|
Hardware connection. If you need any support,please feel free to contact us via:
|
12.1.3. Sketch
In the project, we will control the ON and OFF of the relay with the button.
12.1.3.1. Sketch_12_Relay
First, enter where the project is located:
$ cd ~/Freenove_Kit/Pi4j/Sketches/Sketch_12_Relay
Enter the command to run the code.
$ jbang Relay.java
After running the code, press the button, the relay will be closed and the indicator light will light up. Press the button again, the relay will be disconnected and the indicator light will go out.
Hardware connection. If you need any support, please feel free to contact us via: support@freenove.com
Each time when the button is pressed, you can see the messages printed on the terminal.
Press Ctrl+C to exit the program.
You can run the following command to open the code with Geany to view and edit it.
$ geany Relay.java
Click the icon to run the code.
If the code fails to run, please check Geany Configuration.
The following is program code:
1///usr/bin/env jbang "$0" "$@" ; exit $?
2
3//DEPS org.slf4j:slf4j-api:2.0.12
4//DEPS org.slf4j:slf4j-simple:2.0.12
5//DEPS com.pi4j:pi4j-core:2.6.0
6//DEPS com.pi4j:pi4j-plugin-raspberrypi:2.6.0
7//DEPS com.pi4j:pi4j-plugin-gpiod:2.6.0
8
9import com.pi4j.Pi4J;
10import com.pi4j.io.gpio.digital.DigitalState;
11import com.pi4j.io.gpio.digital.DigitalOutput;
12import com.pi4j.util.Console;
13import java.util.concurrent.atomic.AtomicBoolean;
14
15public class Relay{
16
17 private static final int PIN_BUTTON = 18;
18 private static final int PIN_RELAY = 17;
19 private static final AtomicBoolean relayState = new AtomicBoolean(false);
20
21 public static void myPrintln(String format, Object... args) {
22 Console console = new Console();
23 console.println(String.format("\u001B[32m" + format + "\u001B[0m", args));
24 }
25
26 private static void updateRelay(DigitalOutput relay, boolean state) {
27 if (state) {
28 relay.high();
29 } else {
30 relay.low();
31 }
32 }
33
34 public static void main(String[] args) throws Exception {
35 final var console = new Console();
36 var pi4j = Pi4J.newAutoContext();
37
38 var relay = pi4j.dout().create(PIN_RELAY);
39 var button = pi4j.din().create(PIN_BUTTON);
40
41 button.addListener(e -> {
42 if (e.state() == DigitalState.LOW) {
43 relayState.set(!relayState.get());
44 myPrintln("Button was pressed. Relay state: %s", relayState.get());
45 updateRelay(relay, relayState.get());
46 }
47 });
48
49 try{
50 myPrintln("The button gpio is %d, the relay gpio is %d", PIN_BUTTON, PIN_RELAY);
51 while (true) {
52 Thread.sleep(500);
53 }
54 }
55 finally{
56 pi4j.shutdown();
57 }
58 }
59}
Create a boolean variable relayState and set the default state to false.
1private static final AtomicBoolean relayState = new AtomicBoolean(false);
Relay control function: According to the value of the Boolean variable state, the Raspberry Pi controls the GPIO output high and low levels, thereby controlling the relay to be attracted and disconnected.
1private static void updateRelay(DigitalOutput relay, boolean state) {
2 if (state) {
3 relay.high();
4 } else {
5 relay.low();
6 }
7}
Each time a button is pressed, the value of relayState is changed and the value of relayState is sent as a parameter to the relay control function. At the same time, a prompt message is printed in the terminal.
1button.addListener(e -> {
2 if (e.state() == DigitalState.LOW) {
3 relayState.set(!relayState.get());
4 myPrintln("Button was pressed. Relay state: %s", relayState.get());
5 updateRelay(relay, relayState.get());
6 }
7});













