问题
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
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!
回答1:
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: If your Message contains a Newline-Character at the end you could do it easy like this:
//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
}
}
If you use the Arduino Serial.println()-function, this would be your solution.
2: Wait a short time before read your message:
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
}
}
Good luck!
来源:https://stackoverflow.com/questions/34698237/c-sharp-serial-datarecieved-data-is-in-pieces