I am working with a micro-controller that has an interrupt that counts every 1ms since start.
I have a variable which can be between 0 and 999 and I want to toggle another value if the time elapsed is less than x
milliseconds (in following example it is 500ms). So between time 0 and 500 I want shouldActivate
to be TRUE, and between 500 and 1000 it should be false, then between 1000 and 1500 it should be true and so on.
int activeTime = 500; // 500ms active
int shouldActivate = 0;
int elapsed = 0; //how many ticks we had so far
// This function gets automatically called every 1ms
void tick() {
if(elapsed < activeTime) {
elapsed++;
shouldActivate = 1;
} else {
shouldActivate = 0;
elapsed--;
}
}
The above code works when I just start, while elapsed goes over 500, I get problems as it just does the decrement operation only once.
What conditions should I put into my function to achive the desired result?