Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Raspberry Pi 3 Projects for Java Programmers
Raspberry Pi 3 Projects for Java Programmers

Raspberry Pi 3 Projects for Java Programmers: Get the most out of your Raspberry Pi 3 with Java

Arrow left icon
Profile Icon John Sirach Profile Icon Chandra Profile Icon Seneviratne
Arrow right icon
NZ$64.99
Paperback May 2017 286 pages 1st Edition
eBook
NZ$14.99 NZ$51.99
Paperback
NZ$64.99
Subscription
Free Trial
Arrow left icon
Profile Icon John Sirach Profile Icon Chandra Profile Icon Seneviratne
Arrow right icon
NZ$64.99
Paperback May 2017 286 pages 1st Edition
eBook
NZ$14.99 NZ$51.99
Paperback
NZ$64.99
Subscription
Free Trial
eBook
NZ$14.99 NZ$51.99
Paperback
NZ$64.99
Subscription
Free Trial

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Raspberry Pi 3 Projects for Java Programmers

Setting up Your Raspberry Pi

In the first part of this chapter, we will be setting up a Raspberry Pi 3 with the installation of the official, by the Raspberry Pi foundation, released Raspbian Linux distribution with the help of the NOOBS installer. This will be followed up with any preparations needed to be able to use the onboard hardware and the installation of Java. The second part will cover preparing NetBeans as the editor of choice to write, compile, and deploy our Java applications with a simple Hello World application at the end of the chapter to confirm that our setup works.

Getting started with the Raspberry Pi

With the release of the Raspberry Pi 3, the Raspberry Pi foundation has made a very big step in the history of the Raspberry Pi. The current hardware architecture is now based on a 1.2 GHz 64 bit ARMv7. This latest release of the Raspberry Pi also includes support for wireless networking and has an onboard Bluetooth 4.1 chip available.

Even though the Raspberry Pi 3 has 64-bit ARMv8, the operating system of the Raspberry Pi which is Raspbian confusingly report it is an 32-bit ARMv7. This is because of the Raspbian OS is currently only available in 32-bit.

To get started with the Raspberry Pi you will need the following components:

  • Keyboard and mouse: Having both a keyboard and mouse present will greatly help with the installation of the Raspbian distribution. Almost any keyboard or mouse will work.
  • Display: You can attach any compatible HDMI display, which can be a computer display or a television. The Raspberry Pi also has composite output shared with the audio connector. You will need an A/V cable if you want to use this output.
  • Power adapter: Because of all the enhancements made, the Raspberry Pi foundation recommends a 5V adapter capable of delivering 2.5 A. You would be able to use a lower-rated one, but I strongly advise against this if you are planning to use all the available USB ports. The connector for powering the device uses a micro USB cable.
  • MicroSD card: The Raspberry Pi 3 uses a MicroSD card. I would advise using at least an 8-GB class 10 version. This will allow us to use the additional space to install applications, and as our projects will log data, you won't be running out of space soon.
  • The Raspberry Pi 3: Last but not least, a Raspberry Pi 3. Some of our projects will be using the on-board Bluetooth chip, and this version will also be focused on in this book.

Our first step will be preparing a SD card for use with the Raspberry Pi. You will need a MicroSD card as the Raspberry Pi 3 only supports this format. The preparation of the SD card is being done on a normal PC, so it is wise to purchase one with an adapter fitting a full-size SD card slot. There are webshops selling preformatted SD cards with the NOOBS installer already present on the card. If you have bought one of these preformatted cards you can skip to the Installing Raspbian section.

Getting a compatible SD card

There is a large number of SD cards available. The Raspberry Pi foundation advises an 8-GB card, which leaves space to install different kinds of application and supplies enough space for us to write log data. When you buy an SD card, it is wise to keep your eyes open for the quality of these cards. Well-known and established manufacturers often supply better quality than the counterfeit ones. SD cards are sold with different class definitions. These classes explain the minimal combined read and write speeds. Class 6 should provide at least 6 MB/s, and class 10 cards should provide at least 10 MB/s. There is a good online resource available that provides tested results of using SD cards with the Raspberry Pi. If you need a resource to check for compatible SD cards, I advise you to go to the embedded Linux page at http://elinux.org/RPi_SD_cards.

Preparing and formatting the SD card

