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);
}
}
Can we live we this. In general no, because sampling period is used in digitizing algorithms in the analog world. Like a PID controller Example 2 - ok
// JDN
// NB time variables must be unsigned type due to wrap around !!!
const unsigned long TS = 10; // 10 msec tick
unsigned long tLast;
#define getMillis millis
void setup() {
// ...
tLast = getMillis();
}
my5msecCode()
{
delay(5); // just to simulate
}
void loop() {
if (TS <= (getMillis() - tLast)) {
my5msecCode();
tLast += TS;
}
}
Example 3We do have two independent systems
// JDN
// NB time variables must be unsigned type due to wrap around !!!
const unsigned long tPer1 = 50, tPer2 = 120; // peridos
unsigned long nextTime1, nextTime2;
#define getMillis millis
void criticalCode1() {
Serial.print("1 - ");
Serial.println(millis());
}
void criticalCode2() {
Serial.print("2 - ");
Serial.println(millis());
}
void setup() {
Serial.begin(115200);
delay(10);
nextTime1 = nextTime2 = getMillis();
}
unsigned long tt;
void loop() {
tt = getMillis();
if (nextTime1 <= tt + tPer1) {
criticalCode1();
nextTime1 += tPer1;
}
if (nextTime2 <= tt + tPer2) {
criticalCode2();
nextTime2 += tPer2;
}
}
Example 4 - testing loop time
// JDN
// NB time variables must be unsigned type due to wrap around !!!
const unsigned long TS = 15; // 15 msec tick
unsigned long tLast;
#define getMillis millis
#define TESTPIN 13
void setup() {
// ...
pinMode(TESTPIN,OUTPUT);
tLast = getMillis();
}
my5msecCode()
{
delay(5); // just to simulate
}
void loop() {
if (TS <= (getMillis() - tLast)) {
digitalWrite(TESTPIN,HIGH);
my5msecCode();
tLast += TS;
digitalWrite(TESTPIN,LOW);
}
}
Use an oscilloscope or logic analyser to observe and measure on the square wave on TESTPIN.
To be aware of
Try to invert order of if in loop and see what happens |