Saturday, November 12, 2016

IOT: Java + Raspberry Pi + Pi4j+ 4 Channel Relay + Connected to Mains to control Light bulb or Laptop Charger




Objective: The Objective of this exercise is to configure a Relay Switch with Raspberry Pi and control it with 5V (by switching it ON and OFF) using GPIO pins on Raspberry Pi, which in turn controls (by switching it ON and OFF) the Main Power (220V) to operate any electrical devices (like Light bulb or Laptop Charger etc).

YouTube Video:
The YouTube Video for this tutorial is available at this link.
GitHub Source:
https://github.com/agilerules/IOT/tree/master/iot-pi4j-raspi-relay

Task details:
Once the application is successfully setup (as per the instructions below) and once you run the Java program, it will turn ON the LED in the IN1 Relay (of 4 channel Relay), which in-turn will turn ON the Light bulb or Laptop Charger connected. The program will wait for 10 Seconds and then turn OFF the LED in the IN1 Relay (of 4 channel Relay), which in-turn will turn OFF the Light bulb or Laptop Charger.
Overview about Relay:
What are relays?
A relay is an electromagnetic switch operated by a relatively small electric current that can turn on or off a much larger electric current. The heart of a relay is an electromagnet (a coil of wire that becomes a temporary magnet when electricity flows through it). You can think of a relay as a kind of electric lever: switch it on with a tiny current and it switches on ("leverages") another appliance using a much bigger current. 
Why Relay’s are useful? 
As the name suggests, many sensors are incredibly sensitive pieces of electronic equipment and produce only small electric currents. But often we need them to drive bigger pieces of apparatus that use bigger currents. Relays bridge the gap, making it possible for small currents to activate larger ones. That means relays can work either as switches (turning things on and off) or as amplifiers (converting small currents into larger ones).
How Relays work?
Note: The below concept is a extract from http://www.explainthatstuff.com/howrelayswork.html
When power flows through the first circuit (1), it activates the electromagnet (brown), generating a magnetic field (blue) that attracts a contact (red) and activates the second circuit (2). When the power is switched off, a spring pulls the contact back up to its original position, switching the second circuit off again.
This is an example of a "normally open" (NO) relay: the contacts in the second circuit are not connected by default, and switch on only when a current flows through the magnet. Other relays are "normally closed" (NC; the contacts are connected so a current flows through them by default) and switch off only when the magnet is activated, pulling or pushing the contacts apart. Normally open relays are the most common.
Dependencies:
Software:
Pi4j
Java
Maven (Please find my blog here on how to install Maven on Raspberry Pi)
Hardware:
Raspberry Pi (installed with Java, Maven)
3 Jumper wires
4 Channel Relay
Breadboard
GPIO Ribbon Cable
Thick Electrical Wire (4Ft) for 3 pin
3 pin plug (to be connected to end of Electrical Wire)
3 pin socket with Switch (to be connected to other end of the Electrical Wire). The Switch here is optional.
Wire Cutter
Small Screw Driver (to screw the wiring to the Relay)
Insulation Tape
Knife (or any equivalent device) to cut the thick Electrical Wire


Steps:
1.  Complete the following Wiring process of Raspberry Pi, 4 Channel Relay and with few jumper wires as shown in the below diagram. Ensure that the Raspberry Pi is in Power OFF mode, while doing the wiring process.
Wiring Diagram:

Breadboard Diagram:
1) A wire from Pin 12 (GPIO 1) to Relay IN1
2) A wire from Pin 2 (5 V Power) to Relay VCC (+)
3) A wire from Pin 6 (Ground) to Relay GND (-)




