Accessing 1-wire Protocol Devices from Java

More Raspberry Pi fun with Java! For an Adafruit LCD Shield library, check out my previous blog.

So, instead of just playing around for fun, I decided to actually do something useful. In this case I wanted a little remote sensor station, which I can plug-in wherever I want to, and communicate with over http over GSM.

Building It

First of all you need to bunker up on as many DS18B20s and as many AM2302/DHT11/DHT22’s you think you’ll need. There are plenty of articles out there on how to configure them. I decided to do it a tiny bit differently to most examples by hooking up the power pin to the 5V rail (both since the specs indicate that you can run longer cable lengths if you do so and since more current can be sourced from the 5V rail). The data is pulled up to the 3.3V rail, just like in all the examples. Note that a bunch of DS18B20s can be hooked up in parallel and communicated with over a single GPIO port. Also note that this is NOT possible with the DHT sensors, which will need one GPIO port per sensor.

Ultimately I decided to have two (optional) DS18B20s and one AM2302 on my board, and I used an Adafruit Perma Proto to hook it all up. Mostly because they are pretty. 😉 To connect the AM2302, I used a Molex jumper assembly, and for the DS18B20s I decided to use RJ-11s. I can highly recommend the RJ-11s! The connectors take a bit of space on the card, and they do require you to mutilate the poor Perma Proto a bit (drill larger holes), but attaching/removing sensors is a joy. Here is a picture of the thingy with all the sensors connected:

sensor_board

In my build I will also use an LCD shield for local control and readouts without necessarily having access to a monitor. I also added a few buttons and LEDs, mostly to satisfy my youngest son.

I guess those could come in handy for diagnostics later. 🙂

Now, the 1-wire protocol used by the DS18B20 (Dallas 1-wire) and the 1-wire protocol used by the DHT sensors (AM2302, DHT11, DHT22) are quite different. Both of these require a bit of time sensitive bit-banging. Fortunately, that work has already been done for us.

For the DS18B20 there are two modules available which will expose all the DS18B20s as files under /sys/bus/w1/devices. Simply add w1-gpio and w1-therm to /etc/modules. Note that you must have the DS18B20s on GPIO port 4 for the module to work.

For the DHT sensors there is no module, but I’ve adapted the Adafruit native library described here, to create a native library for Java. Read the README.txt provided in the zip for more information.

Java Access

Once you have added the modules and put native libraries on the library path, there is only a tiny bit of configuration left to do. The library should automatically discover all DS18B20s you have. If you only happen to have one AM2302 on GPIO-pin 22, you are good to go. If not, you need to edit the property file dhtsensors.properties in the w1.jar to correspond to your setup:

# Specify devices to use with the dht library in this file.
# If you have no such devices, just comment everything out.
#
# Type can be one of the following:
# 2302 (for AM2302)
# 11 (for DHT-11)
# 22 (for DHT-22)
sensor0.pin=22
sensor0.type=2302

If you have no DHT sensors, simply comment out the lines. If you have more than one, simply add two more lines for every sensor, indicating which type and what pin they are on. For example:

sensor0.pin=22
sensor0.type=2302
sensor1.pin=23
sensor1.type=2302
sensor2.pin=24
sensor2.type=22

To test that everything is set up properly, simply run:

sudo java -Djava.library.path=<library path> –jar w1.jar

Note that Pi4J isn’t needed on the classpath. We’re relying on the native library and the w1-gpio mod to provide the necessary interfaces.

The output should look something along the lines of this:

Found 4 sensors!

Temperature(28-000004f7960a):23,38°C
Temperature(28-000004f78caf):23,56°C
Temperature(2302@22-temperature):23,00°C
Humidity(2302@22-hygrometer):36,50%

Temperature(28-000004f7960a):23,38°C
Temperature(28-000004f78caf):23,56°C
Temperature(2302@22-temperature):23,00°C
Humidity(2302@22-hygrometer):36,50%

