Saturday, November 12, 2016

IOT: Java + Raspberry Pi + Pi4j + 4 Channel Relay

Objective: The Objective of this exercise is to configure a 4 Channel Relay Switch with Raspberry Pi and control it (by switching it ON and OFF) using GPIO pins on Raspberry Pi.
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 all the LED's ON in the 4 channel Relay, wait for 2 Seconds, turn OFF all the LED's on the 4 Relay’s one after the other with a delay of 1 second each and then finally turn OFF all the LED's (one after the other).
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)
5 Jumper wires
4 Channel Relay
Breadboard
GPIO Ribbon Cable

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 11 (GPIO 0) to Relay IN1
2) A wire from Pin 12 (GPIO 1) to Relay IN2
3) A wire from Pin 13 (GPIO 2) to Relay IN3
4) A wire from Pin 15 (GPIO 3) to Relay IN4
5) A wire from Pin 2 (5 V Power) to Relay VCC (+)
6) 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 RelayCircuit.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.RelayCircuit" -Dexec.classpathScope=runtime

9.  If all the wiring is done correctly, now you should see the all the LED's on the Relay with turn ON for 2 seconds, then all the LED's will be turned OFF one after the other for every 1 second gap,  turn ON all the LED's, then finally turn OFF the Relay OFF.
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 Stepper Motor.
<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: 
1. Maven Compiler configuration should be set to Java 1.7 or above for this program to run because we are using the byte API’s which will work only with Java 1.7 or above.
byte[] half_step_sequence = new byte[8]
<build>
<plugins>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.5.1</version>
               <configuration>
                  <source>1.7</source>
                  <target>1.7</target>
               </configuration>
            </plugin>
      </plugins>
</build>
2. 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) RelayCircuit.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 4 GPIO pins – GPIO_00, GPIO_01, GPIO_02, and GPIO_03 of Raspberry Pi to communicate with 4 Channel Relay Circuit. Now provision these 4 pins as output pins with Pin State as HIGH (means Relay OFF) while initializing  and change the state to LOW (means Relay ON) with the following lines of code:
System.out.println("All LED's on Relay will turn ON..");
GpioPinDigitalOutput relayLED1 = gpioRelayLED1.provisionDigitalOutputPin(RaspiPin.GPIO_00,"RelayLED1",PinState.HIGH); //OFF
relayLED1.low(); //ON
  
final GpioController gpioRelayLED2 = GpioFactory.getInstance();          
final GpioPinDigitalOutput relayLED2 = gpioRelayLED2.provisionDigitalOutputPin(RaspiPin.GPIO_01,"RelayLED2",PinState.HIGH); //OFF
relayLED2.low();  //ON
        
final GpioController gpioRelayLED3 = GpioFactory.getInstance();          
final GpioPinDigitalOutput relayLED3 = gpioRelayLED3.provisionDigitalOutputPin(RaspiPin.GPIO_02,"RelayLED3",PinState.HIGH); //OFF
relayLED3.low(); //ON
        
final GpioController gpioRelayLED4 = GpioFactory.getInstance();          
final GpioPinDigitalOutput relayLED4 = gpioRelayLED4.provisionDigitalOutputPin(RaspiPin.GPIO_03,"RelayLED4",PinState.HIGH); //OFF
relayLED4.low(); //ON
3.  Now introduce some delay of 2 seconds, before we turn all the LED’s OFF on Relay. This function will invoke the Thread.sleep() with the milliseconds passed as input.
introduceDelay(2000);
/**
       * 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.  Now turn ON the LED’s on the Relay by invoking the low() method on each of the relayLED instance and by introducing a delay of 1 millisecond in between.
System.out.println("All LED's on Relay will turn ON again..");
            introduceDelay(1000);
            relayLED4.low(); //ON
            introduceDelay(1000);
            relayLED3.low(); //ON
            introduceDelay(1000);
            relayLED2.low(); //ON
            introduceDelay(1000);
            relayLED1.low(); //ON
   introduceDelay(1000);
5.  Now turn OFF the LED’s on the Relay by invoking the high() method on each of the relayLED instance and by introducing a delay of 1 millisecond in between.
System.out.println("All LED's on Relay will turn OFF..");
            relayLED1.high(); //ON
            introduceDelay(1000);
            relayLED2.high(); //ON
            introduceDelay(1000);
            relayLED3.high(); //ON
            introduceDelay(1000);
            relayLED4.high(); //ON
6. That’s the end of the tutorial. Hope it was useful.

No comments:

Post a Comment