C# Serial.DataRecieved 数据是分段的 [英] C# Serial.DataRecieved data is in pieces
问题描述
我正在制作一个程序,它在所有可用的 COM 端口中搜索文本ConnectAlready".多亏了堆栈溢出方面的人的帮助,我才能完成大部分工作.我在控制台上打印了我收到的数据,但我得到的不是一个字符串ConnectAlready",而是类似于:
I'm making a program that is searching all available COM ports for a text "ConnectAlready." Thanks to the help of people on stack overflow I was able to do a majority of it. I print the data i receive on the console, but instead of getting one string "ConnectAlready", i get something like:
Conne
ct
alre
ady
每一个都是不同的字符串,因此我无法检查串行端口是否正在读取ConnectAlready".
Each one of those is a different string, and therefore i cannot check if the serial port is reading "ConnectAlready."
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort serialPort1 = sender as SerialPort;
byte[] data = new byte[serialPort1.BytesToRead];
Stream portStream = serialPort1.BaseStream;
portStream.Read(data, 0, data.Length);
string dataString = Encoding.UTF8.GetString(data);
Console.WriteLine(dataString);
bool hasData = dataString.Contains("ConnectAlready");
if (hasData)
{
established = true;
estport = serialPort1.PortName;
MessageBox.Show(estport);
}
}
有什么建议吗?感谢您的帮助!
Any advice? thanks for your help!
推荐答案
好的,您的问题如下:如果您在 Port 上收到数据,则会触发该事件.然后你读取已经存在的字节.但是您的计算机比您的传输速度更快 --> 并非整个消息都已在您的缓冲区中.
Okay, your problem is the following: If you receive data on your Port, the event fires. Then you read the bytes that are already there. But your computer is faster than your transmission --> Not the whole message is already in your buffer.
这里有两种可能的解决方案:
Here are two possible solutions:
1:如果您的消息在末尾包含换行符,您可以像这样轻松做到:
//Add to your init:
YourSerialPort.Timeout = 100; //Maximum duration of your message in milliseconds
YourSerialPort.NewLine = "\r\n"; //You can also change the newline-character (you can also omit)
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string dataString = ((SerialPort)sender).ReadLine();
if (dataString.Contains("ConnectAlready"))
{
//Your code
}
}
如果您使用 Arduino Serial.println() 函数,这将是您的解决方案.
If you use the Arduino Serial.println()-function, this would be your solution.
2:请稍等片刻再阅读您的消息:
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.sleep(50);
SerialPort serialPort1 = sender as SerialPort;
byte[] data = new byte[serialPort1.BytesToRead];
Stream portStream = serialPort1.BaseStream;
portStream.Read(data, 0, data.Length);
string dataString = Encoding.UTF8.GetString(data);
Console.WriteLine(dataString);
bool hasData = dataString.Contains("ConnectAlready");
if (hasData)
{
//Your code
}
}
祝你好运!
这篇关于C# Serial.DataRecieved 数据是分段的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!