110,502
社区成员
发帖
与我相关
我的任务
分享
//串口接收数据,接收到的东西显示到文本框t1种,以备查看
String memo = "",tmpmemo="";
private void sp_DataReceived(object sender,SerialDataReceivedEventArgs e)
{
String readMsg = (sp.ReadExisting()).ToString();//串口获得的数据
//将收到的数据合并入缓存
tmpmemo += readMsg;
//永久缓存
memo += readMsg;
//数据正确,显示数据
this.Invoke(new EventHandler(delegate
{
t1.Text += tmpmemo + "\r\n";
t1.SelectionStart = t1.TextLength;
t1.ScrollToCaret();
tmpmemo = "";
}));
}
System.Threading.Timer T;
private void button5_Click(object sender,EventArgs e)
{
T = new System.Threading.Timer(tt,null,0,100);
}
//这里本来是要对字符串memo进行分析,将数据显示到窗体上的,为了测试程序是否正常工作,只是简单的显示累加数字
private void tt(object state)
{
Invoke(( ThreadStart ) delegate
{
l1.Text = (errCount++).ToString();
});
}
String memo = "";
private void sp_DataReceived(object sender,SerialDataReceivedEventArgs e)
{
String readMsg = (sp.ReadExisting()).ToString();//串口获得的数据
//将收到的数据合并入缓存
memo += readMsg;
}
Boolean show = false;
Regex reg = new Regex(@"ABCD\d+EFGH");//数据包格式为:以ABCD开始,EFGH结尾,共计64个字符。具体报文为0-9的数字
private void tt(object state)
{ if (show)
return;
MatchCollection info = reg.Matches(memo);
int l = info.Count;
//当收到的数据中没有完整数据包时,退出,继续等待新的数据
if (l == 0)
{
return;
}
BeginInvoke((ThreadStart)delegate
{
try
{
show = true;
String str = info[0].Value;
memo = memo.Replace(str, "");//将抓取的数据从缓存中移除
t1.Text += str + "\r\n";
t1.SelectionStart = t1.TextLength;
t1.ScrollToCaret();
str = str.Substring(59, 3);
l1.Text = str;
if (!Timers)
T.Dispose();
GC.Collect();
}
finally
{
show = false;
}
});
}
private void button1_Click(object sender,EventArgs e)
{
T = new System.Threading.Timer(tt,null,0,20);
}
public delegate DisPlay(string s)
DisPlay display;
private void Form1_Load(object sender, EventArgs e)
{
display = ShowText;
}
void ShowText(string str)
{
t1.Text += str + "\r\n";
t1.SelectionStart = t1.TextLength;
t1.ScrollToCaret();
str = str.Substring(59, 3);
l1.Text = str;
show = false;
}
private void tt(object state)
{
if (show)
return;
MatchCollection info = reg.Matches(memo);
int l = info.Count;
//当收到的数据中没有完整数据包时,退出,继续等待新的数据
if (l == 0)
{
return;
}
show = true;
String str = info[0].Value;
memo = memo.Replace(str, "");//将抓取的数据从缓存中移除
BeginInvoke(display, str);
if (!Timers)
T.Dispose();
//GC.Collect();
}
memo += readMsg;
//分析缓存数据中是否有完整数据包
MatchCollection info = reg.Matches(memo);
int l = info.Count;
//当收到的数据中没有完整数据包时,退出,继续等待新的数据
if(l == 0)
{
return;
}