我目前正在使用Visual Studio 2010 c#中的SerialPort库读取定制PCB上的数据。从串行端口I/O读取定时器c#Visual Studios 2010
我目前正在试图通过按钮单击从设备读取给定数据的某些类型的数据,并在超时之前等待5秒钟,如果没有来自设备的响应。
但是,由于某些原因,定时器正在出现故障,并经常在5秒钟之前过期,从而停止存储有效数据。下面是我的代码使用,有人可以指出我的缺陷?我怀疑从我使用的System.Windows.Forms.Timer事件计时器功能是不正确的。
按钮单击
bool flag = false;
private void btnGetData_Click(object sender, EventArgs e)
{
string command = "*data#";//make string command to send
sendCommand(command);
flag = true;
gui.Timer.Interval = timerlength;
gui.Timer.Enabled = true;
gui.Timer.Tick += new EventHandler(Timer_Tick);
}
计时器事件处理程序
private void readVarsTimer_Tick(object sender, EventArgs e)
{
if (flag == true)
{
flag = false;//set flag low
print("Data Timer Expired, Run Command Again.");
gui.Timer.Stop();//stop timer
gui.Timer.Enabled = false; //event over
timerlength = 5000;//reset timer
}
}
串口读取数据,请假设设置串行端口是正确的,因为任何传输或接收数据不使用定时器工作得很好。
if (flag == true)
{
//code to read data in, and parse to display in text boxes correct
flag = false;
}
其他重要事项:
我有三种类型的数据我可以从设备期望的,所以我使用if /通过相应的按钮设置标志别人的。因此,“旗”变量的全局声明。
我还没有检测到串行端口获取垃圾数据可能导致我关闭的问题,我已经运行并分析了足够的数据以知道我得到了正确的预期数据。
这个计时器在设备关闭时也是完美无暇的,并且会持续五秒钟然后过期。
感谢您提供的信息汉斯,我会根据您的建议对正确的代码进行测试,看看它明天会如何发展,并将结果返回。 :) – PhoenixLament 2013-04-28 17:44:09
它的工作,谢谢! – PhoenixLament 2013-04-30 03:29:04