Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# SerialPort.ReadExisting()方法有时无法正确返回字符串_C#_Serial Port - Fatal编程技术网

C# SerialPort.ReadExisting()方法有时无法正确返回字符串

C# SerialPort.ReadExisting()方法有时无法正确返回字符串,c#,serial-port,C#,Serial Port,SerialPort.ReadExisting方法有时无法正确返回我的字符串 这是我的密码: string Initial=""; SerialPort sp = new SerialPort { PortName = "COM3", BaudRate = 9600, Parity = Parity.None, StopBits = StopBits.One, DataBits = 8, Handshake = Handshake.None}; sp.Open(); sp.WriteLine(

SerialPort.ReadExisting方法有时无法正确返回我的字符串

这是我的密码:

string Initial="";
SerialPort sp = new SerialPort { PortName = "COM3", BaudRate = 9600, Parity = Parity.None, StopBits = StopBits.One, DataBits = 8, Handshake = Handshake.None};

sp.Open();
sp.WriteLine("P");
Initial = sp.ReadExisting();  // Then Initial must be OK.

if (Initial == "OK")
{ ....}
但是,结果是“O”或“K”或“OK”。我不知道为什么会这样。我应该如何避免这种情况,并始终通过ReadExisting()或任何其他方法从串行获取正确的字符串


注意:由于C#中的新手,用代码发布你的答案会更有帮助。

一定要关注“现有”这个词。您只能获得存在的字符。串行端口速度较慢,因此接收缓冲区中只有“O”,而尚未接收的“K”是完全正常的。很可能您只需要sp.ReadLine()就可以解决问题。正如Hans所说,串行端口上的许多事情可能会出错或速度变慢。您还应该考虑使用协议。只有当接收到第一个字符和最后一个字符时才认为消息完成。把你的信息放进去,阅读它们之间的内容。如果没有更多的细节,就不可能回答这个问题。Hans是正确的,您正在看到正在调用的方法的正常行为,他猜测您可以调用
ReadLine()
(您调用
WriteLine()
来发送数据,因此您的协议可能使用换行符来分隔消息)。但是,如果将
ReadExisting()
更改为
ReadLine()
无法解决问题,则需要编辑问题以提供有关您的情况的更好详细信息。