RT LOOP - also for ArduinoSimple code for rt in a loop Do also handle wrap around on millis after 49.7 days We do use unsigned int math and wrap around No wrap problem - test in std C
// small test program
// use unsigned char instead of unsigned to reach wrap around with 256 steps
#include <stdio.h>
#include <math.h>
void main()
{
int c =0;
unsigned char x,x0,y,z; // char -> int in real life
x0 = x = 12;
y = 3;
z = x;
for (int i=0; i < 500; i++)
{
x0 = x;
x++;
c++;
if (x < x0) { // wrap
z+=y ;
x+=y ;
}
if (x-z >= y) {
z+=y;
printf("ping %i\n",c);
c = 0;
a }
printf(" x%i y %i z %i\n",x,y,z);
}
}
Arduino impl
unsigned long x,x0,y,z;
x0 = x;
y = 3;
z = x;
void setup()
{
x0 = x = z = millis();;
y = 12; // periode
}
void loop()
{
x0 = x;
x++;
if (x < x0) { // wrap
z+=y ;
x+=y ;
}
if (x-z >= y) {
z+=y;
// now its time for periodic code
}
}
No wrap problem solution presented here: millisrt.pdf Thanks to Nick Gammon for this idea |