Temperature(28-000004f7960a):23,44°C
Temperature(28-000004f78caf):23,56°C
Temperature(2302@22-temperature):23,10°C
Humidity(2302@22-hygrometer):36,50%

Library Usage

The code is very simple. To get all the sensors, do:

Set<Sensor> sensors = Sensors.getSensors();

To print the sensors like in the example, do:

System.out.println(String.format(“Found %d sensors!”, sensors.size()));
while (true) {
    for (Sensor sensor : sensors) {
        System.out.println(String.format(“%s(%s):%3.2f%s”, sensor.getPhysicalQuantity(),
                                     sensor.getID(), sensor.getValue(), sensor.getUnitString()));
        Thread.sleep(1000);
    }
    System.out.println(“”);
    System.out.flush();
}       

That’s really all there is to it.

Conclusion

A simple Java library to read a few different kinds of temperature and hygrometer sensors was introduced.

Downloads:

Monitoring LEGO Mindstorms with Java Mission Control

Since release 7u40, Java can run on LEGO Mindstorms EV3. In this post the JMC Team will explore how to use Java Mission Control to monitor Java applications running on Mindstorms. This post is a guest post by the JMC Team.

What We Have Done

Our primary goal was to show that we can monitor a Java application running on a Java SE embedded platform over JMX.
We started off by unpacking our LEGO Mindstorms kit and built the demo robot which was a good way to get to know the components. A simple demo program was present in the default firmware so it was quite easy to get it to run.

EV3-robot

When we had familiarized ourselves with the different sensors and motors we moved on to actually running Java on the system. The leJOS project provides a Linux distribution that can run on Mindstorms and a set of libraries to control just about anything you can connect to the system.

After installing leJOS we verified that we could run Java programs and monitor them using Java Mission Control. Finally we wrote a program that allowed us to control the robot using the MBean management functionality in Java Mission Control.

Running Java programs on Mindstorms

What you need:

  • LEGO Mindstorms EV3
  • A MicroSD card
  • An SD card reader
  • A USB WiFi adapter that is supported by leJOS
    We used a Netgear WNA1100 adapter which is identical to the official LEGO WiFi adapter. A list of alterative adapters can be found at http://www.rjmcnamara.com/lego-mindstorms-ev3/mindstorms-ev3-compatible-wi-fi-dongles/ but we have not tested any of them. It is worth pointing out that the adapter we used sticks out quite a bit so it has to be considered when choosing what to build.
  • A WiFi network with a DHCP server
    Just about any WiFi router should work.
  • A Linux computer to use for writing the leJOS system to the SD card
    If you don’t have a Linux computer you can follow the guide at http://sourceforge.net/p/lejos/wiki/Running%20Ubuntu%20with%20VirtualBox/ to get a virtual Linux system.
  • A computer for developing and compiling Java programs.

EV3-wifi-sd

 

Installing leJOS

To run leJOS you need a bootable SD card with leJOS on it. When you turn on the Mindstorms system with this card inserted it will boot the leJOS distribution. If the SD card slot is empty it will boot the default LEGO system. This is very nice since you don’t have to make any permanent changes to the firmware. You only have to remove the card in order to make it behave as a normal Mindstorms system again.

A handy tip is to attach a small piece of tape to the SD card. This makes it much easier to remove the card from the Mindstorms system if you need to update it later or if you want to keep several cards with different contents.

To install leJOS on an SD card, follow the guide at http://sourceforge.net/p/lejos/wiki/Creating%20a%20bootable%20SD%20card/.
Note that when you insert the SD card into the Linux system for formatting and writing, it is not always clear which device the SD card is using. If the card was mounted automatically you can use the command mount to see which devices are mounted. You can also use the command dmesg to see messages that come when hardware changes are detected. In any event, take care not to select the device for your hard disk.

When the SD card is complete you can start using it:

  • Insert the WiFi USB stick into the USB port on the Mindstorms system
  • Insert the SD card into the SD card slot on the Mindstorms brick and turn it on