To be able to use the SD card, it first needs to be formatted. Most cards are already formatted with the FAT32 filesystem, which the Raspberry Pi NOOBS installer requires, unless you have bought a large SD card it is possible it is formatted with the exFAT filesystem. These then should also be formatted as FAT32. To format the SD card, we will be using the SD association's SDFormatter utility, which you can download from http://elinux.org/RPi_SD_cards, as default OS supplied formatters do not always provide optimal results.

In the following screenshot, the SDFormatter for the Mac is shown. This utility is also available for Windows and has the same options. If you are using Linux, you can use GParted. Make sure when using GParted you use FAT32 as the formatting option. As shown in the screenshot, select the Overwrite format option and give the SD card a label. The example shows RPI3JAVA, but this can be the label of your choice so you can quickly recognize the card when it's inserted:

Press the Format button to start formatting the SD card. Depending on the size of the SD card, this could take some time, enabling you to get a cup of coffee. The utility will show a done message in the form of Card Format complete when the formatting is done. You will now have a usable SD card.

To be able to use the NOOBS installer, you will need to follow the following steps:

  1. Download the NOOBS installer from https://www.raspberrypi.org/downloads/.
  2. Unzip the file with your favorite unzip utility. Most OSes already have one installed.
  3. Copy the contents of the unzipped file into the SD card's root directory so that the copy result is as shown in the following screenshot:
When selecting the NOOBS for download, only select the lite version if you do not mind installing Raspbian using the Raspberry Pi's network connection.

After we have copied the required files into the SD card, we can start installing the Raspbian OS.

Installing Raspbian

To install Raspbian, we need to get the Raspberry Pi ready for use. As the Raspberry Pi has no power on and off button, the powering of the Raspberry Pi will be done as the last step:

  1. At the bottom of the Raspberry Pi on the side you will see a slot to insert your MicroSD card. Insert the SD card with the connectors pointing to the board.
  2. Next, connect the HDMI or the composite connector and your keyboard and mouse. You won't need a network cable as we will be using the wireless functionality built into the Raspberry Pi.
  3. We will now connect the Raspberry Pi with the micro USB power supply.
  4. When the Raspberry Pi boots up, you will be presented with the OSes available to be installed. Depending on the download of NOOBS you have done, you will be able to see if the Raspbian OS is already available on the SD card or if it will be installed by downloading it. This is visualized by showing an SD card image or a network image behind the OS name. In the following screenshot, you see the NOOBS installer with the Raspbian image available on the SD card.
  5. At the bottom of the installation screen you will find the Language and Keyboard drop-down menus. Make sure you select the appropriate language and keyboard selection; otherwise, it will be difficult to enter the right characters on the command line and in other tools requiring text input.
  1. Select the Raspbian [RECOMMENDED] option and click the Install (i) button to start installing the OS:
  1. You will be prompted with a popup confirming the installation as it will overwrite any existing installed OSes. As we are using a clean SD card, we will not be overwriting any.
It is safe to press Yes to start the installation. This installation will take a couple of minutes, so it is a good time to go for a second cup of coffee.
  1. When the installation is done you can press Ok in the popup that appears and the Raspberry Pi will reboot. Because Raspbian is a Linux OS, you will see text scrolling by that relates to services that are being started by the OS.
  2. When all services are started, the Raspberry Pi will start the default graphical environment, called LXDE, which is one of the Linux window managers.

Configuring Raspbian

Now that we have installed Raspbian and have it booting into the graphical environment we can start configuring the Raspberry Pi for our purposes. To be able to configure the Raspberry Pi, the graphical environment has a utility tool installed, which eases up the configuration called Raspberry Pi Configuration:

  1. To open this tool, use the mouse and click on the Menu button on the top left, navigate to Preferences, and press the Raspberry Pi Configuration menu option, as shown in the following screenshot:
  1. When you click on the Raspberry Pi Configuration tool Menu option a popup will appear with the graphical version of the raspi-config command-line tool. In the graphical popup we see four tabs explaining different parts of possible configuration options. We first focus on the System tab, which allows us to:
    • Change the Password
    • Change the Hostname, which helps to identify the Raspberry Pi in the network
    • Change the Boot method to To Desktop or the CLI
    • Set the Network at Boot option
  1. With the system newly installed, the default username is pi and the password is set to raspberry. Because these are the default settings, it is recommended that we change the password.
  2. Press the Change Password button and enter a newly chosen password twice, Once to set the password and the second time to make sure we have entered the new password correctly.
  3. Press Ok when the password has been entered twice.
Try to come up with a password that contains capital letters, numbers, and some strange characters, as this will make it more difficult to guess.
  1. Now after we have set a new password, we are going to change the hostname of the Raspberry Pi. With the hostname we are able to identify the device on the network. I have changed the hostname into RASPI3JAVA, which helps me to identify the Raspberry Pi to be used for the book.
The hostname is used on the CLI, so you will immediately identify this Raspberry Pi when you log in.
  1. By default, the Raspberry Pi boots into the graphical user interface, which you are looking at right now. Because a future project will require us to make use of a display with our application, we will be choosing to boot into CLI mode.
  2. Click on the radio button that says To CLI. The next time we reboot, we will be shown the CLI.
  3. Because we will be using the integrated Wi-Fi connection on this Raspberry Pi, we are going to change the Network at Boot option to have it waiting for the network. Later on in the book we will be creating network-based services and we will be logging in from remote locations. Having the network ready before any service requiring a network connection is a good practice.
  4. Tick the box that says Wait for network.

We have set some default settings, which sets some primary options to help us identify the Raspberry Pi and change the boot mode. We will now be changing some advanced settings that enable us to make use of the hardware provided by the Raspberry Pi:

  1. Click on the Interface tab, which will give us a list of the available hardware provided. This list is as follows:
    • Camera: The Official Raspberry Pi camera interface
    • SSH: To be able to log in from remote locations
    • SPI: Serial peripheral interface bus for communicating with hardware
    • I2C: Serial communication bus mostly used between chips
    • Serial: The serial communication interface
    • 1-Wire: Low data power supplying bus interface conceptual based on I2C
    • Remote GPIO
  1. A future project that we will be working on will require some kind of camera interface. This project will be able to use both the local attached official Raspberry Pi Camera module as well as a USB connected webcam.
  2. If you have the camera module, tick the Enabled radio box behind Camera. We will be deploying our applications immediately from the editor. This means we need to enable the SSH option. By default this already is, so we leave the setting as it is. If the SSH option is not enabled, tick the Enabled radio button behind the SSH option. For now, you can leave the other interfaces disabled as we will only enable them when we need them.
  3. As we now have enabled the default interfaces that we will need, we are going to do some performance tweaking. Click on the Performance tab to open the performance options.
  4. We will not need to overclock the Raspberry Pi, so you can leave this option as it is. Later on in the book we will be interfacing with the Raspberry Pi's display and doing neat tricks with it. For this, we need some memory for the Graphical Processor Unit (GPU). By default this is set to 64 MB. We will ask for the largest amount of memory possible to be assigned to the GPU, which is 512 MB. Put 512 behind the GPU Memory option; there is no need to enter the text MB. The memory on the Raspberry Pi is shared between the system and the GPU. Having this option set to 512 MB results in 512 MB available for the system. I can assure you that this is more than sufficient.
  1. Now that we are done with the system configuration, we are making sure we can work with the Raspberry Pi. Click on the Localisation tab to show the options applicable to the location the Raspberry Pi resides in. We have the following options:
    • Set Locale: Where you set your locale settings
    • Timezone: The time zone you are currently in
    • Keyboard: The layout of the keyboard
    • WiFi Country: The country you will be making the Wi-Fi connection in
  1. This book uses the US-English language with a broad character set. Unless you prefer to continue with your own personal preferences, change the following by pressing the Set Locale button:
    • Language to en (English)
    • Country to US (USA)
    • Character Set to UTF-8
  1. Press the OK button to continue.

