Ensure loop runs at fixed predefined frequency in C

108 Views Asked by At

I want to make a while(1) loop in C which must run at fixed 10,000Hz frequency irrespective of the time taken by executing statements written in the loop.

There can be 2 exit condition, based on runtime (let's say 1sec, then it should run for 10,000 times, the no. of iterations) and based on loop count (let's say 20,000 iterations, then ideally it should take 2sec time)

int loopCount = 0;
while (1) {
    // Some calculations
    // loopCount++; 
    // Check for exit
    // Delay based on frequency 
}

If I run all iterations (10,000) then it's taking more than 1 sec. If I run only for 1 sec, then it is existing before loop count hits 10,000.

Any solutions will help a lot.

Expectation solution on keeping track of time with multiple processes.

1

There are 1 best solutions below

0
On

For exact time measuring you need to have some timer running on your system that uses interrupt and execute outside your while loop.

For example if you have a tick timer running at 100uS that increment a counter named tick_counter, you can use it in your while loop in the following manner:

int loopCount = 0;
static int current_tick;
current_tick = tick_counter;
while (1) {
    // Some calculations
    // loopCount++; 
    // Check for exit
    // Delay based on frequency 
    if( (tick_counter - current_tick) > 10000)
    {
        current_tick = tick_counter; // save the current tick time for next check...
        // do your calculations here...
    }
}

The example above is "hard coded" for 1sec delay. You need to modify it to your needs.