【发布时间】:2012-11-26 22:43:08
【问题描述】:
我通过串行端口定期接收一些数据,以便绘制它并做更多的事情。为了达到这个目的,我将数据从我的微控制器发送到我的计算机,并带有一个标头,它指定了每个数据包的长度。
除了最后一个细节外,我的程序运行良好且运行良好。当标头指定长度时,我的程序在达到该字节数之前不会停止。因此,如果由于某种原因,丢失了一个数据包中的某些数据,程序将等待并获取下一个数据包的开头......然后开始真正的问题。从那一刻起,一切都失败了。
我想过每 0.9 秒增加一个计时器(包每秒来一次),它会发出命令以返回等待并重置变量。但我不知道该怎么做,我试过但在运行时出现错误。由于 IndCom(请参阅下一个代码)在某些函数的中间重置,并且出现“索引超出范围”时出现错误。
我附上我的代码(没有计时器)
private void routineRx(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
int BytesWaiting;
do
{
BytesWaiting = this.serialPort.BytesToRead;
//Copy it to the BuffCom
while (BytesWaiting > 0)
{
BuffCom[IndCom] = (byte)this.serialPort.ReadByte();
IndCom = IndCom + 1;
BytesWaiting = BytesWaiting - 1;
}
} while (IndCom < HeaderLength);
//I have to read until I got the whole Header which gives the info about the current packet
PacketLength = getIntInfo(BuffCom,4);
while (IndCom < PacketLength)
{
BytesWaiting = this.serialPort.BytesToRead;
//Copy it to the BuffCom
while (BytesWaiting > 0)
{
BuffCom[IndCom] = (byte)this.serialPort.ReadByte();
IndCom = IndCom + 1;
BytesWaiting = BytesWaiting - 1;
}
}
//If we have a packet--> check if it is valid and, if so, what kind of packet is
this.Invoke(new EventHandler(checkPacket));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我是面向对象编程和 C# 方面的新手,所以请宽容!非常感谢你
【问题讨论】:
-
** 因此,如果由于某种原因丢失了一个数据包中的某些数据**:您可能想在开始规避之前解决问题?为什么数据丢失? µC 没有发送它,或者您的应用出于某种原因丢弃了它?
-
如果我是真的,那是因为我在强迫这种情况,发送错误的数据包(指定的长度比真实的长)。我从来没有错过一个数据包或一个字节。但这是实现GPRS应用的第一步,丢失数据的概率会增加。我首先通过串口测试程序,但我需要一个强大的程序,能够面对这类问题
标签: c# timer serial-port