Tuesday, August 04, 2009

Generating sine wave using multimedia timer

In case we need a high resolution timer for our Windows based application, we can use multimedia timer. For an explanation of what multimedia timer is, you can refer to multimedia timer documentation from msdn.

I will give an example of using this multimedia timer for generating sine wave.
First you need to add these two lines in your source code:

#pragma comment(lib, "winmm.lib")

then after that you can declare an instance of multimedia timer:


In order to make this timer work, you need to define a callback function to handle the timer interrupt, something like this:

void CALLBACK SineGenProc(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
deg = ((2*M_PI)/10) * (counter2);
y = 0.1f + 0.05f * sin(deg);

outputVolt = y;
offsetVolt = 0.0;

writeAnalog(anOutChannel, offsetVolt, outputVolt);

you need to define the variables as global so that the callback can access it and don't forget to include math library for this program.

after defining and declaring the callback function, the next step is to start the timer. It can be done simply by these lines of code:

UINT uDelay = 1;
UINT uResolution = 1;
DWORD dwUser = NULL;
UINT fuEvent = TIME_PERIODIC; //You also choose TIME_ONESHOT;

SineTimer = timeSetEvent(uDelay, uResolution, SineGenProc, dwUser, fuEvent);

//give an error message here because we fail in making the timer

We can turn the timer off by adding these lines of code:


that's it, I tried this and checked the output using oscilloscope and it works.. :)


Post a Comment

<< Home