如何检查我的串口是否在c#中没有接收到更多的数据

本文关键字:数据 检查 何检查 我的 是否 串口 | 更新日期: 2023-09-27 18:03:08

我试图确定我是否正在接收数据,因为每次我运行我的程序时,我都期待不同数量的数据。下面是我的代码来说明:'

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

我是否需要在列表末尾添加'0 ?

如何检查我的串口是否在c#中没有接收到更多的数据

您可以使用BytesToRead属性。它将显示数据是否在接收到的缓冲区中。如果是,可以使用read方法之一来读取。

在你的代码示例中,你似乎一个字符一个字符地读取

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

另一种可能是读取整个缓冲区,然后解析输入:

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

我是否需要在列表末尾添加'0 ?

这取决于你使用这个字符的目的。但是要获取列表的最后一个元素,你可以使用:

int last = Receiverlist.Last();