Collecting the data from a GPS module

require 'time'
require 'serialport'

class GPS

  def parse(s)

    _, raw_time, raw_lat, ns, raw_lon, ew = s.split(',')
    time, latitude, longitude = Time.parse(raw_time), 
                               decimalize(raw_lat, ns), decimalize(raw_lon, ew)
  end

  private

  def decimalize(raw_x, raw_nesw)

    nesw = {n: :+, e: :+, s: :-, w: :-}
    x = 0.method(nesw[raw_nesw.downcase.to_sym]).call(raw_x.to_f)

    degrees = (x / 100).to_i
    minutes = x - (degrees * 100.0)
    (degrees + (minutes / 60)).round(8)
  end

end

#params for serial port
port_str = "/dev/ttyAMA0"  #may be different for you
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE

sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)


gps = GPS.new

#just read forever
while true do

  if (str = sp.gets) =~ /^\$GPGGA/ then
    puts gps.parse(str).inspect
  end

end

sp.close

Output:

[2014-07-02 10:23:56 +0000, 55.91928883, -3.11704133]
[2014-07-02 10:23:57 +0000, 55.91928917, -3.11703833]
[2014-07-02 10:23:58 +0000, 55.9192865, -3.11703967]
[2014-07-02 10:23:59 +0000, 55.91928333, -3.117041]
[2014-07-02 10:24:00 +0000, 55.91928333, -3.11703967]
[2014-07-02 10:24:01 +0000, 55.91928317, -3.117037]
[2014-07-02 10:24:02 +0000, 55.91928083, -3.11703833]
[2014-07-02 10:24:03 +0000, 55.91927867, -3.11703783]
[2014-07-02 10:24:04 +0000, 55.91927733, -3.117037]
[2014-07-02 10:24:05 +0000, 55.9192765, -3.1170355]
[2014-07-02 10:24:06 +0000, 55.91927633, -3.1170335]
[2014-07-02 10:24:07 +0000, 55.9192755, -3.1170345]
[2014-07-02 10:24:08 +0000, 55.9192745, -3.1170355]
[2014-07-02 10:24:09 +0000, 55.9192725, -3.11703617]
[2014-07-02 10:24:10 +0000, 55.91927117, -3.11703733]
[2014-07-02 10:24:11 +0000, 55.91927167, -3.11703483]
[2014-07-02 10:24:12 +0000, 55.9192695, -3.11703583]
[2014-07-02 10:24:13 +0000, 55.91926883, -3.11703517]

Resources

Tags:
Source:
1140hrs.txt
Published:
05-07-2014 11:40