As this needs to build up the Locale settings this can take up to about 20 seconds to set up. You will be notified with a small window when this process is finished.

  1. The next step is to set the timezone. This is needed as we want to have time and dates shown correctly.
  2. Click on the Set Timezone button and select your appropriate Area and Location from the drop-down menus. When done, press the OK button.
  3. To make sure that the text we enter in any input field is correct, we are going to set the layout of our keyboard. There are a lot of layouts available, so you need to check yours. The Raspberry Pi is quite helpful and provides many keyboard options.
  4. Press the Set Keyboard button to open up a popup showing the keyboard options. Here, you are able to select your country and the keyboard layout available for this country. In my case, I have to select United States as the Country and the Variant as English (US, with euro on 5).
  5. After you have made the selection, you can test your keyboard setup in the input field below the Country and Variant selection lists. Press the OK button when you are satisfied with your selection.
  1. Unless you are connecting your Raspberry Pi to a wired network connection, we are going to set up the country we are going to make the Wi-Fi connection in so that we are able to connect remotely to the Raspberry Pi. Press the Set WiFi Country button to have the Wifi Country Code shown, which provides us the list of available countries for the Wi-Fi connection. Press the OK button after you have made the selection. We are now done with the minimal Raspberry Pi system configuration.
  2. Press OK in the settings window to have all our settings stored and press No in the popup that follows that says a reboot is needed to have the settings applied as, we are not completely done yet.
  3. Our final step is to set up the local Wi-Fi chip on the Raspberry Pi.

We will now set up the Wi-Fi on the Raspberry Pi. If you want your Raspberry Pi connected with a network cable, you can skip this section and head over to the Set fixed IP section:

  1. To set up the Wi-Fi, click on the Network icon, which is at the top of the screen between the Bluetooth and Speaker Volume icons.
  2. When you click this button, the Raspberry Pi will start to scan for available wireless networks. Give it a couple of seconds if your network does not appear immediately. When you see your network appear, click on it, and if your network is secured you will be asked to supply the credentials required to be able to connect to your wireless network.
If you have any trouble connecting to your wireless network without any messages, log in to your router and change the Wi-Fi channel to a channel lower than channel 11.
  1. When you have entered your credentials and pressed the OK button you will see the icon changing from the two network computers to the wireless icon, as it it trying to connect to the wireless network.
  2. Now that the Raspberry Pi has rebooted, we have configured the wireless network to make sure the wireless network will keep its connection. As the Raspberry Pi is an embedded device targeting low power consumption, the Wi-Fi connection is possible set to sleep mode if after a specific time there is no network usage.
  3. To make sure the Wi-Fi does not go into power sleep mode we will be changing a setting through the command line that will make sure that this won't happen. To open a CLI we need to open a terminal. A terminal is a window that will show the command prompt where we are able to provide commands.
  1. When you look at the graphical interface you will notice a small computer screen icon at the top in the menu bar. When we hover over this icon it shows the text terminal. Press this icon to open up a terminal.
  2. A popup will open with a large black screen showing the command prompt, as shown in the following screenshot:
Do you notice the hostname we set earlier? This is the same prompt as we will see when we log in remotely.
  1. Now that we have a command line open we need to enter a command to make sure the wireless network will not go to sleep after a period of no network activity. Enter the following in the terminal:
           sudo iw dev wlan0 set power_save off
  1. Press Enter. This command sets the power save mode to off so the wlan0 (wireless device) won't enter power save mode and will stay connected to the network.

We are almost done with setting up the Raspberry Pi. To be able to connect to the Raspberry Pi from a remote location we need to know the IP address of the Raspberry Pi. This final configuration step involves setting a fixed IP address into the Raspberry Pi settings:

  1. To open the settings for a fixed IP configuration, we are going to open up the settings by pressing the wireless network icon with the right mouse button and press the WiFi Networks (dhcpcdui) Settings option.
  2. A popup will appear with the settings we can change. As we will only change the settings of the Wi-Fi connection, we select Interface next to the Configure option. When interface is selected, we select the wlan0 option in the drop-down menu next to the interface selection.
If you have chosen to use a wired connection instead of the wireless connection you can select the eth0 option next to the interface option.
  1. We now have a couple of options available to enter IP address-related information. Please refer to the documentation of your router to find out which IP address is available to you which you can use. My advice is to only enter the IP address in the available fields, which leaves the other options automatically configured, like in the following screenshot. Notice that the entered IP address is the correct one; this only applies to my configuration, which could differ from yours:
  1. After you have entered the IP address you can click Apply and Close.
  2. It is now time to restart our Raspberry Pi and have it boot to the Command Line Interface (CLI).
  3. While it is rebooting, you will see a lot of text scrolling, which shows the services starting and at the end, instead of starting, the graphical interface, we are now shown the text-based CLI, as shown in the following screenshot:
  1. If you want to return to the graphical interface just type in the following command:
      startx
  1. Press Enter and wait a couple of seconds for the graphical user interface to appear again. We are now ready to install the Oracle JDK, which we will be using to run our Java applications.

