Saturday, November 12, 2016

IOT: Java + Raspberry Pi + Pi4j+ 4 Channel Relay + PIR Motion Sensor + Control Electrical bulb connected to Mains



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) based on trigger from PIR Motion Sensor, which in turn controls the Main Power (220V) and switch on an Electrical bulb. This can be considered as a security system where if the PIR Motion sensor senses any movement, it will automatically switch ON the bulb and alert everyone.

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 - the PIR Motion sensor will keep looking for any human movements and as and when it encounters a movement, it will trigger a 5V and turn ON the LED in the IN1 Relay (of 4 channel Relay), which in-turn will turn ON the Light bulb connected to Mains. If there is no movement, the PIR Motion Sensor will not trigger a 5V, which will turn OFF the LED in the IN1 Relay (of 4 channel Relay), which in-turn will turn OFF the light bulb connected to Mains. 
Overview about PIR Motion Sensor:
PIR stands for Passive InfraRed. This motion sensor consists of a fresnel lens, a infrared detector and supporting detection circuitry. The lens on the sensor focuses any infrared radiation/wavelengths present around it towards the infrared detector. Our bodies generate infrared heat and as a result this gets picked up by the motion sensor. The sensor outputs a 5V signal for a period of one minute as soon as it detects us. It offers a tentative range of detection of about 6-7 m and is highly sensitive. When the PIR motion sensor detects a person, it outputs a 5V signal to the raspberry pi through its GPIO. And we define what the raspberry pi should do as it detects an intruder through Java Pi4J coding. Here we are just printing: “Intruder detected”.
The PIR Motion Sensor has 3 pins (as shown in the below diagram):
Pin 1: is a +DC Voltage, usually connected to pin 2 of Raspberry Pi.
Pin 2: is an output pin
Pin 3 is the pin connected to Ground
In certain PIR motion sensors you can even adjust the delay at which the sensor outputs a HIGH signal at the expense of compromising the accuracy. You just need to turn the two knobs on the sensor counter clockwise using a screwdriver.
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)
6 Jumper wires
PIR Motion Sensor
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
1.  Complete the following Wiring process of Raspberry Pi, 4 Channel Relay, PIR Motion Sensor 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:
Relay Connections:
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 (-)
PIR Motion Sensor Connections:
4)  A wire from Pin 16 (GPIO 4) to PIR Motion Sensor Signal
5)  A wire from Pin 2 (5 V Power) to PIR Motion Sensor Power (+)
6)  A wire from Pin 6 (Ground) to PIR Motion Sensor 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.RelayCircuitWithMainsAndPIRMotionSensor" -Dexec.classpathScope=runtime
9.  If all the wiring is done correctly, and once you run the Java program - the PIR Motion sensor will keep looking for any human movements and as and when it encounters a movement, it will trigger a 5V and turn ON the LED in the IN1 Relay (of 4 channel Relay), which in-turn will turn ON the Light bulb connected to Mains. If there is no movement, the PIR Motion Sensor will not trigger a 5V, which will turn OFF the LED in the IN1 Relay (of 4 channel Relay), which in-turn will turn OFF the light bulb connected to Mains.
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) RelayCircuitWithMainsAndPIRMotionSensor.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.
System.out.println("LED's on Relay will turn ON..");
GpioPinDigitalOutput relayLED1 = gpioRelayLED1.provisionDigitalOutputPin(RaspiPin.GPIO_01,"RelayLED1",PinState.HIGH); //OFF
3.  Now initialize the PIR Motion Sensor by provisioning the GPIO pin 4 as Input pin with Pin Pull Resistance as PULL_DOWN.
System.out.println("PIR Motion Sensor is looking for any movement!!!..");
//Create gpio controller for PIR Motion Sensor listening on the pin GPIO_04       
final GpioController gpioPIRMotionSensor = GpioFactory.getInstance();
final GpioPinDigitalInput pirMotionsensor = gpioPIRMotionSensor.provisionDigitalInputPin(RaspiPin.GPIO_04, PinPullResistance.PULL_DOWN);
4.  Now add event listener to the PIR Motion Sensor and if the PIR Motion Sensor event is High (whenever it encounters a human movement) then it will trigger the Relay as Low (which means it will Power ON to Electrical Light) with a message displaying as "Intruder Detected!, Relay is ON and Light is ON". Similarly if the PIR Motion Sensor event is Low (whenever there is no human movement) then it will trigger the Relay as High (which means it will Power OFF to Electrical Light) with a message displaying as "All is quiet, Relay is OFF and Light is OFF”.
//Create and register gpio pin listener on PIRMotion Sensor GPIO Input instance           
         pirMotionsensor.addListener(new GpioPinListenerDigital() {
                 
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
//if the event state is High then print "Intruder Detected" and turn the Relay and Light ON by invoking the low() method
                        if(event.getState().isHigh()){ 
System.out.println("Intruder Detected!, Relay is ON and Light is ON");
                        relayLED1.low(); //ON
                    }  
//if the event state is Low then print "All is quiet.." and make the Relay and Light OFF by invoking the high() method
                    if(event.getState().isLow()){  
System.out.println("All is quiet, Relay is OFF and Light is OFF");
                        relayLED1.high(); //OFF
                    }
                  }
         });
5.  Run this program in loop until the user hits Ctrl+C to exit from the loop.
try {          
                // keep program running until user aborts
                for (;;) {     
                    //Thread.sleep(500); 
                }      
            }          
            catch (final Exception e) {        
                System.out.println(e.getMessage());    
            }finally{
                  System.out.println("LED's on Relay IN1 will turn OFF..");
                  relayLED1.high(); //OFF
         }
6.  That’s the end of the tutorial. Hope it was useful.

No comments:

Post a Comment