we use Arduino IDE as testing

About Time

We need mechanisms to maintain execution of code with a given fixed samplings time

Example 1 - notZoGood

 // Sampling frequency is 20 Hz aka 50 milli seconds

const int samplingTime = 50;
const int codeTime = 12;

void criticalcode()
{
    delay(codeTime); // delay to mimic that code takes time}
}

void setup()
{
}

void loop()
{
    while (1) {
      criticalcode();
      delay(samplingTime);
    }
}
  1. Is there a problem (yes)

  2. If yes then what is the problem

  3. What is the real time for doing one loop

  4. and what is the real sampling frequemcy based on that

    1. hint 16.129 Hz

  5. How to test it

Example 2 - nearly ok


const int samplingTime = 50;
const int codeTime = 12;

unsigned long ourTime;

void criticalcode()
{
  Serial.println(millis());
  delay(codeTime); // delay to mimic that code takes time
}

void setup()
{

  Serial.begin(115200);
  delay(10);
  ourTime = millis();
}


void loop()
{

  criticalcode();
  ourTime += samplingTime;
  delay(ourTime - millis());
}
  1. Is there a problem

    1. small drifting ?

  2. What is the upper limit of codeTime

  3. Will it work with codeTime negative(hint testing)

Example 3

We do have two independent systems Can we just wait Nope - switch to pulling strategy


const int samplingTime1 = 50;
const int codeTime1 = 12;

const int samplingTime2 = 120;
const int codeTime2 = 48;

unsigned long ourTime1, ourTime2;

void criticalCode1()
{
  Serial.print("1 - ");
  Serial.println(millis());
  delay(codeTime1); // delay to mimic that code takes time
}

void criticalCode2()
{
  Serial.print("2 - ");
  Serial.println(millis());
  delay(codeTime2); // delay to mimic that code takes time
}

void setup()
{

  Serial.begin(115200);
  delay(10);
  ourTime1 =  millis();
  ourTime2 = ourTime1;
}


void loop()
{
  if (ourTime1 <= millis()) {
    criticalCode1();
    ourTime1 += samplingTime1;
  }

  if (ourTime2 <= millis()) {
    criticalCode2();
    ourTime2 += samplingTime2;
  }
}

My preferred

Den her anbefales

unsigned long tNext;
unsigned long tPer = 50;

void setup()
{

  ....
  // and last
  tNext = millis() + tPer;
}

void loop()
{
   if (tNext <= millis() {
   {
      tNext +=tPer;
      // din kode til tidskritisk afviklin
   }
}

I ikke Arduino env

int main ()
{
   tNext = millis() + tPer; // hedder nok noget anden end millis
   while (1)
   {
     if (tNext <= millis() {
     {
       tNext +=tPer;
       // din kode til tidskritisk afvikling
     }
   }
}





To be aware of

  • Can you always be sure of exection time of your code (test)

  • What is the problem ?

  • What is the maximum delay on exetion of codes 1 and 2 (criticalCode1, criticalCode2)

  • Is it possible to prioritize execution ?

  • Is it solveable ?

  • make a drawing

Try to invert order of ifs in loop and see what happens