Working with UART by Using Java ME Embedded and a Raspberry Pi

Overview

Purpose

This tutorial covers how to create an Oracle Java Micro Edition Embedded 8 (Java ME Embedded 8) application that read and write to a universal asynchronous receiver/transmitter (UART) device. When connected to a Raspberry Pi, the UART device reads data from global position system (GPS) satellites to provide an accurate position.

Time to Complete

Approximately 1 hour

Introduction

Intelligent devices are becoming an ever more important and ubiquitous part of our everyday lives. Mobile phones represented the first wave of smaller personal computers. And now, as the price of electronics and processing power continues to fall, there is an intersection between sensors and other electromechanical devices and computers that live on the edge of the Internet: close to the source of the data, processing the data locally and sending just what is required to other computers to consume. This wave of machine-to-machine (M2M) technology, or more broadly, the Internet of Things (IoT), is rapidly shaping the future of computing. Oracle Java Platform, Micro Edition (Java ME) provides Java developers with a direct path to this new market space by using their existing knowledge and skills.

The serial connection is the mainstay of communications between computer equipment and terminals and keyboards. The advantage of serial communications is the simplicity of the wiring and the ability to communicate in both synchronous and asynchronous modes. Serial devices typically have an integrated circuit (stand-alone or part of another hardware) called a UART, which handles the specific signaling required to establish communications and convert digital signals to individual characters. The Raspberry Pi has a built-in UART that can be used to communicate with serial devices, including the Adafruit GPS device, which uses serial communication to send GPS telemetry data to the Raspberry Pi.

Scenario

In this tutorial, you create a Java ME Embedded 8 application that communicates with a GPS device. The device provides accurate positioning by using global positioning satellites. You use a MediaTek MT3339 chipset, which was designed for small, hand-held and mobile GPS applications. The chip is soldered on a breakout board that includes supporting components to make it compatible with the Raspberry Pi.

Hardware and Software Requirements

The following is a list of hardware and software requirements:

Prerequisites

Before starting this tutorial, you should:

Installing the GPS Daemon Software (gpsd)

In this section, you install gpsd, a tool that allows you to quickly test the functionality of your GPS device.

  1. Connect to the Raspberry Pi by using PuTTY.

    PuTTY Connection
  2. Enter sudo apt-get install gpsd gpsd-clients python-gps to install the gpsd daemon and clients.

    PuTTY Connection
  3. Enter Y at the prompt.

    PuTTY Connection

    The software takes a few minutes to install.

    PuTTY Connection

(Optional) Connecting the GPS Device by Using the USB to TTL Serial Cable

If you have a USB to TTL serial cable, you can test the GPS device without creating a circuit on the breadboard. Note: USB line voltages are 5V, which is too high for typical TTL devices. This custom cable converts the 5V levels to TTL levels that are compatible with serial devices.

  1. Attach the ends of the USB to TTL serial cable to the GPS breakout module in the following sequence:

    1. Connect the red lead to the VIN pin of the GPS device.
    2. Connect the black lead to the GND pin.
    3. Connect the green lead to the RX pin.
    4. Connect the white lead to the TX pin.
    USB Wiring
  2. Plug the USB end into the Raspberry Pi.

    Raspberry Pi

    For the first few minutes, the Fix LED on the GPS breakout board will flash about once every second while it is acquiring a signal. After it acquires a signal, the Fix LED will flash every 15 seconds.

  3. Enter ls /dev/ttyUSB* to determine the device's USB port connection.

    PuTTY Connection

    In this example, the GPS device is on the /dev/ttyUSB0 serial port.

  4. Enter sudo gpsd /dev/ttyUSB0 -F /var/run/gpsd.sock to start the gpsd daemon on the device address.

    PuTTY Connection

    Note: Use the USB serial port that you located in step 3.

  5. Enter cgps -s to start the GPS client and display the output.

    PuTTY Connection

    Formatted data from the GPS device is displayed in the console window.

    PuTTY Connection
  6. If there is no output and cgps quits after just a few seconds, perform the following steps:

    1. Place the GPS device close to a window. In general, GPS works better with a line of sight to the sky.
    2. Wait for the device to acquire a fix. This may take a few minutes, depending upon your location.
    3. Enter cat /dev/USB0 in the PuTTY window (use the USB port number you discovered in step 3). You should see strings of characters. If not, recheck your connections.
    4. Kill and restart the gpsd daemon.

Connecting the GPS Device by Using the UART on the Raspberry Pi

By default, the Raspberry Pi uses its built-in UART as the serial console. Therefore, you must configure the Raspberry Pi so that you can use the UART.

