2

I have the following C code:

int count = 0; // relative time
int T1 = 20; // period 1 in ms
int T2 = 50; // period 2 in ms
int T3 = 80; // period 3 in ms
   while (1) {
      if (count%T1 == 0) function1();
      if (count%T2 == 0) function2();
      if (count%T3 == 0) function3();
      count++;
      if (count == T1*T2*T3) count = 0;
      delay(1); // wait for 1 ms
   }

I'd like to know the reason for which there is the integer division count%T1==0 instead of count==T1. Maybe it takes into account the fact that the period T1 may not be an integer?

Thank you in advance.

0

1 Answer 1

6

From the code you posted, it looks like that:

  • function1 will be called every 20ms
  • function2 will be called every 50ms
  • function3 will be called every 80ms
  • The counter resets at 80 seconds (20*50*80ms).

The keyword here is every.

Let's take function1 trigger as example.

If you write count == T1, function1 will only get executed once before a reset, when count is equal to 20.

If you want to run function1 every 20ms, you would expect it to execute at 20ms, 40ms, 60ms, and so on.

To translate this concept into code, you check if the counter is divisible by 20 via the modulo operator, hence the count % T1 expression.

Same concept applies to T2 and T3 checks.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @MatteoPasini can I use the condition count==T1 if I replace count=T1*T2*T3 with count=max(T1, T2, T3)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.