If everything worked correctly you will after a while see the leJOS logo and one or two IP addresses on the screen. One is for USB and Bluetooth networking and the other is for WiFi.

 EV3-lejos

Connect to the WiFi IP address using ssh and login as root with no password. This will give you a pretty normal Linux prompt from where you can run your programs.

You can try running a demo program:

cd /home/root/lejos/samples
jrun EV3HelloWorld

This should result in some beeping and blinking.

Development environment

If you follow the instructions at http://sourceforge.net/p/lejos/wiki/Developing%20with%20leJOS/ then you will get an Eclipse development environment where you can do everything from within Eclipse.

 

Minimum requirements

If you can’t or don’t want to do everything from within Eclipse then you can set up your own environment. For a minimal setup all you need to do is to get hold of the ev3 library.

The first option is to get the latest source files from git. You can do this either by running git clone git://git.code.sf.net/p/lejos/ev3 lejos-ev3 or, if you don’t have git installed, downloading a snapshot of the code from http://sourceforge.net/p/lejos/ev3/ci/master/tree/. The subdirectories contains various libraries and demo projects complete with Eclipse project files. The ev3classes subdirectory contains the source code for the leJOS API so import at least that into your favorite development environment.

You should preferably build the DbusJava and ev3classes projects with ant. This will give you an ev3classes.jar file which should be placed in /home/root/lejos/lib on your Mindstorms system so that you have the same version of the library when you run your programs.

The second option is to take the ev3classes.jar file from the leJOS installation and add it to your classpath. You can find this jar file on your Mindstorms system in /home/root/lejos/lib. Note however that the ev3classes.jar file that is distributed with the leJOS installer is not necessarily the latest so we recommend getting the source code from git and building it yourself if you can.

 

Development process

In short, the development process consists of these stages:

  • Write a program and compile it on your development system
  • Upload the class or jar files to the Mindstorms system
  • Run the program on the Mindstorms system

If you followed the guide on the lejos wiki then you can follow their instructions. Otherwise, you can use your favorite scp application to transfer files and your favorite ssh terminal to run your programs.
Whichever way you choose, start off with a simple program like this one:

import lejos.hardware.Button;
import lejos.hardware.LCD;

public class HelloWorld {
    public static void main(String[] args) throws Exception {
        LCD.clear();
        LCD.drawString(“Hello World”, 0, 5);
        Button.waitForAnyPress();
        LCD.clear();
        LCD.refresh();
    }
}

Compile the program and create a jar file with the class:

javac -cp ev3classes.jar HelloWorld.java
jar cvf HelloWorld.jar HelloWorld.class

Copy the jar file to the Mindstorms system using scp and start it from an ssh terminal:

jrun -cp HelloWorld.jar HelloWorld

 

Connecting Java Mission Control to a remote Java process

Java Mission Control is a tool for monitoring and analyzing Java processes. It has been bundled together with JDK since version 7u40. Java Mission Control uses JMX to communicate with remote Java processes. To enable the management agent on a Java process you can add the following parameters when starting it:

-Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.port=7091 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false

You can select just about any free port number instead of 7091. If you are running multiple Java processes on the same system then you need to use different ports for each process. Depending on how the leJOS system detects which IP address is the primary one, you may also have to add the following parameter:

-Djava.rmi.server.hostname=The IP address of the Mindstorms WiFi adapter

Once the Java process is up and running you can connect to it using Java Mission Control. Add a connection to the Mindstorms IP address and the port number that you chose. Expand your new connection in the JVM browser view and open a JMX Console on the MBean Server.

JMC browser New connection  New connection wizardJMC browser Start JMX Console

 
If everything worked as it should you will see a console window displaying the status of the Java process.

JMX Console 

This procedure is the same for any remote Java process that you want to monitor. Java Mission Control can auto-detect Java processes that can be monitored through a protocol called JDP. You can read more about JDP at https://hirt.se/blog/?p=388.

 

Monitoring and controlling Mindstorms using MBeans

