Skip to content

Instantly share code, notes, and snippets.

@juanedi
Created January 13, 2015 18:09
Show Gist options
  • Save juanedi/5c8764b30ae6e1ef9121 to your computer and use it in GitHub Desktop.
Save juanedi/5c8764b30ae6e1ef9121 to your computer and use it in GitHub Desktop.
Read GPS coordinates form serial port
package com.cepheid.genexpert.reporter;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Enumeration;
import net.sf.marineapi.nmea.io.SentenceReader;
import net.sf.marineapi.provider.PositionProvider;
import net.sf.marineapi.provider.event.PositionEvent;
import net.sf.marineapi.provider.event.ProviderListener;
public class Gps {
public static InputStream openPort() {
@SuppressWarnings("unchecked")
Enumeration<CommPortIdentifier> portIdentifiers = CommPortIdentifier.getPortIdentifiers();
try {
for (CommPortIdentifier identifier: Collections.<CommPortIdentifier>list(portIdentifiers)) {
if (identifier.getPortType() == CommPortIdentifier.PORT_SERIAL
&& identifier.getName().equals("/dev/cu.usbserial")) {
SerialPort port = (SerialPort) identifier.open("SerialExample", 30);
port.setSerialPortParams(4800, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
return port.getInputStream();
}
}
throw new IllegalStateException("Serial port for GPS was not found");
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static void main(String[] args) throws IOException {
InputStream serialPort = openPort();
SentenceReader nmeaReader = new SentenceReader(serialPort);
PositionProvider positionProvider = new PositionProvider(nmeaReader);
positionProvider.addListener(new ProviderListener<PositionEvent>() {
@Override
public void providerUpdate(PositionEvent evt) {
// to format latitude and longitude, see implementation of evt.getPosition().toString()
System.out.println("TPV: " + evt.toString());
}
});
nmeaReader.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment