Reader small image

You're reading from  Raspberry Pi 3 Projects for Java Programmers

Product typeBook
Published inMay 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781786462121
Edition1st Edition
Languages
Right arrow
Authors (3):
John Sirach
John Sirach
author image
John Sirach

John Sirach works as a Product Owner at Greenhouse Innovation. He has more than 10 years of experience with Internet-related disciplines from connectivity to hosting and Internet Of Things. Currently, he is involved in the open source "PiDome Home Automation platform" project as a passionate Java and JavaFX software developer and project maintainer. In the past 10 years, he has gained experience with large-scale web applications committed to online services with the most experience gained in frontend web development and application middleware.
Read more about John Sirach

Pradeeka Seneviratne
Pradeeka Seneviratne
author image
Pradeeka Seneviratne

Pradeeka Seneviratne is a software engineer with over 10 years' experience in computer programming and systems design. He is an expert in the development of Arduino- and Raspberry Pi-based embedded systems. Pradeeka is currently a full-time embedded software engineer who works with embedded systems and highly scalable technologies. Previously, he worked as a software engineer for several IT infrastructure and technology servicing companies. He collaborated with the Outernet project as a volunteer hardware and software tester for Lighthouse- and Raspberry Pi-based DIY Outernet receivers based on Ku band satellite frequencies. He is also the author of five books: Internet of Things with Arduino Blueprints [Packt Publishing] IoT: Building Arduino-Based Projects [Packt Publishing] Building Arduino PLCs [Apress] Raspberry Pi 3 Projects for Java Programmers [Packt Publishing] Beginning BBC micro:bit [Apress]
Read more about Pradeeka Seneviratne

View More author details
Right arrow

Automatic Light Switch Using Presence Detection

Now that we have our Raspberry Pi 3 up and running we can start with our first project that uses it. In this chapter, we will be doing presence detection using the integrated Bluetooth chip and show it on a HD44780 16x2 display. As only showing presence will not fill the whole display, we will be adding light intensity detection and environmental temperature. We would also like to add a home automation factor to this setup by adding a relay that can turn on a light. This little project could possibly be placed at a strategic location such as an entry hallway on which we will focus.

We would like to turn on a light switch when we're nearly home when the light in the hallway is quite dim and show the current temperature. This chapter will then cover the basics of using libraries in other projects in the book.

To be able to build this, we will be covering the following...

Introduction to and installing Fritzing

If you already know about Fritzing, you can skip this section and continue to the Bill of Materials section.

Fritzing is one of the most popular and most commonly used free and open source electronic schematics designers used by electronics hobbyists. This application also makes it very easy for beginners, as schematics are built using drawings from actual devices.

The community surrounding this application is very large, resulting in a lot of schematics made available for download and electronic parts being added at a large rate. I advise that after reading the book, you take a closer look at the community part as you will be able to build a lot of applications with the knowledge gained.

To install Fritzing, all we need to do is go to the Fritzing website at http://fritzing.org and click the Download link on the top of the website. The installation is explained in full detail...

Billing of materials

To be able to realize our build, we need the following components:

  • A breadboard
  • A Raspberry Pi, of course
  • A Raspberry Pi 3 T-Cobbler or male to female jumper wires
  • Breadboard wires
  • Three 10 Kohm resistors
  • A Hitachi HD44780 16x2 character display
  • One 10 Kohm potentiometer
  • One 4.7 Kohm resistor
  • A 1 µF capacitor
  • A LDR a.k.a. LDR
  • One BC546B NPN transistor
  • One 5V switchable mechanical relay, such as a Keyes 5V relay module or similar
  • One 1N4148 diode
  • A device capable of being detected by Bluetooth, such as a mobile phone

How to emulate reading analog values on digital pins

Let us start with some theory. The Raspberry Pi only has digital pins. This results in being unable to read analog values. But with some devices, we are able to read analog values, or rather, create an RC Circuit to cheat a little bit. An RC circuit is a circuitry setup where we place a resistor and a capacitor in series with each other. When a voltage is applied on the circuit, the voltage across the capacitor will rise. The higher the resistor value is, the longer it will take for the voltage to rise across the capacitor.

With a fixed resistor, the time to equalize the voltage before and after the resistor around the capacitor will be the same. When we introduce an LDR, where the resistor value depends on the light intensity, the more light that hits the sensor, the lower the resistance is. With this in mind, we take a look at a feature on the digital pins on...

Starting our project and installing the necessary libraries

This project is available for download and can be opened within NetBeans. The only thing we need to do is change the project's properties so it is able to be run on the Raspberry Pi. When the project is opened, go to the project's Properties and by selecting the Run node on the left side, we can change the Runtime Platform to the Raspberry Pi platform. This is explained in detail in Chapter 1, Setting up Your Raspberry Pi, in the Our First Remote Java Application section.

