Wireless DevCenter    
 Published on Wireless DevCenter (http://www.oreillynet.com/wireless/)
 See this if you're having trouble printing code examples


GPS, Palm Pilot, OpenGL ... Let's Go!

by Chris Halsall
12/08/2000

GPS receivers are demonstrably the best available tool for figuring out where you are. Now that selective availability (SA) has been disabled, the accuracy of civilian-class SPS GPS is perfectly adequate for sea and land travel. As a result, consumer-level technology deployment continues to accelerate, resulting in lower costs per unit.

A fairly major limitation of GPS receivers, however, is the small amount of memory that stand-alone units have to store coordinates -- most modern GPS units can store only 500 or so "waypoints." The software that runs on a GPS receiver is also generally closed, so customization is not an option. And asking if a GPS unit runs Java usually results in blank stares.

Fortunately, GPS receivers can be interfaced with mobile computing solutions by way of the National Marine Electronics Association (NMEA) standard for marine instrumentation. Now up to NMEA 0183 version 2.3, data is presented as a series of sentences in a 4800 baud 8N1 data stream compatible with computer RS-232 interfaces.

What's done with the data at that point is, of course, then entirely in the province of the software developer. Just about anything can be done. How much money do you have to throw at the solution?

Plot of a road trip, with coastal outlines.

Plot of a road trip, with coastal outlines.

A common example is the use of a laptop computer to plot a sailboat's position on a dynamic chart. For vehicle drivers, both laptop and embedded solutions include databases of streets, and they can give advanced notice of where to turn next when navigating the streets. The expanded memory capacity of mobile computing devices allows for many more position samples to be recorded for playback and analysis.

Another area that will add exciting (and in some cases, scary) possibilities is ubiquitous mobile networking. With a way to transmit the GPS receiver's data, mobile assets can be monitored for misuse (over-speed or off-route) as well as safety. Police and emergency vehicles, along with taxi cabs in high-risk areas, are already beginning to use this ability, as are organizers of sailing races.

Lastly, the electronics industry's perpetual march toward the tiny and inexpensive continues in the GPS receiver space as well, with complete receivers the size of small electrolytic capacitors now possible. Because of the future requirement for cell phone companies to be able to physically locate callers to 911, GPS receivers are expected to start showing up in mainstream cell phones in the very near future. Specialty models are available right now.

Imagine what you could do -- or better yet, what you can start experimenting with now...

The GPS data-stream -- the details

Most consumer level GPS receivers, either handheld or vehicle mounted, "expose" current data by way of the NMEA 0183 standard. This is presented on a 4800 baud serial stream, with neither hardware nor software handshaking enabled -- you just hope you get most of the data.

NMEA 0183 defines a set of sentences, each beginning with a five-letter name preceded with a dollar sign. The name is made up of a two-letter "talker" ID, followed by a sentence ID. Examples include "$GPGGA" and "$GPGGL." The sentence will usually terminate with a "*" followed by a simple checksum. Some manufacturers also provide additional proprietary sentences -- most notably Garmin.

Each sentence "payload" consists of a comma-separated series of values, the number and meaning of which are defined by the standard. Two excellent resources for the NMEA standard and definitions of the sentences, along with some of the Garmin sentences, are at Glenn Baddeley's GPS pages and Peter Bennett's GPS and NMEA site.

The sentences of most interest to programmers are defined below. Note that GPS receivers may not transmit all of these sentences, so care must be taken when purchasing a receiver for a particular application.

$GPGGA

Provides time (UTC), latitude and longitude fix, and altitude. In addition, quality of fix, number of satellites used in fix, horizontal dilution of precision, and height of geoid above WGS84 ellipsoid is provided. If differential GPS (DGPS) is in use, the station's ID and time since last update is also presented.

This sentence was introduced with NMEA 0183 version 2.00, and combines into one what previously required several sentences. Not all receivers present data in all fields.

$GPGLL

Provides time and latitude and longitude fix. Superseded by GPGGA with version NMEA 0183 version 2.00.

$GPRMC

Gives time and latitude and longitude fix. Also, true and magnetic track (heading) and ground speed, along with magnetic variation.

$GPVTG

Gives true and magnetic track (heading) and ground speed. Note these values are derived from successive positions, and so are only valid while in motion. A GPS receiver never knows its orientation, and can only infer such information.

$GPGSA

Presents IDs of all satellites used for the fix calculation, as well as the fix mode (No Fix, 2D, 3D), and whether it's being forced into that mode manually, or if it was an automatic selection. The position, horizontal, and vertical dilution of precision (PDOP, HDOP, and VDOP, respectively) are also given.

$GPGSV

Is a list of the satellites in view, including their elevation and azimuth (rotation) from the receiver's location, and the signal strength. Up to four satellites can be presented in one sentence, and as many sentences as are needed are transmitted in sequence.

$GPZDA

Current date and time, including local time-zone differences, with a high resolution. Not a common message. Because of its accuracy, this is often used with ntp deamons (or similar) to provide precise time alignment for (geographically) large networks. Examples include the Internet, the phone networks, and national/international power grids.

There are several other messages which might appear in a stream, depending on the settings and modes of the GPS. A full block of sentences is transmitted at a time, usually at a 1Hz frequency. If there is too much data to transmit in one second, the GPS unit will wait until all the data is sent and then wait for the next top-of-second. Thus the rate may drop to once every two seconds, or three, etc.

For this reason, it is usually advisable to disable any messages that aren't needed, as they're consuming valuable bandwidth! In particular, if a route is currently enabled, several sentences dealing with the next waypoint will be included. Unless needed, routes and waypoints should be disabled. Exactly how this is done is specific to each GPS unit, and I suggest you refer to your receiver's manual.

Acquiring some data...

For the mobile examples, I used a Palm Pilot IIIxe to capture hiking data and a lap-top to capture road-trip data. At roughly a megabyte of data per hour from a typical unit, a Palm Pilot IIIxe can acquire about 7 hours of uncompressed data, with modern laptops good to go for several months.

Coastal outlines improve visualization.

Coastal outlines improve visualization.

The physical connection between the GPS receiver and the laptop computer is made with a cable you either make yourself or pay a surprisingly high price for from the manufacturer. The cables are wired to be compatible with DB9 style serial ports of PCs.

To connect the Palm Pilot, the same PC cable will be compatible with the Palm modem cable if you have one, or the normal cradle cable (or mobile version) combined with a null-modem adapter. If you're building your own cables, you may decide to have two versions, one for use with the Palm's mobile cradle cable and another for use with laptops.

A third common configuration is a permanently wired installation in a building, with a cable running to the GPS or only to the antenna on the roof. While usually used in order to provide accurate time code to a server, it can also be a handy warning during office parties -- when the building starts to oscillate to the tunes, it's time to turn it down!

For Palm software, two main classes exist -- ones that simply log the data for later use, and others which use or display the data immediately in real time. Free examples for logging include File-X-Fer and GPS TrackLogger, or any transfer utility that can capture and retransmit serial data.

A few examples for immediate processing include PilotGPS, tzgps and NMEA Mon. Solutions are available that display full real-time location on a map, but only from commercial suppliers. The Palm's ".3" secret shortcut is handy to know about, disabling the automatic power-off feature if the software doesn't do this itself. Beware of other "." shortcuts, however; their use is rather dangerous.

For full mobile PCs, a wide range of software is available. Something as simple as minicom or another serial communication program can be used to capture data for post-processing. On the other hand, several versions of GPS broadcast deamons exist, which allow multiple clients to access a GPS. See GPSd and NMEA Server as examples.

Sample files:

airport.gps - GPS Track - Road trip to the airport.

wander.gps - GPS Track - 23 hour plot of a stationary receiver.

victoria.gps - Outline - Canada's vacation hotspot.

lowerisland.gps - Outline - An island on the far west coast.

There are several sample files included in the adjacent sidebar for examination and used in the program found at the end of this article. These have been acquired by four different GPS units over the course of several months.

An important note: GPS receivers provide fixes relative to a map datum, which can be set. The default is the World Geodetic Survey, 1984 (WGS 84). However, if using the GPS with an existing map (either electronic or traditional), the GPS unit must be set to match or significant errors will result.

An excellent resource for extracting coastal outlines in WGS 84 Datum is the US Geologic Survey's Coastline. The data is not in NMEA format, however, so a filter is required to translate into NMEA. An example Perl script, ll2nmea.pl was written for our purposes. This inserts GPGGA messages with "999999" as the datestamp whenever the plot should be broken, which our program watches for. This allows islands and other non-continuous outlines to be plotted.

Building your own cables

For those who still love the sight of solder melting, the smell of flux in the (well-circulated) air, and the creative freedom of a roll of shielded twisted two-pair and the right ends, this section's for you. Dig out your soldering iron!

Soldering the cables.

When soldering, why limit yourself to opposing thumbs? Steady hands are required to avoid cold-solder joins.

If you prefer your cables prebuilt, and pronounce solder the way it's spelled, I refer you to your GPS manufacturer. However, please be prepared for sticker-shock -- a GPS-to-PC cable can cost as much as 40% of the price of an inexpensive GPS receiver.

Besides cost, in many cases it may be desirable to have many different cables for one or more GPS units, each appropriate depending on location or use. GPS-to-PC adapter cables also do not "expose" the power supply pins on the DB9 connectors, so to supply power to the receiver for long-term use, a power and data adapter cable must be acquired. These are almost universally designed to plug into a cigarette lighter in a vehicle, however, so they aren't optimal for building installations.

Thus, simply for flexibility reasons, building a custom cable is often desirable if you have the skills to do so. Unfortunately, once you try to acquire the proper ends, or connectors, to mate with the GPS units, you quickly find that most GPS manufacturers use proprietary connectors.

Arg! Foiled by a little bit of plastic and metal!

Fortunately, in the case of the Garmin units, there's an answer! It turns out that one person who encountered this very problem also happened to have access to a plastic injection mold machine. Full details, including information on how to have a couple shipped out to you upon pledge of payment, are available at Larry's PPlug page

Long story short: There's a world-wide network of "Pfranc"s, who have implemented a "share-hardware" distribution network for these little connectors. Find your nearest Pfranc, fill out an order form including agreement to send some amount of money (or something in kind), and the connectors are on their way.

Once you receive them and agree they're to spec, you submit your pledge. Fill out the check while your iron comes up to temperature. Connectors for older (e.g., GPS 12) series have been available since 1996. The new interface type used for the eMap and eTrex series has just become available as well.

A compact adapter for a Palm mobile cable.

A compact adapter for a Palm mobile cable.

Beyond the difficulties of acquiring the correct connectors and getting documentation on which pins are what, the actual wiring is quite trivial. To connect to a computer's serial port, the GPS Data-Out (T) pin connects to a DB9 female connector's pin 2. The Data-In (R) goes to pin 3, and GPS Ground connects to pin 5. These pins correspond to RxD, TxD and GND, respectively, on the computer's serial port.

When wiring a cable to interface directly with a Palm Pilot's cradle or mobile PC connector cable, a DB9 male connector is used instead, and pins 2 and 3 are reversed. Another option is to place a null-modem adapter between the above wired PC GPS and the Pilot cables, but it obviously won't be as compact.

When building a cable to provide power to the GPS unit, extreme care must be taken to provide only the voltage level the GPS can handle. Different GPSs have very different requirements, ranging from +24 to +3.3 volts DC. Supplying the wrong voltage, or the correct voltage to the wrong pin, can result in a very fast and very expensive lesson.

Even when only building a data cable, serious damage can still result from incorrect wiring. If you're not comfortable performing this kind of work, ask a friend who is to help, or perhaps invest in a professionally built cable. Letting out the Magic Blue Smoke is bad karma.

Humm ... 3D data ... OpenGL!

When you start to think about data returned by a GPS receiver, you immediately realize that it's three dimensional. Thus, the display of GPS data will often be very well suited for implementation in OpenGL, letting the standard do most of the heavy lifting. It's not being lazy, it's being efficient!

GPS fixes include three values: longitude, latitude, and altitude. For simple cases covering relatively small areas (a few hundred kilometers), these can be mapped to X, Y, and Z and displayed. However, for more advanced cases where high precision is required, the lat, long, and altitude must be mapped onto a spheroid as defined by the map datum.

In order to keep our demonstration program as simple as possible, we're going to take the easy route and do the simple linear transform. This will be adequate for our purposes, but those who require greater precision are encouraged to investigate the WGS83 specification.

The program presented here builds upon previous examples in past articles. A familiarity with these, or OpenGL in general, is presumed.

GPS data plotter

It takes surprisingly little effort to get a meaningful plot of GPS data using OpenGL. Once an NMEA parser has been written, the rest of the work is primarily just record-keeping for all the data. OpenGL has an antialiased lines mode which results in nicely blended images.

First person point of view of a local road trip.

First person point of view of a local road trip.

In our sample implementation, main() does the usual call to glutInit() and then calls a new function, ourLoadFiles(). This is passed the argc and argv variables, which include the command-line arguments passed to our program.

By calling ourLoadNMEA(), ourLoadFiles() will attempt to load up to 10 files passed to it on the command line. Data is stored in instances of the Point structure, with bookkeeping information for each file in instances of the Points header structure.

After all the files have been loaded, a second pass is made through the data converting latitude, longitude and altitude into Y, X, and Z, while at the same time normalizing the points to be within +/- 1.0 horizontally and 0.0 to 0.5 vertically.

The ourLoadNMEA() parser is a fairly simple affair, and is only interested in GPGGA messages. It itself leverages on ourChecksumValid() to confirm the checksum of each message before attempting to parse, although, as it's a simple XOR checksum, errors can still slip by. The function keeps an eye out for messages with a datestamp of 999999, which is a non-standard flag we use to allow for non-continuous plots."

One thing to take note of is the extra effort made to extract the latitude and longitude values from each line. Standard versions of sscanf() can't scan for doubles, floats being the best available. Unfortunately, float values introduce rounding errors when representing the numerical resolution provided in the NMEA format. This extraction is encoded in the ourParceFraction() function.

The other new feature of this program is the inclusion of some additional GLUT callbacks, glutMouseFunc() and glutMotionFunc(). These are used to implement a more natural way of moving around in 3D space using the mouse. A quick call to ourOGLInit() for some of our last-minute housekeeping (including generation of Display Lists for ground tracks for each file), and then we're into glutMainLoop().

What are we drawing?

On the path of a local road trip.

On the path of a local road trip.

As usual, cbRenderScene() is where we draw our pretty pictures, based on any data we've already loaded plus any inputs acted upon by the other callback functions. The first thing this function does is enable or display line smoothing, depending on the current flag. Controlled with the 'A' key, antialiased lines result in beautiful images. This is off by default, but should be enabled if hardware support (or a fast CPU) is available.

The next thing is to act upon the "On Path" flag, toggled with the 'O' key. Using gluLookAt() places the viewpoint either on the first file's path, looking at the current position, or at some independent "First Person" location. The path positions increment by some value each frame, which can be controlled with the "<" and ">" arrow keys. Thus, when on the path, it's as if you're replaying the trip.

In first person mode, on the other hand, your position remains the same during the playback of the first file's data. Pressing the left mouse button and dragging around the screen results in the view rotating around, but the position remaining the same. Dragging the middle mouse button changes the observational point's height, while dragging with the right button adjusts the position of the observer. The Page Up/Down buttons, and arrow keys, offer the same functionality.

Note that in first person mode, the motion commands are relative to the current orientation. Thus, simply adding some value to the observer's position when forward motion is requested doesn't work. Instead, a point-of-interest vector is maintained, which is both the direction we are looking as well as where we should move to in case of forward motion.

The OpenGL feature GL_LINE_STRIPS comes in handy. Used to draw successive, attached line segments, it allows us to send half as much data to OpenGL to draw our paths as we might otherwise have to. The GLUT library's stroked characters are also used to incorporate text directly into the 3D scene.

Empirical data

A plot of a stationary GPS receiver over several hours.

A plot of a stationary GPS receiver over several hours.

The GPS Plotter program accepts multiple files in order to allow past trips to be compared to the most recent, for example, or to include sets of tracks for reference. The first ground-track is color-coded based on the time stamp for each fix, varying from red to blue for the earliest to oldest fix. The green value is set based on the time stamp's seconds, so gives a clear indication of time frame and thus speed. Any other groundtracks are assigned a solid, preset color.

In addition to the usual applications of plotting positions during over-ground travel, plotting a stationary receiver's data stream over several hours or days can be informative, too, if a little discouraging. In fact, anyone who uses their GPS for anything serious would be well advised to collect several days worth of data, and to take the observed random wander into consideration.

If you have more than two GPS units, try collecting data from both of them at the same time, and feed them to this program. As we'll examine much more deeply in our next installment, two GPSs don't help improve things much.

Conclusions

This program is intended for developer experimentation and adoption. Because of the overly simple Lat/Long/Altitude to X/Y/Z transformation, it should not be used for serious navigation or distance calculation. For such work, commercial off-the-shelf (COTS) software is probably best.

On the other hand, for those wishing to experiment with GPS programming, it should be good enough to start. True WGS84 support could be added without too much effort, as could texture mapping of imported maps for current position on a chart type display where outline vectors are not adequate.

As GPS receivers start finding their way into PDAs, 3D plotting applications such as is demonstrated here will soon be possible in self-contained hand-helds. In fact, if you were to combine a GPS module and a Handspring or a clip-on GPS for a Palm, such functionality is technically possible now; there is a sub-set port of OpenGL available for the Palm OS.

Although, in reality, it's going to take something more powerful than a Palm to do meaningful OpenGL displays. Palms are OK for logging or simple processing, but 3D is really a bit beyond them. On the other hand, something like the iPAQ or Yopy would likely have little trouble generating a very interesting real-time display from a GPS stream.

The GPS with Palm.

On the bleeding edge, strange looks just mean you might be doing something right.

Real-time plotting is only one possible solution space when GPSs are considered, however. As receivers continue to shrink in size and cost, current position data will become available to a greater number of devices, and thus to their programmers. With background logging of data, or combining position data with other events, exciting possibilities arise.

PDAs will be able to report where, physically, each and every note, address or e-mail message was entered, and where they themselves have been for the last month. They may be programmed to demand a password if they ever find themselves outside of a pre-set geographical area, and to "phone home" if the challenge fails. And, of course, when you're hungry for sushi, they'll know where to go for the best tekka maki and ika.

Download Files for OpenGL GPS Datastream Plotter

gpsplot.c
Makefile

Sample files:

airport.gps - GPS Track - Road trip to the airport.
wander.gps - GPS Track - 23 hour plot of a stationary receiver.
victoria.gps - Outline - Canada's vacation hotspot.
lowerisland.gps - Outline - An island on the far west coast.

It is already possible for vehicles to know where they are, and to give directions to particular destinations. Currently still quite expensive, mass production will result in such ability to be standard options on most cars by the middle, or, at the very latest, the end of the decade. For teen-agers, borrowing the family car will be far less like getting true freedom for a few hours than it current does -- wireless networking will allow constant monitoring of location and speed.

All this leads to the holy grail, of course: pervasive computing. At about the same time as everything is tiny, running code and chatting on wireless networks, everything should also know (approximately) where it is physically. The possibilities that result from this are only beginning to be explored and exploited.

So, as you get strange looks from people as you wander around with a GPS cabled to your PDA, both balanced in one hand, just remember the chant: "I'm living the future... I'm living the future..." Strange looks are nothing, especially if you come up with the next killer app.

Chris Halsall is the Managing Director of Ideas 4 Lease (Barbados). Chris is a specialist... at automating information gathering and presentation systems.


Related Articles:

Where Are You, Exactly? A GPS Introduction

Creating Real Time 3D Graphics With OpenGL

OpenGL Rendering and Drawing

Preparing to Build an OpenGL Application

Building a Black Hole With OpenGL


Discuss this article in the O'Reilly Network Wireless Forum.

Return to the Wireless DevCenter.

 

Copyright © 2009 O'Reilly Media, Inc.