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 - nearly okconst 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(); ourTime2 = ourTime1; } void loop() { if (ourTime1 <= millis()) { criticalCode1(); ourTime1 += samplingTime1; } if (ourTime2 <= millis()) { criticalCode2(); ourTime2 += samplingTime2; } } My preferredDen 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
Try to invert order of ifs in loop and see what happens |