Contributions

Contributions are appreciated and used to host this site. Thank You for your support.

Feature Products
  • Raspberry Pi with Java: Programming the Internet of Things (IoT)
    Raspberry Pi with Java: Programming the Internet of Things (IoT)
  • Raspberry Pi 2 Model B Project Board - 1GB RAM - 900 MHz Quad-Core CPU
    Raspberry Pi 2 Model B Project Board - 1GB RAM - 900 MHz Quad-Core CPU
  • Premium Clear Case for Raspberry Pi 2 Model B Quad Core and Raspberry Pi Model B+ (B PLUS)
    Premium Clear Case for Raspberry Pi 2 Model B Quad Core and Raspberry Pi Model B+ (B PLUS)
  • Edimax EW-7811Un 150 Mbps Wireless 11n Nano Size USB Adapter with EZmax Setup Wizard
    Edimax EW-7811Un 150 Mbps Wireless 11n Nano Size USB Adapter with EZmax Setup Wizard
  • Getting Started with Raspberry Pi
    Getting Started with Raspberry Pi
  • Raspberry Pi User Guide
    Raspberry Pi User Guide
  • PiBrella LED Add On Board
    PiBrella LED Add On Board
  • Diversitech® WS-1 - Wet Switch Flood Detector
    Diversitech® WS-1 - Wet Switch Flood Detector
  • Onsite Pro FS1NPTW Whole Home Wireless FloodStop with 1 Inch Valve
    Onsite Pro FS1NPTW Whole Home Wireless FloodStop with 1 Inch Valve
  • Floodstop Washing Machine Valve Shutoff Kit
    Floodstop Washing Machine Valve Shutoff Kit
  • Onsite Pro FS3/4H Washing Machine FloodStop with Straight Valves
    Onsite Pro FS3/4H Washing Machine FloodStop with Straight Valves
  • Floodstop Individual Water Appliance Additional Water Sensor XS-01
    Floodstop Individual Water Appliance Additional Water Sensor XS-01
  • Aqua Managers - FS 1 1/4-NPT - Floodstop for Water Heaters Water Leak Detection System - White - 1.25 in. pipe
    Aqua Managers - FS 1 1/4-NPT - Floodstop for Water Heaters Water Leak Detection System - White - 1.25 in. pipe
  • Furman MP-20 Power Relay Accessory, 20 Amp, Two Outlets, Remote Turn-on from Momentary or Maintained Contact Switches
    Furman MP-20 Power Relay Accessory, 20 Amp, Two Outlets, Remote Turn-on from Momentary or Maintained Contact Switches
  • Furman MP-15 Power Relay Accessory, 15 Amp, Two Outlets, Remote Turn-on from Momentary or Maintained Contact Switches
    Furman MP-15 Power Relay Accessory, 15 Amp, Two Outlets, Remote Turn-on from Momentary or Maintained Contact Switches
  • Metra 70-2002 Radio Wiring Harness for Saturn 00-05
    Metra 70-2002 Radio Wiring Harness for Saturn 00-05
  • Metra Reverse Wiring Harness 71-2002 for Select 2000-2005 Saturn Vehicles OEM Radio
    Metra Reverse Wiring Harness 71-2002 for Select 2000-2005 Saturn Vehicles OEM Radio
Monday
Feb252013

Raspberry Pi - Programming Pi-Face with Java & Pi4J

Overview

I just got my hands on a Pi-Face expansion board for my Raspberry Pi.  I purchased mine direct from Newark and it arrived is less than a week.  My first objective was to get this board integrated into the Pi4J project and fully working with Java on my Raspberry Pi.  This article covers installing the Pi-Face board, setting up the SPI communication driver, and demonstrates programming the Pi-Face in Java.  With the Pi-Face Java API interface now available in the Pi4J libraries (in Pi4J version 0.0.5-SNAPSHOT and later) this makes it a breeze to program and work with in your own Java program.   

Shipping List

Documentation