Creating the Application Circuit by Using the Breadboard

  1. Place the 26-pin header connector into the breadboard so that:

    • The connector straddles the center.
    • Pin 1 (marked 3V3) is in column 14 at the top.
    • The "key" (the square cutout in the center of the connector) is in the center at the top.
    Breadboard

    Note: Your breadboard may be different. Leave enough room to place the GPS device to the left of the connector.

  2. Insert the GPS breakout board into the breadboard so that the breakout board's left pin (PPS) is in row 1.

    Breadboard

    All of the breakout board's pins should be in column f.

  3. Check that you have version 2 of the Raspberry Pi. For more information, see "Checking the Hardware Version of Your Raspberry Pi" in the tutorial titled Working with GPIO by Using Java Embedded and a Raspberry Pi.

  4. Perform the following tasks, using the row numbers shown in the image as a reference:

    1. Insert a red wire between row 2, marked VIN on the GPS breakout board, and row 14 on the connector (marked 5v0).
      Note: Because the GPS device has an internal voltage regulator, you can wire it to the 5V output line.
    2. Insert a green wire between row 3, marked GND on the GPS breakout board, and row 16 on the connector (marked GND) .
    3. Insert a blue wire between row 4, marked RX on the GPS breakout board, and row 17 on the connector (marked TXD).
    4. Insert a white wire between row 5, marked TX on the GPS breakout board, and row 18 on the connector (marked RXD).
    Breadboard

    Note: You are cross-wiring the RX pin on the GPS device to the TXD pin on the connector, and the TX pin on the GPS device to the RXD pin on the connector.

    Your wiring should look similar to this picture:

    Breadboard
  5. Review the application circuit that you created.

  6. Circuit diagram

    Note: It is important that you cross-connect the RX pin on the GPS device to the TXD pin on the connector and the TX pin on the GPS device to the RXD pin on the connector.

  7. Unplug the Raspberry Pi power cable .

  8. Connect the ribbon cable between the breadboard and the Raspberry Pi.

    If you have not performed this step before, see "Connecting the Ribbon Cable Between the Raspberry Pi and the Header" in the tutorial titled Working with GPIO by Using Java Embedded and a Raspberry Pi.

  9. Plug the power cable back into your Raspberry Pi.

