3
votes

I am using a GPS mouse/receiver connected via USB (creates virtual COM port) to determine the computer time drift. GPS mouse sends a PPS event in form of a NMEA message I would like to have a precise timestamp of each message received so that I can calculate the difference between GPS time and computer time.

What is the best way to get a time stamp as soon as the message is received. I tried both with polling the serial port and data received event. Right now my code looks like this:

     while ( serialPort.IsOpen())
        {

                if (serialPort.BytesToRead != 0)
                {   GetSystemTimePreciseAsFileTime(out filetime);
                    DateTime collected = DateTime.Now;


                    time.Add(collected.Ticks.ToString());
                    time2.Add(filetime.ToString());

                    serialPort.DiscardOutBuffer();
                    serialPort.DiscardInBuffer()
                }
                else {

                } 
        }`

I have tried with DateTime.Now.Ticks with Stopwatch but the Noise of the difference is arround 20ms. I have seen papers where 1ms accuracy/precision was achieved. Does anyone have an idea what am I doing wrong?

1
Why are you using GetSystemTimePreciseAsFileTime() AND DateTime.Now? Why not just use GetSystemTimePreciseAsFileTime()? - Matthew Watson
I was trying all the possible timers available in C# and compared them to see if this was the problem. It was just for comparison. - gojcic

1 Answers

0
votes

DateTime will have jitter, that is documented:

The resolution of this property depends on the system timer, which is approximately 15 milliseconds on Windows systems

MSDN

The StopWatch is actually a wrapper around the multimedia timers, the most accurate timers available on the windows platform, but they do not offer an absolute time. They give ticks at a certain frequency, knowing both you can convert that to time. The thing is that the ticks are ticks from startup and have no relation to the system time.

On a sidenote: it depends on how precise you want to go. Don't forget that there is a certain delay in the hardware receiving the message and reading the bytes in the .NET serial class. The latency can be substantial compared to 'hard realtime' for which .NET is not suited.