|
we use Arduino IDE as testing About TimeWe 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);
}
}
Example 2 - 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());
}
Example 3We 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();
ourTime1 = (ourTime1/10) * 10; // to get zero as last digit
ourTime2 = ourTime1;
}
void loop()
{
if (ourTime1 <= millis()) {
criticalCode1();
ourTime1 += samplingTime1;
}
if (ourTime2 <= millis()) {
criticalCode2();
ourTime2 += samplingTime2;
}
}
Double example
const int samplingTime1 = 50;
const int codeTime1 = 12;
const int samplingTime2 = 150;
const int codeTime2 = 48;
unsigned long ourTime1, ourTime2;
int run1 = 0, run2 = 0;
void criticalCode1()
{
Serial.print("1 - ");
run1++;
Serial.print(ourTime1);
Serial.print(" ");
Serial.println(millis());
delay(codeTime1); // delay to mimic that code takes time
}
void criticalCode2()
{
Serial.print("2 - ");
run2++;
Serial.print(ourTime2);
Serial.print(" ");
Serial.println(millis());
delay(codeTime2); // delay to mimic that code takes time
}
void setup()
{
Serial.begin(115200);
delay(10);
ourTime1 = millis();
ourTime1 = (ourTime1 / 10) * 10; // to get zero as last digit
ourTime2 = ourTime1;
}
void loop()
{
if (ourTime1 <= millis()) {
criticalCode1();
ourTime1 += samplingTime1;
}
if (ourTime2 <= millis()) {
criticalCode2();
ourTime2 += samplingTime2;
}
}
Try to invert order of ifs in loop and see what happens |