Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys,

I'm having a problem reading from a COM Port.
It's a GPS/Moderm device connect via a USB Cable.

C#
private void connectButton_Click(object sender, System.EventArgs e)
        {
            connectButton.Enabled = false;
            disconnectButton.Enabled = true;
            COMlistBox.Enabled = false;
            port.PortName = "COM23";
            //port.PortName = COMlistBox.SelectedItem as string;
            port.Parity = Parity.None;
            port.BaudRate = 9600;
            port.StopBits = StopBits.One;
            port.DataBits = 8;
            port.Open();
            timer1.Enabled = true;
        }

C#
private void ReadData()
        {
            byte[] bData = new byte[256];

            try
            {
                //Code hangs at this point
                port.Read(bData, 0, (int)bData.Length);

                protocol.ParseBuffer(bData);
            }
            catch(Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
                //swallow it.
            }

            DisplayNMEARawData(bData);
            DisplayGeneralInfo();
            DisplaySatellites();
        }

Please assist?

Kind Regards,
Ndeza
Posted
Comments
CPallini 26-Oct-11 4:58am    
And..
What is the problem?
ndeza 26-Oct-11 5:00am    
The Problem, is that is hangs, and donesn't read any data.

1 solution

Well yes. It will hang there, unless the buffer already contains 256 bytes.
SerialPort.Read is a blocking call: it does not return until it has acquired the specified number of bytes.
If it recieves 255 bytes, then it will wait for the last one. And wait, and wait, and wait...

Try using the SerialPort.DataRecieved event[^] instead - assemble the bytes and process them there rather than expecting a fixed number of bytes each time.
 
Share this answer
 
Comments
ndeza 26-Oct-11 5:08am    
Hi Griff,

Thank you for the sol, after hanging it brings up an error informing me that the "A device attached to the system is not functioning." Will try your sol and look in to the device.

Thanks for you help.

Kind Regrads,
Monde
OriginalGriff 26-Oct-11 5:29am    
The error message means that it didn't get the number of bytes you asked for, and eventually timed out. It doesn't mean the GPS/Modem is faulty, just that it assumes you know what you are asking for! :laugh:
ndeza 26-Oct-11 5:32am    
is that the default bytes needed?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900