Assume the following while
loop runs at 1kHz. What is the proper way to run another piece of code inside this loop but with different frequency (i.e. say 500Hz) without multithreading.
while (1){ // running 1kHz (i.e. outer loop)
do stuff
if (){ // running 500Hz (i.e. inner loop)
do another stuff
}
}
Another question is assume the outer loop runs at the maximum speed of the CPU, is it possible to run the inner loop at a percentage of outer loop (i.e. 50% of outer loop).
CodePudding user response:
The easiest way is something like this:
int counter = 0;
while (1) {
// do stuff
if ( counter == 2) { // inner loop
counter = 0;
// do other stuff
}
}
Note that in a spin-loop like this there's no guarantee that the outer loop will run at 1kHz; it will run at a speed determined by the CPU speed and the amount of work that occurs within the loop. If you really need exactly 1kHz execution, you'll probably want to program a timer-interrupt instead. What is guaranteed is that the code inside the inner if()
block will be executed on every second iteration of the outer loop.
CodePudding user response:
Something like this should work
unsigned int counter = 0;
while (1) {
// do stuff
counter =1;
if ((counter%2) == 0) { // inner loop
// do other stuff
}
}