让我解释一下场景:为我带来数据(字符串)的串行端口,如下例所示:
02051014 0009 M 0 741 30041105 2632 0 30041105
我尝试过各种读取(读取、读取字节、读取字符、读取行、读取现有)。我试图更改新行,但数据一直重复。看看上面的例子,现在看看数据是怎么来的:
0220510114 00009 M 0 741 300441105 2632 0 300411055
任何人都知道我该如何解决这个问题?
编码:
[...]
try
{
this.serialPort = new SerialPort("COM1", 2400, Parity.None, 7, StopBits.One);
this.serialPort.DataReceived += new SerialDataReceivedEventHandler(portaSerial_DataReceived);
this.serialPort.Handshake = Handshake.XOnXOff;
this.serialPort.Encoding = Encoding.ASCII;
this.serialPort.Open();
}
[...]
private void portaSerial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
var invalidValuesToBreakLine = new int[] { 13, 10, 0 };
int data;
while (this.serialPort.BytesToRead > 0)
{
data = this.serialPort.ReadChar();
if (invalidValuesToBreakLine.Contains(data))
{
if (!this.breakLineWasPerformed)
{
this.breakLineWasPerformed = true;
this.dataList.Add(this.temporaryString);
this.temporaryString = string.Empty;
}
}
else
{
if (this.breakLineWasPerformed)
{
this.breakLineWasPerformed = false;
}
this.temporaryString += (char)data;
}
}
[...]