Board Layout/Features

  • 2 mechanical relays (connected to outputs 1 and 2; can be disabled via jumpers)
  • 4 momentary pushbutton PCB switches (connected to inputs 1-4)
  • 8 digital inputs (sink to GND to activate each input pin; pulled-up via software)
  • 8 open-collector outputs
  • 8 LED indicators (for the 8 digital outputs)

Photos

(Click any photo to enlarge.)

 

 

 




 

 

   

 

 

  

Hardware Installation

Installing the Pi-Face board is a snap.  It literally takes just a few seconds.  First, remove the power supply from your Raspberry Pi so that it is powered down while installing (or uninstalling) the Pi-Face board.  With the Pi powered down, simply place the Pi-Face board directly on top of the Pi such that the header connector on the Pi-Face is aligned with and mates with the P1 header pins on the Raspberry Pi as shown in the photo below.  Press the Pi-Face board down until the P1 header connector is fully seated.  

Note that on the opposite side there should be a rubber bumper attached to the Pi-Face that rests on top of the HDMI connector on the Raspberry Pi.  This bumper prevents any electronics from shorting out between the Pi-Face and Raspberry Pi boards.  

Driver Installation

The Pi-Face expansion board uses a MCP23S17 16-Bit I/O Expander chip to perform all of its onboard functionality.  The MCP23S17 chip uses SPI for communication between the Raspberry Pi and the Pi-Face board.  The Raspberry Pi supports a SPI driver but it must be configured to enable it.       

You can enable it for one time use by issuing the following two commands from the terminal (Note that if you reboot the system you will need to re-issue these command to enable the SPI driver again.):

   sudo modprobe spi_bcm2708
   sudo chown `id -u`.`id -g` /dev/spidev0.*

If you prefer to permanently load the SPI driver, then you will need to perform the following steps:

  • Edit the /etc/modprobe.d/raspi-blacklist.conf using this command:
     sudo nano /etc/modprobe.d/raspi-blacklist.conf
  • Comment out the line "blacklist spi-bcm2708" by placing a "#" character at the beginning of the line.  This will prevent the SPI driver from being blacklisted on reboot.
     #blacklist spi-bcm2708

Save the file when your changes are complete (CTRL-O to save; CTRL-X to exit)
Here is what my blacklist file looks like:

  • Reboot the Raspberry Pi for the settings to take effect.
     sudo reboot

Programming

Now we are to the fun part .. programming in Java to interact with the Pi-Face board.  The good news is that if you use the Pi4J libraries all the nitty-gritty hard work (SPI communication protocol for the chipset and state change monitoring threads) is already done for you.  Pi4J has implemented the following new device interface and implementation classes to support the Pi-Face board: 

(Browse the com.pi4j.device.piface namespace here.)

These interfaces and classes expose much of the Pi-Face's capabilities using some of the newer Pi4J components interfaces such as Relay, Switch, and LED.  In addition to the component interfaces, you can also access the raw GPIO pins if needed.

NOTE:  You will need to include the following pi4j dependency JARs in your program and included on the classpath:

  • pi4j-core.jar 
  • pi4j-device.jar
  • pi4j-gpio-extension.jar

Example Java Program

The following is the Pi-Face example Java code that is now provided with the Pi4J installation and available as open-source in the Pi4J Github repository.  

This sample implements the following logic:

  • When switch 'S1' is pressed, relay 'K0' will turn ON
  • When switch 'S1' is released, relay 'K0' will turn OFF
  • When switch 'S2' is pressed, relay 'K1' will toggle states
  • When switch 'S3' is pressed, 'LED02' will start blinking
  • When switch 'S3' is released, 'LED02' will stop blinking and turn OFF
  • When switch 'S4' is pressed, the cylon effect on 'LED03' to 'LED07' will speed up
  • When switch 'S4' is pressed, the cylon effect on 'LED03' to 'LED07' will slow down

Installing, Compiling and Running The Sample

Follow the instructions on http://pi4j.com/install.html to install Pi4J and compile the included sample programs.  

If you want to compile just this single example use the following commands:

cd /opt/pi4j/examples
javac -classpath .:classes:/opt/pi4j/lib/'*' -d . PiFaceExample.java