Now you have a Java process running on the Mindstorms system and you can communicate with it using JMX. This allows you to see a lot of information about what the Java process is doing. The next step is to monitor and control the sensors and motors connected to the Mindstorms system. To do this we implement a custom MBean that expose the leJOS libraries.

You can read more about MBeans and MXBeans at http://docs.oracle.com/javase/tutorial/jmx/mbeans/index.html.

 

Creating an MBean

An MBean is basically a Java class that implements an interface. Start off by creating the interface:

public interface MotorMXBean {

    public void moveForward();

    public void stopMotor();

    public int getSpeed();

    public void setSpeed(int speed);
}

Then create a class implementing the interface:

import lejos.hardware.motor.NXTRegulatedMotor;

public class Motor implements MotorMXBean {
    final NXTRegulatedMotor m_motor;

    public Motor(NXTRegulatedMotor motor) {
        m_motor = motor;
    }

    @Override
    public void moveForward() {
        m_motor.forward();
    }

    @Override
    public void stopMotor() {
        m_motor.stop();
    }

    @Override
    public int getSpeed() {
        return m_motor.getSpeed();
    }

    @Override
    public void setSpeed(int speed) {
        m_motor.setSpeed(speed);
    }
}

This exposes a small subset of everything that can be done but it will give you an idea of how things work. You don’t have to expose the leJOS library methods directly, often it can be more useful to have more complex operations like ”find a ball” or monitor values like ”number of balls found”.

With the MBeans implemented, it is time to create an instance and register it with the platform MBean server.

import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;

public class MBeanRunner {
    public static void main(String[] args) throws Exception {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        Motor m = new Motor(lejos.hardware.motor.Motor.B);
        ObjectName name = new ObjectName(“lejostest:name=MotorB”);
        mbs.registerMBean(m, name);
        System.out.println(“Server is running. Press enter to exit”);
        System.in.read();
    }
}

This is a very simple program that doesn’t do anything on its own. It registers a motor controller with the MBean server and waits for commands. Compile the classes and place them on the Mindstorms system. Connect a motor to port B on the Mindstorms system and start the program:

jrun -cp Test.jar -Dcom.sun.management.jmxremote=true -Djava.rmi.server.hostname=192.168.2.3 -Dcom.sun.management.jmxremote.port=7091 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false MBeanRunner

Start Java Mission Control and connect to the Mindstorms system. Go to the MBean Browser and locate the lejostest/MotorB MBean. Go to the Operations tab, select moveForward and click on Execute:

JMC MBean Browser operations

The motor should start running. Go to the Attributes tab and you will see a list of values for all attributes that are exposed with getter methods. Attributes that have setter methods can be set so try clicking on the value for the speed attribute, enter a new value and finish with enter:

JMC MBean Browser attributes

The motor should now change speed. To stop the motor, go back to the operations tab and execute the stopMotor operation.

 

Conclusion

If you have followed this guide you will have accomplished three things:

  1. Running Java programs on a Mindstorms system
  2. Monitoring a remote Java process with Java Mission Control
  3. Exposing application specific data and operations in an MBean

All of these things can be done independently. You can run Java programs on Mindstorms without monitoring them, any program running on a supported JVM can be monitored with Java Mission Control, and there are other methods of monitoring MBeans.
Enjoy.

More information about Java Mission Control can be found at http://www.oracle.com/missioncontrol.
More information about leJOS can be found at http://www.lejos.org/ and at http://sourceforge.net/projects/lejos/.

Using the Adafruit LCD Shield from Java

We’re interrupting the ordinary programming for a series of Raspberry PI related articles. Yep, I finally bought one and started having some fun.

I know I am sooo late to the party. My excuse is that having really young kids translates into a constant time shortage. That said, I bought myself a Raspberry Pi just in time for some vacation. One of the first things I did was to get an LCD shield for the Raspberry PI. I settled on this particular kit:
http://www.adafruit.com/products/1115

