简体   繁体   English

如何检查我的串行端口是否没有在C#中接收更多数据?

[英]How to check if my serial port is not receiving any more data in C#?

I am trying to determine whether I am receiving data or not, since every time I run my program I am expecting a different amount of data. 我试图确定我是否正在接收数据,因为每次运行程序时,我都期望有不同数量的数据。 Here is my code to illustrate:` 这是我的代码来说明:

List<int> Receiverlist = new List<int>();
 while (There is data from serialPort1 ) {
  serialinput = serialPort1.ReadChar();
  Receiverlist.Add(serialinput);
  }`

Do I need to add \\0 in the end of my list ? 我需要在列表末尾添加\\ 0吗?

You can use the BytesToRead property. 您可以使用BytesToRead属性。 It will show you whether data is in the received buffer. 它将显示数据是否在接收的缓冲区中。 If so you can read it with one of the read methods. 如果是这样,您可以使用一种读取方法来读取它。

In your code example you seem to read char by char 在您的代码示例中,您似乎逐字符读取char

List<int> Receiverlist = new List<int>();

while (serialPort1.BytesToRead > 0) 
{
    string serialinput = serialPort1.ReadChar();
    Receiverlist.Add(serialinput);
}

another possibility would be to read the entire buffer and parse the input afterwards: 另一种可能性是读取整个缓冲区,然后解析输入:

if(serialPort1.BytesToRead > 0) 
{
    string serialinput = serialPort1.ReadExisting();
    // parse the input according to your needs
}

Do I need to add \\0 in the end of my list ? 我需要在列表末尾添加\\ 0吗?

It depends on what your purpose is with this char. 这取决于此char的用途。 But to get the last element of a list you can just use: 但是要获取列表的最后一个元素,您可以使用:

int last = Receiverlist.Last();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM