我使用串口连接一个返回给我的设备“:GS#”字符串。经过长时间的检查,我几乎可以肯定问题来自于 切换条件,即我的程序永远不会进入案例并始终进入默认状态。我在一个文本框中打印了收到的字符串,它是 “:GS#”!我很迷惑。我的错在哪里?
这是我的代码:
char[] lxCMD = new char[8];
.
.
.
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
serialPort.Read(lxCMD, 0, lxCMD.Length);
this.Invoke(new EventHandler(UpdateVar));
}
private void UpdateVar(object sender, EventArgs e)
{
string strRecieved = "Ack";
if (lxCMD[0] != 0x6)
{
strRecieved = new string(lxCMD);
}
textBox1.AppendText(strRecieved); // This line prints :GS# correctly!
textBox1.AppendText(Environment.NewLine);
switch(strRecieved)
{
case ":GS#":
serialPort.Write("20:08:18#");
textBox1.AppendText("1:");
textBox1.AppendText(Environment.NewLine);
break;
case "Ack":
serialPort.Write("1");
textBox1.AppendText("2:");
textBox1.AppendText(Environment.NewLine);
break;
default:
textBox1.AppendText("Nothing");
break;
}
}
答案 0 :(得分:1)
正如评论中指出的那样,保存读取字节的char
数组长度为8个字符。因此,当您将该数组转换为字符串时,它会创建一个长度为8的字符串,您可以通过调用strRecieved.Length
来检查它,例如:
textBox1.AppendText(strRecieved); // This line prints :GS# correctly!
textBox1.AppendText(Environment.NewLine);
Console.Out.WriteLine(strRecieved.Length); //or any other means of output - will output 8
这意味着字符串中有一些不可打印的字符(ASCII表为null)。因此情况并不匹配!
由于串行端口的Read
方法返回读取的字节数,请尝试使用它来获取正确的子字符串。例如(我认为这应该有效):
char[] lxCMD = new char[8];
var bytesRead = 0;
.
.
.
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
bytesRead = serialPort.Read(lxCMD, 0, lxCMD.Length);
this.Invoke(new EventHandler(UpdateVar));
}
private void UpdateVar(object sender, EventArgs e)
{
string strRecieved = "Ack";
if (lxCMD[0] != 0x6)
{
strRecieved = new string(lxCMD);
strRecieved = strRecieved.SubString(0, bytesRead)
}
textBox1.AppendText(strRecieved); // This line prints :GS# correctly!
textBox1.AppendText(Environment.NewLine);
switch(strRecieved)
{
case ":GS#":
serialPort.Write("20:08:18#");
textBox1.AppendText("1:");
textBox1.AppendText(Environment.NewLine);
break;
case "Ack":
serialPort.Write("1");
textBox1.AppendText("2:");
textBox1.AppendText(Environment.NewLine);
break;
default:
textBox1.AppendText("Nothing");
break;
}
}
答案 1 :(得分:1)
将if语句中的字符串strRecieved初始化更改为:
strRecieved = new string(chars.TakeWhile(c => c != '\0').ToArray());
问题是如果输入的长度不是8,则char数组最后会包含多个\ 0字符。
以下测试证明了这一点:
[Test]
public void stringConstructor_CharArrayWithSomeEmptyValues_StringWithoutEmptyValues()
{
var expected = "test";
var chars = new char[expected.Length+42];
chars[0] = expected[0];
chars[1] = expected[1];
chars[2] = expected[2];
chars[3] = expected[3];
var str = new string(chars.TakeWhile(c => c != '\0').ToArray());
Assert.AreEqual(expected, str);
str = new string(chars,0,chars.Length);
Assert.AreNotEqual(expected, str);
}