现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

怎样使用多媒体定时器

2012-07-10 21:03 工业·编程 ⁄ 共 1807字 ⁄ 字号 暂无评论

  SetTimer定时的分辨率最小到50ms,在需要更小的定时间隔时他就无能为力了,多媒体定时器在精确定实时中很有用处,能够定时到一毫秒,不过得到这样的好处是要付出代价的,使用起来略嫌麻烦,下面1-6步就是使用方法,不对之处请指正。原来写时使用了使用了英文注释,比较简单就不改了。

1.Link winmm.lib
#i nclude <mmsystem.h>        

#pragma comment(lib, "winmm.lib")
2.Define variables
#define TARGET_RESOLUTION 1    // 1-millisecond target resolution
int wTimerID;                      // store timer ID
int msInterval;                      // delay
UINT wTimerRes;                    // end resolution  

3.Obtaining and setting timer resolution

//Obtaining timer resolution

TIMECAPS tc;
if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR)

{
     MessageBox("Obtaining timer resolution error");
     return;
}
wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);

  //setting timer resolution

timeBeginPeriod(wTimerRes);    

4.Starting a Single/Periodic Timer Event
wTimerID=timeSetEvent(
    msInterval,                // delay
    wTimerRes,                 // resolution
    MMTimerProc,               // callback function
    (DWORD)UserData,// User Data, it is sent to dwUser of the callback function //parameter
    TIME_PERIODIC              // TIME_PERIODIC or TIME_ONESHOT

    );              
5.Writing a Timer Callback Function
void CALLBACK MMTimerProc(UINT wTimerID, UINT msg,

    DWORD dwUser, DWORD dw1, DWORD dw2)

{

    //timer routine
}

6.Canceling a Timer Event
if(wTimerID)  // is timer event pending?
{            

     timeKillEvent(npSeq->wTimerID); // cancel the event
     wTimerID = 0;
}

7.Error Shoting

1.DWORD dwUserData = (DWORD)this; //UserData
//if it is used in global area will get the following error
error C2355: 'this' : can only be referenced inside non-static member functions
2. int msInterval;
msInterval = 1;
//if it is used in global area will get the following error
error C2501: 'msInterval' : missing storage-class or type specifiers
error C2374: 'msInterval' : redefinition; multiple initialization
8.Unserstanding Difficult Points
1. wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);

【上篇】
【下篇】

给我留言

留言无头像?