2.  Once the above connection is complete, Power ON the Raspberry Pi. Now connect to Raspberry Pi using Putty with your Raspberry Pi Credentials and by-default, you will in the path /home/pi. 
3.  For proper organization purpose, I created folders (using mkdir command) \projects. But this is not mandatory. You can even skip this step and move to next step.
mkdir projects
4.  From the \projects folder, execute the following command to Git clone the code to your local raspberry Pi.
git clone https://github.com/agilerules/IOT.git
5.  Once the git clone is complete, you will see IOT folder created in \projects folder. Now go to IOT folder (using the command cd IOT) and you will see the folder iot-pi4j-raspi-relay inside this folder IOT.
6.  Move to this iot-pi4j-raspi-relay folder (using the command cd iot-pi4j-raspi-relay)
7.  Now run the following commands to perform maven clean and maven package. (Incase if mvn command is not recognized then it means that maven is not installed on your Raspberry Pi.  Please follow my blog on how to install Maven on Raspberry Pi.
mvn clean

mvn package
8.  Now execute the following command to start the maven build and run the Java class RelayCircuitWithMains.java in standalone mode. (Incase if mvn command is not recognized then it means that maven is not installed on your Raspberry Pi.  Please follow my blog on how to install Maven on Raspberry Pi.
mvn exec:java -Dexec.mainClass="relay.RelayCircuitWithMains" -Dexec.classpathScope=runtime

9.  If all the wiring is done correctly, and once you run the Java program, it will turn ON the LED in the IN1 Relay (of 4 channel Relay), which in-turn will turn ON the Light bulb or Laptop Charger connected. The program will wait for 10 Seconds and then turn OFF the LED in the IN1 Relay (of 4 channel Relay), which in-turn will turn OFF the Light bulb or Laptop Charger.
10.  Here is the source code explanation below:
The complete project structure is available here:
a) Pom.xml:
The below is the library dependency that we need for this application:
pi4j-core – This is for Pi4J to communicate with Raspberry Pi GPIO pins.
pi4j-device – This is for Pi4J to communicate with Relay.
<dependencies>
            <dependency>
                  <groupId>com.pi4j</groupId>
                  <artifactId>pi4j-core</artifactId>
                  <version>1.1-SNAPSHOT</version>
            </dependency>
<dependency>
                  <groupId>com.pi4j</groupId>
                  <artifactId>pi4j-device</artifactId>
                  <version>1.2-SNAPSHOT</version>
            </dependency>
   </dependencies>
Note: 
At the time of wiring this program, the Pi4j 1.1 is available as a SNAPSHOT version and is not available in Maven repository yet. So had to use the OSS Sonatype Repository URL.
<repository>
            <id>oss-snapshots-repo</id>
            <name>Sonatype OSS Maven Repository</name>
            <url>https://oss.sonatype.org/content/groups/public</url>
            <snapshots>
                  <enabled>true</enabled>
                  <updatePolicy>always</updatePolicy>
            </snapshots>
</repository>
b)  RelayCircuitWithMains.java:
This java class has one method named controlRelayCircuit(), which will control the Relay Circuit by switching it ON and OFF. Here are the steps involved:
1.  Pi4j programs can be run with sudo user only. But with version 1.1, it is no more required if the program is enabled to run with Non Privileged Access using the following command.
//This is required to enable Non Privileged Access to avoid applying sudo to run Pi4j programs
GpioUtil.enableNonPrivilegedAccess();

2.  As shown in the wiring diagram section, we are going to use the GPIO pin 1 (GPIO_01) of Raspberry Pi to communicate with IN1 relay of 4 Channel Relay Circuit. Now provision this pin as output pin with Pin State as HIGH (means Relay OFF) while initializing and change the state to LOW (means Relay ON) and which in-turn will turn ON the Light bulb or Laptop Charger connected.
System.out.println("LED's on Relay will turn ON..");
GpioPinDigitalOutput relayLED1 = gpioRelayLED1.provisionDigitalOutputPin(RaspiPin.GPIO_01,"RelayLED1",PinState.HIGH); //OFF
relayLED1.low(); //ON

3.  Now introduce some delay of 10 seconds by invoking introduceDelay(10000) and turn the IN1 Relay OFF by invoking high() method, which in-turn will turn OFF the Light bulb or Laptop Charger connected. This introduceDelay() function will invoke the Thread.sleep() with the milliseconds passed as input. 
introduceDelay(10000);
System.out.println("LED's on Relay IN1 will turn OFF..");
relayLED1.high(); //OFF


/**
       * Introduce Delay with parameter in milliseconds
       * @param n Delay parameter in milliseconds
       */
      public void introduceDelay(int n){
            try {
System.out.println("Wait for "+ (n/1000) +" seconds..");
                  Thread.sleep(n);
            } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
}
4.  That’s the end of the tutorial. Hope it was useful.

No comments:

Post a Comment