串口ReadLine与ReadExisting或如何正确读取串口数据

sar*_*ake 14 c# compact-framework serial-port windows-ce

我正在从串口读取数据.数据来自规模.我现在正在使用Readline()并在删除后删除数据DiscardInBuffer().从串口读取数据的正确方法是什么?网上的例子很少,我觉得这就像是一些没有人想到的圣杯.

有什么帮助吗?

好像串口是一个反复无常的孩子.

C#,WinCE 5.0,HP瘦客户端,Compact framework 2.0

 private void WeighSample()
    {
        this._processingDone = false;
        this._workerThread = new Thread(CaptureWeight);
        this._workerThread.IsBackground = true;
        this._workerThread.Start();
    } //end of WeighSample()


    private void CaptureWeight()
    {
         globalCounter++;
         string value = "";


          while (!this._processingDone)
          {
              try
              {

                 value = this._sp.ReadLine();

                  if (value != "")
                  {
                      if (value == "ES")
                      {
                          _sp.DiscardInBuffer();
                          value = "";
                      }
                      else
                      {
                          this.Invoke(this.OnDataAcquiredEvent, new object[] { value });
                      }
                  }
              }
              catch (TimeoutException)
              {
                  //catch it but do nothing
              }
              catch
              {
                  //reset the port here?
                  MessageBox.Show("some other than timeout exception thrown while reading serial port");
              }
          }


    } //end of CaptureWeight()
Run Code Online (Sandbox Code Playgroud)

关于我的应用程序需要注意的一点是,当光标跳到文本框时,我启动线程(weighSample).这样做的原因是重量也可以手动输入(部分需求).所以我事先并不知道用户是否要在天平上按PRINT或输入重量.在获取数据后的任何一种情况下,我退出工作线程.另外,请注意我没有使用串行端口事件DataReceived,因为我被告知它不可靠.

任何意见/想法欢迎.这是我第一次使用串口.

jos*_*rry 11

取决于输入数据的行尾(EOL)字符.如果您的数据是面向行的,则ReadLine是一个有效的函数,但您可能希望查看NewLine属性并确保为输入数据设置了相应的属性.

例如,如果您的比例输出EOL的换行然后设置 port.NewLine = "\n";

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.newline.aspx


cta*_*cke 5

从来没有幸运使用过ReadLine.只要在数据可用时读取本地缓冲区,然后使用单独的线程扫描数据并自行查找换行符.

  • 我已经读过Read是非阻塞的 - 我很困惑,似乎没有人真正解释它是如何工作的.这样做是否安全:_sp.Read(buffer,0,_sp.BytesToRead); 和缓冲区是char []谢谢!由于缺乏有关串口的信息,我感到不知所措. (2认同)