It’s a really nice little LCD kit which also features a few buttons. The shield uses a port extender (MCP23017) to get another 16 GPIO ports over I²C. This is quite nice, since you probably want to use your GPIO ports for other things. Also, you can hook up several I²C devices on the same bus, so using the I²C pins for the LCD shield doesn’t mean that you’ve used them up.

The LCD shield can be run in various different modes. My little example library uses 16×2 characters by default.

Building the Kit

The instructions for building the kit are excellent, and there are just a few things I’d like to note:

  1. Get a stacking header
    I fortunately came to the conclusion I would need a stacking header before soldering everything together, but unfortunately after I had ordered the LCD shield. I am oh so happy I decided to wait for the header to arrive before finally putting the kit together.
  2. If you want to attach a standard flat 26 pin cable, trim out some space in the LCD PCB for the little orientation peg on the cable header 
    This I did not do – I ended up trimming down the cable header with my Dremel instead, since it’s too hard to access that area after soldering on the LCD.
  3. (Optional) Unused GPIO pins for free!
    E.g. GPA5 appears to not be in use. Feel free to use it for your own purposes. The library initializes it as yet another input pin by default, but that is easily changed.
  4. (Optional) Use interrupts for the buttons
    This will cost you a GPIO pin (and you cannot use one of the unused ones on the LCD shield’s MCP23017), but will allow you to poll the button pins a lot less often without risking missing a button press. You may want to do some additional soldering on pin 20 of the MCP23017 – INTA is not hooked up by default. This also requires you to hack my Java code a little bit to initialize GPINTEN, and to read from INTF and INTCAP,

Testing the Kit

Once you’ve built the kit, follow the instructions here to try out the LCD kit using the demo python code. Once you have your LCD shield up and running you can move on to getting everything to run from Java.

Using the LCD Shield from Java

Once everything is working from python, you are ready to run things from Java. I mostly did a straight port of the Python library.

  1. First download and install Pi4J
    This will be required for most future posts I might put on the blog.
  2. Next download lcd.jar
    The source is available with lcd_src.zip.

Now you can run the included demos by just invoking the jar like this:
sudo java –Xbootclasspath/a:/opt/pi4j/lib/pi4j-core.jar –jar lcd.jar

lcd2

When running the demos, use the up/down buttons to select a demo, then press select to run a demo. When the demo is done, use up/down to select a new demo.

API Examples

Here is how the API can be used to show some text:

LCD lcd = new LCD();
lcd.setText("Hello World!\n2nd Hello World!");

Here is an example with some buttons:

final LCD lcd = new LCD();
lcd.setText("LCD Test!\nPress a button...");
ButtonPressedObserver observer = new ButtonPressedObserver(lcd);
observer.addButtonListener(new ButtonListener() {
    @Override public void onButtonPressed(Button button) {
        lcd.clear();
       
lcd.setText(button.toString());
    }
});

For more examples, check out the demos in the se.hirt.pi.adafruitlcd.demo package. I currently have most of the implementation in my python port LCD class. Anything that isn’t purely reading/setting registers, I’ve handled outside of that class (such as the polling of buttons). If I ever find some time I might clean up the API and move away from the current python port.

Tips and Tricks

  • If you want to teach the LCD to do additional tricks, the LCD controller used is the HD44780
    Note that it might be valuable to read the spec if for no other reason than to understand the limits (e.g. quite small DDRAM buffer).
  • MCP23017 is an awesome little thing
    Ever wanted more GPIO ports? Using the MCP23017 is one way to get plenty more. Just remember to provide a unique address by configuring A0-A2 (see page 8 of the spec). Connecting them all to ground will yield 0x20 (which is what the LCD shield uses). Hooking them all up to 5v will yield 0x27.
  • Be careful with how much current you source/sink, both using the MCP23017 (25mA) and the RPi (16mA GPIO, 50mA 3.3v rail, 5V rail pretty much depends on your power supply). If you need to source/sink more than the IO pins can handle, you can use a Darlington Array, for example ULN2803.