Installing Java

In this section, we will be installing a file transfer application, installing Java, and preparing the NetBeans editor.

We will be using the Oracle JDK to run our Java applications. At the time of writing, the latest version is JDK 1.8, which all our projects will be using as a minimal version:

  1. To get the Oracle JDK, go to http://www.oracle.com/technetwork/java/javase/downloads/index.html and select the Download JDK button.
  2. On the following page you need to select the ARM version to be downloaded. Although the version you will be seeing now may differ from the version mentioned in the book, the naming scheme for the download is the same in all these versions. Even though the Raspberry Pi is now based on a 64-bit architecture the OS is still 32-bit at the time of writing. This also means the version you will need to download is: jdk-8u[buildnumber]-linux-arm32-vfp-hflt.tar.gz, which is the 32-bit version. The [buildnumber] indicates the release build of the JDK. All projects are targeted to work on JDK8, so any build number that is at least 91 or higher should be working. At the time of writing, the JDK version used is jdk-8u91-linux-arm32-vfp-hflt.tar.gz.
  3. To be able to use this Java version we will be using an application to upload the downloaded version to the Raspberry Pi. The application we will be using is called FileZilla and it is available for Windows, Linux, and Mac. To download this application go to https://filezilla-project.org/ and by clicking the Download FileZilla Client link, the application will be downloaded.
  1. To install FileZilla open the downloaded installer and follow the instructions on the screen. We will now upload this Java version to the Raspberry Pi. Open FileZilla, and you will be presented with the window shown in the following screenshot:
  1. To connect we need to enter the credentials that we have set during the installation of the Raspberry Pi. In the most upper part below the icons we will enter the credentials, which are as follows:
  • Only the IP address in the Host field
  • The username pi in the Username field
  • The password we have changed during preparation in the Password field
  • We enter port number 22 in the Port field, which is the secured connection
  1. Press the Quickconnect button, and when all the credentials are entered correctly we are logged in to the Raspberry Pi. On the left side in FileZilla we see the structure of our local computer, and on the right side we see the directory structure of the Raspberry Pi.
  2. Browse to the downloaded Java version on the left side of the application. When you see the Java version that we downloaded click and move this file from the left to the right side. The file will now be uploaded to the Raspberry Pi.
  3. In the most bottom part of FileZilla we see the upload progressing. When the upload is finished, the progress is removed from this list and the upload is done.

We can now close FileZilla and do the final steps required to install this Java version.

  1. For this, we will use the CLI on the Raspberry Pi. There are different ways to get to this command line. On Windows, we can use PuTTY. This is a small application that allows us to log in from the Windows PC onto the Raspberry Pi. On a Mac we can use the terminal application to log in. When we have our keyboard and display connected to the Raspberry Pi we are already logged in. As we will be using the Raspberry Pi as a remote device, we will be using PuTTY on Windows and the terminal on Mac. When you use Mac, you can skip the paragraph where we will be using the terminal.
  2. On Windows, we use PuTTY to connect to the Raspberry Pi. To use PuTTY we need to download it from http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html.
  3. On the second half of this page, we see a list of files ready to be downloaded below the Binaries header.
  1. Click the putty.exe file to download. This file does not need to be installed, so we can save this file in any location that we can easily reach. When PuTTY is downloaded, double-click it to open it so that you see something similar to the following screenshot:
  1. With this window open we can enter the IP address of the Raspberry Pi in the Host Name field.
  2. We would like to save this IP address with a recognizable name, so we enter RASPI3JAVA without the quotes in the Saved Sessions field and press Save.
  3. We now have saved this session for future usage. When we now press Open we are prompted with Login as, where we enter the username pi and press Enter.
  4. The next step is to enter the password we have set during the preparation. When the credentials are entered correctly we are logged in.
  1. To log in on the Mac we use the terminal application, which is preinstalled on the Mac. We open this application by pressing command + space bar at the same time. This will open Spotlight Search, where we can type terminal without quotes and press return or Enter on the keyboard to open the terminal. Hold the option button while clicking on the green circle in the top-left corner to maximize the terminal window.
  2. We are now in the CLI on the Mac. To log in on the Raspberry Pi we need to enter the following command:
       ssh pi@192.168.1.20

The connection we make is done with ssh, which is a small terminal application that creates a secure connection with the Raspberry Pi. We use pi as the username where the @ character literally means at because we log in as this user at the specified IP address. In the preceding command-line example, I have used the 192.168.1.20 IP address of my Raspberry Pi. You should replace this with the IP address you have set for yours. We are now asked to enter the password; enter the password that has been set for the user pi during the preparation.

From this point on it does not matter how we are logged in on the Raspberry Pi as the following steps are the same via Windows with PuTTY, Mac with terminal, or using the keyboard with a display attached to the Raspberry Pi. We are now presented with the CLI on the Raspberry Pi, which gives us the opportunity to unpack and install the Java package we have uploaded to the Raspberry Pi. We will place this installation in the /opt/ directory. To make this possible we first create the java directory inside the /opt/ directory by entering the following command:

    sudo mkdir /opt/java

We use the sudo command because this directory is owned by the root user, which is the administrator on the Raspberry Pi. The sudo command temporarily leverages our privileges to be an administrator for the duration of the command. With mkdir /opt/java we created the java directory inside the /opt/ directory. Now that we have the /opt/java directory we are going to unpack the downloaded Java archive file. We do this by entering the following command:

       sudo tar -C /opt/java -xf jdk-8u91-linux-
arm32-vfp-
hflt.tar.gz

Again we have used the sudo command to leverage our permissions. With the tar utility we unpack the Java archive into the /opt/java directory with the help of the -C parameter line switch. The command line parameters -xf tells the tar utility that we want to unpack the jdk-8u91-linux-arm32-vfp-hflt.tar.gz file. The filename in the preceding example is the version downloaded at the time of writing. Replace 91 with the version you have downloaded.

The Linux command line has a nice way to help you enter commands, directories, and filenames. When you have entered a part of the filename pressing the Tab key will auto-complete the filename.

We can now check if the files have been extracted correctly from the downloaded Java archive. By entering the following command we should see the directory extracted from the archive:

    ls -la /opt/java/

If you see the jdk1.8.0_91 directory, as shown the following screenshot, we have successfully unpacked Java. If you have a different version of the JDK, you will see a different number than 91 at the end:

Installing and preparing the NetBeans Java editor

At this point we have installed and prepared the Raspbian Linux OS and downloaded and installed Java JDK 1.8 on the Raspberry Pi. Our final step is to install and prepare NetBeans with Java as our editor, which is also used to upload and run the applications on our Raspberry Pi. We will be using NetBeans 8.1 as a reference for installing and preparing.

If you are not used to using NetBeans; no problem, we will go step-by-step with downloading and installing and preparing the application. To install NetBeans on your computer we first need to download the correct version onto our PC or Mac. As NetBeans runs on Java, it is also available for Linux-based OSes. To get NetBeans, go to http://www.netbeans.org and press the Download link on the top right of the page. You will be redirected to the download page, where you will see three download options. As we are focused on Java SE, the first and smallest download will suffice for our projects. Press the download button for the left-most download to download the smallest version. After download is completed, we need to install it. The installation procedure is almost identical for all platforms. All platforms have their dedicated installer, and the installation instructions are linked to on the download page below the show download bundles.

When you open NetBeans for the very first time you will be presented with a welcome screen. You can set a mark in the top-right corner of this welcome screen that says Do not show this again. Otherwise it will show up every time we start up the editor. We will now configure NetBeans in such a way that we are able to write our application on our local computer, and when we want to run our code, let NetBeans upload the application to the Raspberry Pi and run it. We will be able to see all the output we normally would see when we log in on the Raspberry Pi and run the Java application in the output window of the NetBeans editor! This will speed up our projects a lot as we do not need to do any manual actions such as uploading and logging in. To make use of this very handy feature we need to configure a Remote platform. To configure the remote platform with the Raspberry Pi, we will adding it to NetBeans.

First, we will be defining the platform itself. In NetBeans, click Tools | Java Platforms. The Java platforms settings dialog will show up:

