如何检查我的串行端口是否不再接收 C# 中的任何数据?
How to check if my serial port is not receiving any more data in C#?
我正在尝试确定我是否正在接收数据,因为每次我 运行 我的程序都期待不同数量的数据。这是我的代码来说明:`
List<int> Receiverlist = new List<int>();
while (There is data from serialPort1 ) {
serialinput = serialPort1.ReadChar();
Receiverlist.Add(serialinput);
}`
我需要在列表末尾添加 \0 吗?
可以使用BytesToRead
属性。它将显示数据是否在接收缓冲区中。如果是这样,您可以使用其中一种读取方法来读取它。
在您的代码示例中,您似乎是逐个读取字符
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
}
Do I need to add [=14=] in the end of my list ?
这取决于您使用此字符的目的。
但是要获取列表的最后一个元素,您可以使用:
int last = Receiverlist.Last();
我正在尝试确定我是否正在接收数据,因为每次我 运行 我的程序都期待不同数量的数据。这是我的代码来说明:`
List<int> Receiverlist = new List<int>();
while (There is data from serialPort1 ) {
serialinput = serialPort1.ReadChar();
Receiverlist.Add(serialinput);
}`
我需要在列表末尾添加 \0 吗?
可以使用BytesToRead
属性。它将显示数据是否在接收缓冲区中。如果是这样,您可以使用其中一种读取方法来读取它。
在您的代码示例中,您似乎是逐个读取字符
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
}
Do I need to add [=14=] in the end of my list ?
这取决于您使用此字符的目的。 但是要获取列表的最后一个元素,您可以使用:
int last = Receiverlist.Last();