To run the sample, use the following command:

cd /opt/pi4j/examples
sudo java -classpath .:classes:/opt/pi4j/lib/'*' PiFaceExample

Pi-Face In Action

The following is a video demonstrating this sample Pi-Face Java program running on my Raspberry Pi.

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments (25)

until guys will fix pi4j, heres workaround i use

python program:

import piface.pfio as pfio
import sys
import time

pfio.init()

for i in range(0,8):
pfio.digital_write_pullup(i,1)

while (1):
s = ''
for i in range(0,8):
s += str(pfio.digital_read(i))
f = open('/mnt/tmp/piFaceInputData','wb')
f.write(s)
f.close()
time.sleep(0.005)

java program to start python (code needs to be after piface java initialization, otherwise it wont work):
//initialize piface if declared
if (pifaceUsed.trim().equals("1")) {
System.out.println("Opening Piface support...");
piFace = new PiFaceGpioProvider(PiFace.DEFAULT_ADDRESS, Spi.CHANNEL_0);

//TODO dirty piface input fix until Robert from savagehomeautomation.com will fix error in pi4j for piface input with pull ups
try {
Process cat = Runtime.getRuntime().exec("sudo python ./piFaceInputRead.py");
// catOut = IOUtils.toString(cat.getInputStream());
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println("Piface support done.");
}

java program to read:
private boolean isCorrectReadPiFace(String str) {
if (str.length()<8) return false;
for (int i=0;i<str.length();i++)
if (!Character.isDigit(str.charAt(i))) return false;
return true;
}

public int getState() {
String catOut = "";
//TODO workaround just until Robert from savagehomeautomation.com will fix error in pi4j and pullup inputs on piface
while (!isCorrectReadPiFace(catOut))
try {
Process cat = Runtime.getRuntime().exec("sudo cat /mnt/tmp/piFaceInputData");
catOut = IOUtils.toString(cat.getInputStream());

} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return Integer.parseInt( ""+catOut.charAt(pinNo) );
//return pin.getState().getValue();
}

October 21, 2013 | Unregistered CommenterMathew

Hi,

@Robert: First of all: Thank you for all your effort on pi4j! I really enjoy it and I use it a lot!

Did you implement support for stacked PiFaces on the same bus with different SPI-adresses?

I tried stacking with PiRack and can only access the PiFace with address 0, regardless of which spiAddress I use on "new PiFaceDevice(...)" calls. As far as I see, in PiFaceGpioProvider.java the variable address is not overridden by the constructors parameter "spiAddress". I think, there is just a single line missing in PiFaceGpioProvider.java or are there other issues with multiple boards?


Thanks!

Regards,
Oliver

November 20, 2013 | Unregistered CommenterOliver

Hi all,
i had the same problems with the piface and pi4j as described in the comments.

I followed the instruction from Michael with the python init file/process and now the example programm works well! :-)

Are there any other known problems with PiFace and Pi4J which I can workaround?

Greetings
Alex

April 19, 2014 | Unregistered CommenterAlex

Thank you Robert c.s. for creating Java libraries for the Piface.

In your source you have "gpio.shutdown()" commented out.

I did something like:


PiFaceBase device = (PiFaceBase) piface;
PiFaceGpioProvider provider = device.getGpioProvider();
provider.shutdown();

and expected all blinks to die. But they don't.

The reason/purpose of my asking is because I want to start/stop my program in a running OSGi container. It shows unexpected results when I try to restart my bundle.

Is it a wrong assumption that the blinking should stop? But most of all, how do I stop the Piface in a clean way?

January 30, 2015 | Unregistered Commenterotembajelle

@otembajelle (selfie :))

Add ...


((PiFaceBase) piface).getGpio().shutdown();

Ah! That solved the issue. Thanks!

January 31, 2015 | Unregistered Commenterotembajelle

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« Raspberry Pi - Pi4J Version 0.0.5 Released! | Main | Raspberry Pi - Java GPIO Frequency Benchmarks »