On the left bottom, click on the Add Platform button. We are now presented with a selection if we want to add a local or a Remote Java Standard Edition. We select the Remote Java Standard Edition and press Next:

We are now presented with a follow up popup were we can enter the details of the remote platform, which is installed on the Raspberry Pi. In the following screenshot, examples are filled in, which we can use for the remote platform:

We just replace the Host IP address with the address that the Raspberry Pi is reachable on. We keep the Username pi and enter the Password we set during the preparation. We set the path to the JDK installation according to the version we have installed. In the example, it is JDK1.8 build 91. Change the 91 to the build you have installed. We do not press the Create button as the directory is already there. As the working directory, we keep the /home/pi/RASPI3JAVA/, so that we know where all our projects will be placed.

Press the Finish button to have NetBeans verify the remote platform and have it download properties from the remotely installed Java version. This action will take a couple of seconds. When you see the following screen, the remote platform has been confirmed by NetBeans:

We press Close to close the dialog so we can begin with our projects.

Our first remote Java application

Now that we have added a remote platform, we will be writing a very simple little Java application to check that it works and have the output from the application executed on the Raspberry Pi and output its information in the editor. We start with a simple Hello World Java application and run it on the Raspberry Pi. The following steps will be needed every time we start a new project.

Click File in the menu bar and click New Project. You will be presented with the New Project wizard, as shown in the following screenshot:

On the left side are the project categories. Here we click on Java, and on the right side we select the Java Application option and press Next to create a Java application. To be able to start with a Java application we need to enter some details so we can begin with our development. The following screenshot shows the details we need to enter to begin:

In this screen we give the project the name, HelloRaspberryPi, and browse to the local directory where we will be putting our project. Make sure you put no spaces in the name of the project! We supply a base path where this project is being placed. In my case, I will place my project in my home directory with the subdirector Raspi3JavaProjects. Other projects that we will be creating later on will also be placed in this directory. NetBeans will automatically create a directory based on the project name in this base directory. Click Finish and the project will be created.

On the left side we have our project structure tree where all our Java packages are, and on the left side we have the editor. This window will be our main projects screen throughout the book, as shown in the following screenshot. This window is the same on all platforms, such as Windows, Linux, and Mac:

Now that we have a new project, we will configure it to run on the remote Raspberry Pi platform. To do this we open the project properties by clicking on the project name in the left side of the window. This opens up a context menu where the bottom option is Properties. When clicked, it opens the Properties window, as shown in the following screenshot:

We click on the Run configuration in the left option tree. We now see the possible run options. We want to run our Java application on the Raspberry Pi, so we change the Runtime Platform to RASPI3JAVA remote or the name you have set in the remote platform configuration. We are asked to save this as a configuration, and we enter a name such as remote Raspberry Pi configuration. Press OK to save our run configuration.

Running our application on the Raspberry Pi

