The .NET Framework provides handy functions for communication with ports, such as the COM port required to read GPS data. This has been described in other articles on CodeProject.
Although these functions are also available in the Compact Framework, listening to GPS data by simply opening a stream using the correct COM port does not work, on many devices, due to limitations in the Compact Framework installed on the device.
This article describes a DLL written in C++ giving full control over the communication with the COM port. It exports functions to open, configure, and close the port, as well as read information form the port character by character.
When developing my Maplorer application (www.maplorer.com), I found that communication would only work from native applications, and only for a buffer size of one, single character. In principle, reading GPS data is fairly simple, as the GPS device constantly sends all readings to a (device-specific) COM port as a never-ending string. All you have to do is listen to that port and parse the string using the NMEA syntax. As .NET functionality was not available on my device, I developed a DLL to provide it.
Using the Code
The functions contained in the DLL can be used very easily in any .NET application via the
DllImport statement; for example, to use the function in any of your classes, just add:
public static extern int InitGpsCom(int Port, int BaudRate,
int ByteSize, int StopBits, int Parity);
public static extern char ReadNextChar();
public static extern int CloseGpsCom();
The three functions listed are used to open communications (
InitGpsCom), read the next character (
ReadNextChar), and free the port.
ReadNextChar function can be easily used to read NMEA sentences, knowing that each new sentence starts with a '$' sign; for example, in C#, you would write something like this:
public String ReadNextSentence()
String result = "";
while ((c = ReadNextChar()) != '$')
result += c;
result = "$" + result;
GpsDllSample.zip provides a complete example for using the DLL in C#, including an NMEA class to parse NMEA sentences and determine latitude, longitude, bearing, etc.
Points of Interest
This project mainly shows you that you can always gain control of a device on your own: if functionality is not available in your programming environment, you can usually find it one level deeper!
The drawback of this solution is the fact that it limits your applications to the CPU architecture the DLL is compiled for - you now run native code, not only .NET byte code.
- Version 1.0: February 2010.