Saturday, September 28, 2013

Sample Java Code to Read GPS Data from a Sparkfun Copernicus II DIP Module on a Raspberry Pi

The 09/25/2013 version of Raspbian Linux includes Java 7.  This example provides very basic Java code that reads GPS data via a serial port and prints the results to the console. My intention is not to provide an example of good object-oriented programming or thorough coverage of the RXTX library.  This post is about a minimum example of Java serial communication on the Raspberry Pi.

I found this post by Johannes Eickhold very helpful.

I used nano in a terminal window on the Raspberry Pi to edit the code.


  1. As noted above, this example assumes you have the 09/25/2013 (or later) version of Raspbian.  
  2. Make sure the serial port is available as described in "Freeing UART on the Pi." 
  3. Install the Java RXTX library:  apt-get install librxtx-java 
  4. Create soft link to comm port:  ln -s /dev/ttyAMA0 /dev/ttyS80 The RXTX library can't find /dev/ttyAMA0.  You will need to re-create this symbolic link whenever you reboot the Raspberry Pi. 


Copernicus II Raspberry Pi
VCC           3.3V 
GND           GND 
TX-B          GPIO15
RX-B          GPIO14

Java Code


import java.util.*;

public class gps {
    private static InputStream inStream;
    public static void main(String[] args) {
        try {
            CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("/dev/ttyS80");
            SerialPort serialPort = (SerialPort)"GPS application", 5000);
            // Change baud rate if not 115200
            serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, 
                 SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            inStream = serialPort.getInputStream();
            String reading ="";
            while(true) {
                if(inStream.available() > 0) {
                    int b =;
        } catch (Exception ex) {

Compiling & Running

When compiling, be sure to include the RXTX JAR file in the classpath.   

javac -cp /usr/share/java/RXTXcomm.jar

When you run the program, you will need to include the RXTX JAR file in the classpath and also tell the Java runtime where to find the .so library files for RXTX:

java -Djava.library.path=/usr/lib/jni/ -cp /usr/share/java/RXTXcomm.jar:. gps

(The command above assume your current working directory contains the gps.class file.)  

1 comment:

  1. Instead of re-creating the symbolic link on the raspberry you can instruct JAVA to use the ttyAMA0 port

    String SerialPortID = "/dev/ttyAMA0"
    System.setProperty("", SerialPortID)