Create Your Own GPS Applications Using C# (4)
Using the information in the previous 3 posts, we can now build our own GPS solution based on the Coding 4 Fun project. Our objective is to create a DLL that can be used in future projects that need to read from GPS devices. The DLL will serve as the interface between the program and a GPS device.
Project Setup
First, open Visual C# Express Edition and create a new class library project.
A class library will compile to a DLL and can be referenced by other projects later on. This is unlike a standard Windows application that produces an executable (EXE) file.
In the Solution Explorer, rename the Class1.cs to something more appropriate. Open the renamed class and change the namespace also.
At the top of code listing, add this line:
using System.IO.Ports;
Then add into this project the 4 C# code files from the Coding 4 Fun project - GPSStructs.cs, Location.cs, NMEAProtocol.cs, and Satellite.cs. Remember, we modified the NMEAProtocol.cs file in our previous post so be sure to read that first.
Coding
Inside our class, we need to add three member variables:
private NMEAProtocol _protocol; private SerialPort _port; private bool _validData;
These variables are initially defined in the constructor:
public myGPS() { _protocol = new NMEAProtocol(); _port = new SerialPort(); _validData = false; }
Next, we need a method to connect to the GPS device based on a set of parameters. For this project, we will assume the necessary information on port name and baud rate are already known and will be passed in when the function is called:
public bool Connect(string portName, int baudRate) { try { _port.PortName = portName; // "COM1", "COM2", etc. _port.Parity = Parity.None; _port.BaudRate = baudRate; // 4800, 9600, etc. _port.StopBits = StopBits.One; _port.DataBits = 8; _port.Open(); return true; } catch { return false; } }
Conversely, we will need a function to disconnect from the device:
public void Disconnect() { if (_port.IsOpen) _port.Close(); }
To be continued…