Configuring the UART on the Raspberry Pi

  1. Connect to the Raspberry Pi by using PuTTY.

    PuTTY Connection
  2. Enter sudo nano /boot/cmdline.txt.

    PuTTY Connection
  3. Remove console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 from the first line in the file.

    PuTTY Connection
  4. Press Ctrl + O and Enter, and then press Ctrl + X to write and close the file.

    PuTTY Connection
  5. Enter sudo nano /etc/inittab.

    PuTTY Connection
  6. Perform the following steps:

    1. Comment out the last line (enter a # at the beginning of the line).
    2. Press Ctrl + O and Enter to write the file.
    3. Press Ctrl + X to close the file.
    PuTTY Connection

    At this point, you have released the /dev/ttyAMA0 UART serial port.

  7. Enter sudo reboot to reboot the Raspberry Pi and make the changes.

    PuTTY Connection
  8. After a few minutes, right-click in the PuTTY window and select Restart Session to reconnect to the Raspberry Pi.

    PuTTY Connection
  9. Log in with the user id pi and the password raspberry.

    PuTTY Connection
  10. Enter sudo gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock to start the gpsd daemon on the UART serial port (/dev/ttyAMA0).

    PuTTY Connection
  11. Enter cgps -s to display the GPS data.

    PuTTY Connection

    Formatted data from the GPS device is displayed in the console window.

    PuTTY Connection

    The GPS device is writing correctly to the UART connection.

Creating a Java ME Project That Uses the GPS Device

In this section, you use NetBeans to develop a Java ME application that reads the GPS device output to the UART serial port. Note: The code in this tutorial is provided in the Resources section.

Creating a NetBeans Java ME Embedded Project

  1. Select File > New Project.

    NetBeans
  2. Select Java ME Embedded from Categories and Java ME Embedded Application from Projects and click Next.

    New Project
  3. In the New Java ME Embedded Application dialog, perform the following steps:

    1. Enter GPSExample as the Project name.
    2. Select EmbeddedExternalDevice1 as the Java ME Platform.
    3. Enter com.example.GPSIMlet in the Create Midlet field.
    4. Click Finish.
    New Embedded Application dialog

Setting Security API Permissions

Java ME Embedded projects that use UART and Comm devices must set special API permissions.

  1. Right click the Project and select Properties.

    NetBeans
  2. Click the Application Descriptor category and select to the API Permissions tab. Click Add.

    Properties
  3. In the Add Permission dialog:

    1. Select jdk.dio.DeviceMgmtPermission from the drop-down menu list.
    2. Enter *:* as the protected resource name.
    3. Enter open in the Actions Requested field.
    4. Click OK.
    Add Permission for API
  4. Click Add to add another permission for a UART connection.

    Properties
  5. In the Add Permission dialog:

    1. Select jdk.dio.uart.UARTPermission from the drop-down menu.
    2. Enter *:* as the protected resource name.
    3. Click OK.
    Add Permission for API
  6. Click Add to add another permission for a Comm Connection.

    Add Permission for API
  7. In the Add Permission dialog:

    1. Select javax.microedition.io.CommProtocolPermission from the drop-down menu.
    2. Enter comm:* as the protected resource name.
    3. Click OK.
    Add Permission for API
  8. Click Ok to close the properties dialog.

    Properties

Adding The Provided Classes to the GPSExample Project

  1. Expand the classes.zip file provided in the Resources section.

  2. Copy the files GPSCommSensor.java, GPSSensor.java, GPSUARTSensor.java, Position.java.
  3. In NetBeans, right-click on the com.example package and select Paste to paste the files into the project.

    Paste files

    There should be five files in the com.example package.

    Paste files
  4. Open the GPSSensor class and note that it is an abstract class. This class provides the base functionality for the GPS sensor, but must be implemented by another class to be instantiated.

  5. Open the GPSUARTSensor and GPSCommSensor classes. These classes provide the specific protocol support for the sensor, as a comm-port device or UART device respectively.

  6. Open the Position class. Note that this class is a POJO, but provides a valuable method for converting the NMEA strings to degree/minute/second position values.

Implementing the GPSIMlet class

  1. Add the following class field:

    
        private static final String SERIAL_PORT = "ttyAMA0";
    
    
  2. Implement the startApp method.

    
        @Override
        public void startApp() {
            try (GPSUARTSensor gps = new GPSUARTSensor())  {
            //try (GPSCommSensor gps = new GPSCommSensor(SERIAL_PORT)) {
    
                /* Take one reading every second for 10 readings */
                for (int i = 0; i < 10; i++) {
                    Position p = gps.getPosition();
                    // Use the toString method to print the result
                    System.out.println(p + "\n");
                    Thread.sleep(1000);
                }
            } catch (IOException ioe) {
                System.out.println("GPSTestMidlet: IOException " + ioe.getMessage());
            } catch (InterruptedException ex) {
                // Ignore
            }
    
            /* Terminate the Imlet correctly */
            System.out.println("GPSTestMidlet finished");
            notifyDestroyed();
        }
    

    This method creates an instance of GPSUARTSensor object in a try-with-resources block. When the try ends, the close method will automatically get called, obviating the need for the destroyApp method.

  3. Fix any missing import statements and save the file.

Running and Testing the GPSExample Project on the Raspberry Pi

In this section, you test the application by using NetBeans with the application circuit that you wired.

  1. Perform the following steps:

    1. Connect to your Raspberry Pi with PuTTY.
    2. Change directories with the cd javame8/bin command.
    3. Start the Application Management System with the sudo ./usertest.sh command.
    PuTTY Window
  2. In NetBeans, right-click the GPSExample project and select Run.

    NetBeans

    In the Output Console of the EmbeddedExternalDevice1 emulator, the data read from the GPS sensor is displayed..

    PuTTY window

    Note: If nothing is displayed and the application appears to hang, check and make sure you have the 8.1 EA version of the Java ME Embedded 8 binary for Raspberry Pi. The GA version of the binary will not work with this GPS device.

  3. Click Stop in the emulator to stop the application.

    EmbeddedExternalDevice 1 Emulator
  4. In the GPSIMlet, try commenting out the try-with-resources that opens the GPS as a UART and uncomment the line that opens the GPS as a comm port:
    
        public void startApp() {
            //try (GPSUARTSensor gps = new GPSUARTSensor())  {
            try (GPSCommSensor gps = new GPSCommSensor(SERIAL_PORT)) {
  5. Run the project again.

Summary

In this tutorial, you learned to:

  • Install the gpsd daemon and client software
  • Connect the GPS device by using a USB to TTL serial cable
  • Prepare the Raspberry Pi to use the UART
  • Connect the GPS device to the Raspberry Pi's UART
  • Write a Java ME Embedded 8 EA application by using the GCF to read the UART

Resources

Credits

  • Lead Curriculum Developer: Tom McGinn
  • Other Contributors: Edgar Alberto Martinez Cruz

To navigate this Oracle by Example tutorial, note the following:

Topic List:
Click a topic to navigate to that section.
Expand All Topics:
Click the button to show or hide the details for the sections. By default, all topics are collapsed.
Hide All Images:
Click the button to show or hide the screenshots. By default, all images are displayed.
Print:
Click the button to print the content. The content that is currently displayed or hidden is printed.

To navigate to a particular section in this tutorial, select the topic from the list.