real time computing

Hi,

why this is not working ]:slight_smile:

I am simply trying to extent the cycle time to a fixed value to create some kind of real time environment.

Here the code:

unsigned long previousMicros = 0;
int cycletime, idletime, c;

void setup() {

Serial.begin(115200);

}

void loop() {
// Get cycletime
unsigned long currentMicros = micros();
cycletime = ((unsigned long)(currentMicros - previousMicros));
previousMicros = currentMicros;
Serial.println(cycletime);

//Calculate idletime (requested cycletime - 1000 micro seconds)

idletime = (1000 - cycletime);
Serial.println(idletime);

delayMicroseconds (idletime);

}

cycletime = ((unsigned long)(currentMicros - previousMicros));

As cycletime is an int the result of the RHS of = is trunicated and becomes an int.

Mark

jakobjua:

Serial.begin(115200);

Serial.println(cycletime);

Serial.println(idletime);

Also, Serial.println() will eventually block, if you feed data too fast.

I think printing two 4-char numbers with linefeeds and start/stop bits and all that, at 115200bps, is running in the 870 microsecs range. That could be a source of timing skew.

Thanks mark, thanks gardner,

if i comment out the last line

delayMicroseconds (idletime);

i get good values, like below
848
152
852
148
848
152
852
148
848
152
852
148
848
152
852
148
848
152
852

cycletime is 852?s
idletime required 148?s

but as soon that i do the delay, everything gets messed up:

8040
-7040
9964
-8964
8032
-7032
9964
-8964
8032
-7032
9972
-8972
8020
-7020
9980
-8980
8012

jakobjua:

  idletime = (1000 - cycletime);

Serial.println(idletime);
 
delayMicroseconds (idletime);

If cycletime ever exceeds 1,000, then the idletime calculation gives you a negative idle time, which delayMicroseconds(unsigned int) treats as a large positive value. This yeilds actual cycle times in the 65,000 range. But because you're doing a long calculation and discarding the high bits, you are printing the actual cycle times MODULO 65536. These are the +/- 8,000 figures.

Make idletime and cycletime long integers and do this, and see if it helps:

  idletime = (1000L - cycletime);
  Serial.println(idletime);
  
  if (idletime > 0L)
     delayMicroseconds(idletime);