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

发布于 2024-07-14 11:22:29 字数 1713 浏览 10 评论 0原文

我正在从串口读取数据。 数据超出了规模。 我现在正在使用 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()

关于我的应用程序需要注意的一件事是,当光标跳到文本框上时,我启动线程 (weighSample)。 原因是重量也可以手动输入(部分要求)。 所以我事先不知道用户是否要按天平上的“打印”键或输入重量。 无论哪种情况,在获取数据后,我都会退出工作线程。 另请注意,我没有使用串行端口事件 DataReceived,因为我被告知它不可靠。

这是我第一次使用串口。

I am reading data from serial port. The data comes off the scale. I am now using Readline() and getting data dropped even after I removed DiscardInBuffer().

What is the proper way to read the data from the serial port? There are so few examples online that I feel it's like some holy grail that no one has figured out.

C#, WinCE 5.0, HP thin client, 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()

One thing to note about my application is that I start the thread (weighSample) when the cursor jumps onto the textbox. The reason to this is that the weight can also be typed in manually (part of the requirements). So I don't know in advance whether a user is going to press PRINT on the balance or type the weight. In either case after the data is acquired, I exit the worker thread. Also, note that I am not using serial port event DataReceived, since I have been told it's not reliable.

This is my first experience with serial ports.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

平生欢 2024-07-21 11:22:29

取决于输入数据的行尾 (EOL) 字符。 如果您的数据是面向行的,那么 ReadLine 是一个有效的函数,但您可能需要查看 NewLine 属性并确保它针对您的输入数据进行了适当的设置。

例如,如果您的电子秤输出 EOL 换行,则设置 port.NewLine = "\n";

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

Depends on what the end-of-line (EOL) character(s) is for your input data. If your data is line oriented then ReadLine is a valid function to use, but you may want to look at the NewLine property and be sure that it is set appropriately for your input data.

For example, if your scale outputs linefeed for EOL then set port.NewLine = "\n";

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

东北女汉子 2024-07-21 11:22:29

从未有幸使用 ReadLine。 只需在数据可用时读取本地缓冲区,然后使用单独的线程扫描数据并自行查找换行符即可。

I have never had luck with ReadLine working. Just do a Read into a local buffer whenever data is available and then use a separate thread to scan the data and find line breaks yourself.

鹤仙姿 2024-07-21 11:22:29
if (serialPort1->IsOpen){
    if (serialPort1->BytesToRead>0){
        this->textBox1->Text += serialPort1->ReadExisting();
    }
}
if (serialPort1->IsOpen){
    if (serialPort1->BytesToRead>0){
        this->textBox1->Text += serialPort1->ReadExisting();
    }
}
ヅ她的身影、若隐若现 2024-07-21 11:22:29

我添加一个答案来回应 Elias Santos。 使用 ReadExisting 方法有一些问题:

https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readexisting(v=vs.110).aspx

请注意,此方法可能会在
内部缓冲区,这使得 BytesToRead 值大于零。

我之前遇到过 ReadExisting 的一些问题,这是因为不需要的字节。 使用 Readline 解决了这些问题。

I am adding an answer to respond to Elias Santos. There are some gotchas in using the ReadExisting method:

https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readexisting(v=vs.110).aspx

Note that this method can leave trailing lead bytes in the
internal buffer, which makes the BytesToRead value greater than zero.

I faced some issues with ReadExisting before and this is because of the unwanted bytes. Using Readline fixed those issues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文