For our project, we need a couple of libraries. We will be using the libraries from the Pi4J project that enable us to interact with the Raspberry Pi pins and use BlueCove libraries to be able to interact with the Bluetooth chip.

Although the libraries are available in the project, it will be useful to know how these are added to the project if you start afresh. This will be...

The Pi4J libraries

The Pi4J library is developed by Robert Savage and is used to interact with the GPIO pins. Communication with the GPIO pins is not done by pure Java but uses a native library developed by Gordon Henderson. This library is bundled within the Pi4J library and is used automatically. The Pi4J project consists of multiple libraries which are as follows:

  • pi4j-core.jar: Always needed, and includes the pi4j native library
  • pi4j-device: Wrappers used for interactions with different kind of peripheral and different Raspberry Pi expansion boards
  • pi4j-gpio-extension.jar: Used by pi4j-device.jar or for custom extension implementations
  • Pi4j-service.jar: Provides listeners for GPIO pins

We will always include all libraries so we are sure to have all the dependencies and will make it easier for you to extend the projects without the need to search for the corresponding libraries of the same version being used...

Adding the HD44780-compatible 16x2 character display

Let's start our project by connecting the 16x2 character display to the Raspberry Pi and show some text on it using Java. When looking around on the Internet for a 16x2 character display, this will often be a HD44780-compatible one. These displays are quite affordable and are used in a lot of projects. Before we attach this display to the Raspberry Pi, we need to check what kind of backlight is being used as there are both LED and EL types. In our schematic and connections, we will be connecting a LCD with an LED backlight.

The character display has a parallel interface, which means we will need a lot of pins to connect the display. We will be communicating in 4-bit mode with the display so we do not need to use all the pins that are available. The pin setup of this kind of display is mostly as follows, ordered by pin number:

  • Ground
  • 5V VCC, (not 3.3V)
  • Contrast...

Showing data on the HD44780-compatible display

Now that we have connected the LCD to the Raspberry Pi, it is time to actually start with the code and display some data. With the project loaded in NetBeans, open the Chapter2.java class, which lives in the, chapter2 package. Let's take a look at the main(String args[]) method.

We see all the methods are commented out. We will be uncommenting these methods throughout the book, so each step will get more obvious, and we will be able to follow and explain all the interactions between the components and the software.

Uncomment the runLcdExample(); method and press the Run (with the green arrow) button in the IDE. NetBeans will start to compile the application; upload it to the Raspberry Pi and run it. If we have set up the wiring correctly, we will see the following screenshot, but of course, with your local time. If you are not able to see the text, we need to adjust...

Adding the light-dependent resistor to the setup

As mentioned earlier, the Raspberry Pi is unable to read analog values. We are going to add the resistor using a RC circuit, as explained earlier. Here, we need the LDR, capacitor, and a 4.7 Kohm fixed resistor. The fixed resistor is used to make sure that when the LDR is completely saturated, which means that there is no resistance anymore, we won't fry our Raspberry Pi. An extra thing we need to keep in mind is that the Raspberry Pi is a 3.3V device. This means that in this schema, we will be using the 3.3V output because we will be reading the input on the Raspberry Pi pin, which cannot be higher than 3.3V.

Here is an image that shows how to attach this RC circuit to the Raspberry Pi:

Shut down the Raspberry Pi and disconnect the power. Let's first take a quick look at the capacitor. The one we are using is an electrolytic capacitor, which has a positive...

Reading and displaying the values from the LDR

Doing this needs some experimentation on the values we want to have, especially because everyone's definition of It is dark is different. Remember, the longer it takes for the pin to detect the high state, the darker it is.

Close all the tabs except the Main class, where we will be uncommenting the next example to run. Scroll to the main function where we will be commenting the runLcdExample(); and uncomment the runLdrExample(); method. This next method runs the example of how to measure light intensity. When the LDR is connected like in the previous directions, you are able to run the application again by pressing the Run button in the button bar. Take a look at the LCD display where we see different text appearing depending on the light intensity surrounding the LDR.

When there is a lot of light, the display could show information as shown in the following screenshot...

Using digital out to switch and display a relay status

For switching a relay, we only need to use one pin on the Raspberry Pi and have its mode set to OUTPUT and turn this high or low to open or close a relay. Most relays need 5V to be able to switch, so we will be using a 2N3904 NPN transistor. With this transistor, we are able to switch a 5V lane with 3.3V so we can switch a relay.

A word of caution: Switching with mains voltages can be very dangerous. Only do this when you are absolutely sure what you are doing. Also, when beginning with relays, make sure you use a mechanical relay as these are able to switch any load up to the maximum rated on the relay.

In our schematic, we will only be switching the relay. This is done for safety reasons (please read A word of caution). When you are more experienced, loads can be added to the relay or a solid-state relay, which suits AC loads better. I would advise that you...

Automatic switch based on environment lighting

