By Michael Kölling

This post is part of a two part series – click here for Part One.

Access Raspberry Pi hardware interactively with BlueJ.

javamag-logo

Originally published in the January/February 2015 issue of Java Magazine. Subscribe today

In Part 1 of this series, we discussed how to run BlueJ on the Raspberry Pi to do some Java programming directly on the pocket-size computer, without the need for a second machine. We no longer need to develop our Java programs on a desktop machine and then transfer the JAR file to the Raspberry Pi; the promise of using the Raspberry Pi as a desktop replacement for tinkering and learning with Java is here.

However, in Part 1, we talked only about doing on the Raspberry Pi what you can also do on your desktop: run BlueJ and some standard Java examples, and use the same functionality that has been available on desktops and laptops for some time.

Now, don’t get me wrong: There is nothing wrong with using BlueJ on the Raspberry Pi just to learn how to write standard Java programs. This combination is a great educational tool, and the fact that the Raspberry Pi is available so cheaply is a game changer. However, we do not need to stop there.

The next exciting step is to do some things that you could not do before: access some of the physical components of the Raspberry Pi directly from Java, and play not only with code but also with hardware. The combination of easily accessible hardware on the Raspberry Pi and the interaction and experimentation functionality of BlueJ allows us to do some cool things.

In this article, we will explore how to create Java objects that correspond directly to hardware parts and are easy to use.

What You Need

Java on Raspberry Pi Fig.1I am assuming that you have set up your Raspberry Pi, you can log in and start the X Windows server, and you have installed and started BlueJ. (If not, read Part 1 of this series first).

In addition, to follow along with the examples in this article, you will need a few additional items: one LED, one button, one resistor, and four wires (see Figure 1).

A breadboard also helps – it is not strictly essential, but if you don’t use a breadboard, it can be difficult to attach the components to each other without soldering. If you try to just twist the ends of the wires and the components together, they tend to come apart very easily.

Getting the BlueJ Project

Let’s start by opening a BlueJ project. Download the RasPi-IO project here, unzip it, and open it in BlueJ on your Raspberry Pi (see Figure 2).

Java on Raspberry Pi Fig.2

This project has two classes that provide abstractions over I/O components that can be connected to the Raspberry Pi: a GPOutput class for anything that can be connected to a general-purpose input/ output (GPIO) pin (such as an LED), and a Button class for a push button connected to a GPIO pin.

Preparing an LED

The first, very simple example we’ll discuss is switching an LED on and off.

Start by connecting your LED to the Raspberry Pi in the following way:

     1. Connect the ground terminal of the LED (the shorter leg) to a wire.

  1. Connect the end of the wire to pin 6 (Ground) of the Raspberry Pi’s expansion header. Refer to the pin configuration diagram for the Raspberry Pi.
  2. Connect the longer leg of the LED to the resistor.
  3. Connect the other end of the resistor to a second wire.
  4. Connect the other end of the second wire to GPIO 1 (pin 12) of the Raspberry Pi’s expansion header.

The whole setup is shown in Figure 3.

Java on Raspberry Pi Fig.3

Be careful that you are using the correct pin numbering scheme. Unfortunately, different numbering schemes for pins are in use. BlueJ uses the Pi4J library, so we’ll use the numbering scheme used by that library. Make sure you are looking at the right one (see the diagram mentioned earlier). GPIO 1 should be pin 12.

Getting to Work in BlueJ

Java on Raspberry Pi Fig.4Now that we have connected our LED to one of the GPIO pins, in BlueJ, create an object of class
GPOutput. (Remember, you can create an object in BlueJ by right-clicking the class and selecting a constructor from the menu.)

You will see two constructors: One lets you select the GPIO number you want to use, and the other uses GPIO 1 by default. Because we have connected our LED to GPIO 1, we can just use the default constructor. We now have an object on the object bench that represents our LED. (In the general case, the object represents whatever is connected to GPIO 1; for us, that is the LED.)

You can now control the LED by interacting with the object. It’s that easy! Right-click the gPOutput
object and invoke the on() method (see Figure 4). The LED should come on. Switch it off again. There is also a blink() method that you can play with. Try it with some different parameter values.

Using a Button

Next, we will connect a button to our Raspberry Pi and read its state. Connect your button as follows (see Figure 5):

 

1. Using the third wire, connect one connector of the button to 3.3V power (pin 1) on the Raspberry Pi’s expansion header.

2. Using the fourth wire, connect the other connector of the button to GPIO 4 (pin 16) on the Raspberry Pi’s expansion header.

Java on Raspberry Pi Fig.5In BlueJ, we can represent the button by creating an object of type Button. Try it out. Again, there is a default constructor and a second constructor with a parameter that lets us specify which GPIO number we want to use. And again, we have connected our button to the GPIO that is used by default— GPIO 4, in this case—so we can make our life easy and use the default constructor.

The button object gives you two methods to check the button’s state: isUp() and isDown(). If you call them without touching the button (that is, while the button is not pressed), isUp() should return true and isDown() should return false.

Try pressing and holding the button down while you call these methods. You should be able to see that the button’s state gets correctly reported by your button object.

Writing a Program

We have seen how we can use BlueJ’s interaction features to test our inputs and outputs very easily – without writing a single line of code. Next, we shall look at how to use objects of the GPOutput and Button classes in a simple program. To do this, we will write code that turns our Raspberry Pi into a light switch: The LED should come on while we press the button.

In your BlueJ project, create a new class called LightSwitch. We start by declaring two fields— one for the LED and one for the button:

private GPOutput led;
private Button button;

Then, in the constructor of your new class, create objects for each of these types, and register your own LightSwitch object as a listener for the button:

public LightSwitch() {
led = new GPOutput(); button = new Button(); button.addListener(this);
}

To make this work, you must ensure that your LightSwitch
class correctly implements the ButtonListener interface by declaring this in the class header:

public class LightSwitch
  implements ButtonListener

You must also implement the buttonEvent method:

@Override
public void buttonEvent( Button button)
{
  // code to come here
}

This listener method will be called whenever the button’s state changes—both when the button is pressed and when it is released. We can then use the button parameter to check the button’s state.

Now, all that remains to be done is to react correctly when the button is pressed by switching our light on and off. We do that by entering the following code in the body of our buttonEvent method:

if (button.isDown()) { led.on();
} else {
led.off(); }

Try it out: Complete your class, compile, and create an object of type LightSwitch. (If you have trouble, compare your code to Listing 1, which shows the complete class discussed here.) Because the object has registered itself as a listener, you do not need to invoke any methods. Just press the button, and you should see the LED light up.

public class LightSwitch implements ButtonListener
{
  private GPOutput led;
  private Button button;

  /**
  * Create a Raspberry Pi light switch. */
  public LightSwitch()
  {
   led = new GPOutput();
   button = new Button();
   button.addListener(this);
  }

  /**
  * Listener method: called when button state changes. */
  public void buttonEvent(Button button)
  {
   if (button.isDown()) {
      led.on();
   }
   else{
     led();
    }
   }
 }

It really is that easy.

Conclusion

You can use BlueJ on the Raspberry Pi not only to write standard Java programs just as you can on your desktop, but also to access the Raspberry Pi’s I/O ports. In the example we explored in this article, two wrapper classes were provided for BlueJ to represent an LED connected to an output pin and a button connected to an input pin. These wrapper classes made it very easy to interact with and write code for these components. BlueJ internally uses the Pi4J library to communicate with the Raspberry Pi. You can either use BlueJ’s wrapper classes to communicate with your hardware, or you can program with the Pi4J interface directly. (Look inside the GPOutput class to see an example of access- ing Pi4J.)

Using BlueJ’s wrapper classes is generally simpler – they provide a simplified interface to your hardware. More wrapper classes are available on the BlueJ website. However, the simplicity is achieved at the price of flexibility. If you need more control over the hardware than the BlueJ-provided wrapper classes give you, you can access the Pi4J library directly. This way, BlueJ manages to serve two audiences: It makes getting your feet wet very easy for people just starting out, and it gives you full flexibility after you have become more comfortable with programming slightly more-complex examples.

So, whatever your level, dive in and start writing Java on the Raspberry Pi!

 

Code Java On the Raspberry Pi (Part Two)

Profile photo of voxxed
About The Author
-

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>