从COM端口读取 [英] Reading From a COM Port

查看:134
本文介绍了从COM端口读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我在从COM端口读取时遇到问题.
这是通过USB电缆连接的GPS/调制解调器设备.

Hi Guys,

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

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;
        }


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();
        }


请协助?

亲切的问候,
Ndeza


Please assist?

Kind Regards,
Ndeza

推荐答案

好.除非缓冲区已经包含256个字节,否则它将挂在那里.
SerialPort.Read是一个阻塞调用:在获取指定的字节数之前,它不会返回.
如果接收到255个字节,它将等待最后一个字节.等等,等等,等等...

尝试使用 SerialPort.DataRecieved事件 [ ^ ]-组装字节并在那里进行处理,而不是每次都期望固定数量的字节.
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.


这篇关于从COM端口读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