In this section, we will be combining the built hardware components to automate the switching of the relay based on the environment lighting, including printing states to the LCD. Let's close all the code tabs in the editor and leave only the Main class open. If not already done, comment the relayExample(); method and uncomment the lightDependentSwitching() method. This last method will instantiate the LdrHandler class and pass on a RelaySwitch object. If you already have been playing with the darkThreshold member value in the LdrHandler class, you can press the Run application button and the application should start switching automatically and update the LCD statuses. When we play a little bit with the environment lighting by putting our hand over the LDR, the relay should close, and when light is reaching the LDR again, the relay should open.

We now have this...

Using the Bluetooth chip on the Raspberry Pi

Since the Raspberry Pi 3, a Bluetooth chip that supports BLE 4.1 has been present on the board. Using Bluetooth from Java can be a challenging thing to do. The latest specification of Bluetooth integration is from the JSR (Java Specification Request)-82 from 2010, which is version 4, and is implemented in J2ME (Java 2 Micro Edition). Although this specification is implemented in J2ME, there are libraries available that provide this specification, although not completely, for J2SE. One of these libraries is called BlueCove.

BlueCove tries to comply with the JSR-82 specification published in 2010. Initial support from BlueCove is for non-ARM based devices. To be able to use Bluetooth on ARM-based devices such as the Raspberry Pi, we will need to create the necessary libraries ourselves or we can use pre-built libraries. The download already contains the libraries we need...

Bluetooth device discovery

We will be only using the device discovery feature as this is the most stable part in the libraries on the Raspberry Pi. Also, there is only one mode available, which I will explain later. Let's close all tabs except for the Main class.

In the main method, have all the methods commented except for the runBluetoothDetectionExample(); method. Follow this method, which causes us to scroll down to the contents of this method:

    /** 
* Runs the Bluetooth device discovery example.
*/
private static void runBluetoothDetectionExample(){
BluetoothDevices example = new BluetoothDevices();
example.init();
try {
System.out.println("Starting device search,
please wait.");
example.runExample();
System.out.println("Search done");
} catch (DiscoveryFailedException ex) {
System...

Putting it all together, our first automation project

It is time to put it all together. As we explained, we want to switch based on presence detection and only when the ambient light reaches a certain level. This is a code-only section. We will be walking through the code and will code some lines ourselves.

If you haven't already, write down or copy the device's Bluetooth address by running the runBluetoothDetectionExample(); one more time as we will be using this address to get a positive detection. When we have the address, we will be writing a couple of lines of code that run all the components we have looked at as a single application. Let's close all open tabs and only open the Main class. Comment the runBluetoothDetectionExample(); method and scroll to the bottom of the class, where we will be adding the following code:

    /** 
* Runs the application.
* @throws LcdSetupException When...

Summary

In this chapter, we have interfaced with a 16x2 character display directly connected to the Raspberry Pi and covered the code used to change the content. We have covered how we are able to read analog data with digital pins by implementing an RC circuit. By attaching a relay with a transistor we have seen how we can switch a 5 V device with a 3 V signal pin that in turn is able to turn on a high-power device. And last but not least, we have taken the first steps with the Raspberry Pi integrated Bluetooth chip to detect nearby Bluetooth devices. This has all led us to our very first home automation project, allowing us to detect presence based on ambient lighting to switch a relay.

As you may have noticed, we looked quite deeply into each step of the code. This is meant as the introduction into the foundations of the Pi4J libraries and how these are used. We have not covered every part yet, only the basics...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Raspberry Pi 3 Projects for Java Programmers
Published in: May 2017Publisher: PacktISBN-13: 9781786462121
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (3)

author image
John Sirach

John Sirach works as a Product Owner at Greenhouse Innovation. He has more than 10 years of experience with Internet-related disciplines from connectivity to hosting and Internet Of Things. Currently, he is involved in the open source "PiDome Home Automation platform" project as a passionate Java and JavaFX software developer and project maintainer. In the past 10 years, he has gained experience with large-scale web applications committed to online services with the most experience gained in frontend web development and application middleware.
Read more about John Sirach

author image
Pradeeka Seneviratne

Pradeeka Seneviratne is a software engineer with over 10 years' experience in computer programming and systems design. He is an expert in the development of Arduino- and Raspberry Pi-based embedded systems. Pradeeka is currently a full-time embedded software engineer who works with embedded systems and highly scalable technologies. Previously, he worked as a software engineer for several IT infrastructure and technology servicing companies. He collaborated with the Outernet project as a volunteer hardware and software tester for Lighthouse- and Raspberry Pi-based DIY Outernet receivers based on Ku band satellite frequencies. He is also the author of five books: Internet of Things with Arduino Blueprints [Packt Publishing] IoT: Building Arduino-Based Projects [Packt Publishing] Building Arduino PLCs [Apress] Raspberry Pi 3 Projects for Java Programmers [Packt Publishing] Beginning BBC micro:bit [Apress]
Read more about Pradeeka Seneviratne