使用异步定时器编写一个数据采集的多线程程序.doc
实验七任务使用异步定时器编写一个数据采集的多线程程序,和普通定时器比较二者运行时的差异。实验步骤步骤1:设计程序界面,生成程序框架。根据实验要求,我们在面板上放置两个带状图控件,分别用于显示异步定时器和普通定时器的采样结果;放置一双态按钮来控制数据采集的开始和关闭。最终界面如图9-1所示,其主要控件的基本属性列表见表9-1。图9-1 最终用户界面表9-1 主要控件基本属性列表控件类型Constant Name 属性设置面板PanelPANEL命令按钮Command ButtonQUITBUTTONCallback FunctionQuitCallbackLable_Quit双态按钮Toggle ButtonTOGGLEBUTTONCallback FunctionDAQControlCBInitial StateoffLable数据定时器控件TimerTIMERCallback FunctionDataAquirTimerCBInterval (seconds)1.0带状图控件Strip ChartSTRIPCHARTLable普通定时器STRIPCHART_2Lable异步定时器步骤2:添加异步定时器。把异步定时器的仪器驱动程序添加到当前工程,在工程窗口选择EditAdd File To ProjectInstrument(*.fp),路径为CVItoolslibtoolboxasynctmr.fp。步骤3:获得异步定时器句柄,在main函数添加如下语句:static int AsyncTimerID;/*先声明句柄变量*/int main (int argc, char *argv)if (InitCVIRTE (0, argv, 0) = 0)return -1;/* out of memory */if (panelHandle = LoadPanel (0, "lesson9.uir", PANEL) < 0)return -1;DisplayPanel (panelHandle); /*获得异步定时器句柄*/AsyncTimerID=NewAsyncTimer (1.0, -1, 0, AsyncTimerCB, 0);RunUserInterface ();DiscardPanel (panelHandle);return 0;步骤4:声明异步定时器回调函数。在main函数之前声明。/*声明AsyncTimerCB*/int CVICALLBACK AsyncTimerCB (int reserved, int timerId, int event, void *callbackData, int eventData1, int eventData2);步骤5:编写回调函数。/*双态按钮回调函数DAQControlCB*/int CVICALLBACK DAQControlCB (int panel, int control, int event,void *callbackData, int eventData1, int eventData2)int i;switch (event)case EVENT_COMMIT:GetCtrlVal (panelHandle, PANEL_TOGGLEBUTTON, &i);SetCtrlAttribute (panelHandle, PANEL_TIMER, ATTR_ENABLED, i);SetAsyncTimerAttribute (AsyncTimerID, ASYNC_ATTR_ENABLED, i);break;return 0;/*普通定时器回调函数DataAquirTimerCB*/int CVICALLBACK DataAquirTimerCB (int panel, int control, int event,void *callbackData, int eventData1, int eventData2)double data;switch (event)case EVENT_TIMER_TICK:data=(double)rand ()/RAND_MAX*100.0;PlotStripChartPoint (panelHandle, PANEL_STRIPCHART_2, data);break;return 0;/*异步定时器回调函数AsyncTimerCB */int CVICALLBACK AsyncTimerCB (int reserved, int timerId, int event, void *callbackData, int eventData1, int eventData2)double data;switch (event)case EVENT_TIMER_TICK:data=(double)rand ()/RAND_MAX*100.0;PlotStripChartPoint (panelHandle, PANEL_STRIPCHART, data);break;return 0;步骤6:添加头文件#include "asynctmr.h" 。步骤7:保存并运行程序。