Now we are ready to write a line of code and have it run on a fully prepared Raspberry Pi with Java and a fully prepared NetBeans Java editor. We will change the main run function of our Java application to have it print out Hello from the Raspberry Pi!. Change the code in the main function so that we have what is shown in the following snippet:

    /** 
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hello from the Raspberry
Pi!");
}

For now, this is enough. This will print out the line stated previously. To run this on the Raspberry Pi we have three options. One is to click on the Run button in the button bar below the Menu bar; the second is to right-click on the project name and select Run from the context menu; and the third is to press F6. Pick the one easiest for you.

Now the application is compiling and will be executed on the Raspberry Pi. The output should look same as following screenshot:

This is one of the many reasons why NetBeans is my personal favorite editor. When we look at the output we can see NetBeans building the application and logging in to the remote platform, which in our case is the Raspberry Pi. When logged in it creates a directory called /home/pi/RASPI3JAVA/HelloRaspberryPi/dist. This is the directory the jar file is placed, so it can be executed on the Raspberry Pi. We can see this application being executed by the CLI command: cd '/home/pi/RASPI3JAVA//HelloRaspberryPi'; '/opt/java/jdk1.8.0_91//bin/java' -Dfile.encoding=UTF-8 -jar /home/pi/RASPI3JAVA//HelloRaspberryPi/dist/HelloRaspberryPi.jar

What this does is cd '/home/pi/RASPI3JAVA//HelloRaspberryPi', which makes sure the directory is the correct one. This is followed by the '/opt/java/jdk1.8.0_91//bin/java' -Dfile.encoding=UTF-8 -jar /home/pi/RASPI3JAVA//HelloRaspberryPi/dist/HelloRaspberryPi.jar command, which runs the Java executable with our jar file as input. All the directories we have created and the installed java version is used. Our result is shown with: Hello from the Raspberry Pi!. We can now start with our projects, well done!

Summary

In this chapter you learned essential techniques on how to prepare the Raspberry Pi 3 ready to use with projects will be discussing through out this book. Then you installed Raspbian on the Raspberry Pi 3 followed by Java, installed NetBeans IDE on your computer and connected the Raspberry Pi with the local computer through SSH using PuTTY. Finally, you wrote a simple Java application, deployed it to the Raspberry Pi and run.

In Chapter 2, Automatic Light Switch Using Presence Detection, you will use this basic Raspberry Pi setup to build a automatic light switch which uses presence detection. So you will learn how to expand this basic Raspberry Pi setup by adding some hardware and software components.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore the small yet powerful mini computer in order to run java applications
  • Leverage Java libraries to build exciting projects on home automation, IoT, and Robotics by leveraging Java libraries
  • Get acquainted with connecting electronic sensors to your Raspberry Pi 3 using Java APIs.

Description

Raspberry Pi is a small, low cost and yet very powerful development platform. It is used to interact with attached electronics by the use of it's GPIO pins for multiple use cases, mainly Home Automation and Robotics. Our book is a project-based guide that will show you how to utilize the Raspberry Pi's GPIO with Java and how you can leverage this utilization with your knowledge of Java. You will start with installing and setting up the necessary hardware to create a seamless development platform. You will then straightaway start by building a project that will utilize light for presence detection. Next, you will program the application, capable of handling real time data using MQTT and utilize RPC to publish data to adafruit.io. Further, you will build a wireless robot on top of the zuma chassis with the Raspberry Pi as the main controller. Lastly, you will end the book with advanced projects that will help you to create a multi-purpose IoT controller along with building a security camera that will perform image capture and recognize faces with the help of notifications. By the end of the book, you will be able to build your own real world usable projects not limited to Home Automation, IoT and/or Robotics utilizing logic, user and web interfaces.

Who is this book for?

The book is aimed at Java programmers who are eager to get their hands-on Raspberry Pi and build interesting projects using java. They have a very basic knowledge of Raspberry Pi.

What you will learn

  • Use presence detection using the integrated bluetooth chip
  • Automatic light switch using presence detection
  • Use a centralized IoT service to publish data using RPC
  • Control a robot by driving motors using PWM
  • Create a small web service capable of performing actions on the Raspberry Pi and supply readings
  • Image capture using Java together with the OpenCV framework
Estimated delivery fee Deliver to New Zealand

Standard delivery 10 - 13 business days

NZ$20.95

Premium delivery 5 - 8 business days

NZ$74.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 31, 2017
Length: 286 pages
Edition : 1st
Language : English
ISBN-13 : 9781786462121
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to New Zealand

Standard delivery 10 - 13 business days

NZ$20.95

Premium delivery 5 - 8 business days

NZ$74.95
(Includes tracking information)

Product Details

Publication date : May 31, 2017
Length: 286 pages
Edition : 1st
Language : English
ISBN-13 : 9781786462121
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just NZ$7 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just NZ$7 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total NZ$ 231.97
Full Stack Web Development with Raspberry Pi 3
NZ$56.99
Raspberry Pi 3 Projects for Java Programmers
NZ$64.99
Raspberry Pi: Amazing Projects from Scratch
NZ$109.99
Total NZ$ 231.97 Stars icon
Banner background image

Table of Contents

7 Chapters
Setting up Your Raspberry Pi Chevron down icon Chevron up icon
Automatic Light Switch Using Presence Detection Chevron down icon Chevron up icon
A Social and Personal Digital Photo Frame Chevron down icon Chevron up icon
Integrating a Real-Time IoT Dashboard Chevron down icon Chevron up icon
Wireless Controlled Robot Chevron down icon Chevron up icon
Building a Multipurpose IoT Controller Chevron down icon Chevron up icon
Security Camera with Face Recognition Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela