Hey say I have a counter that increments ONE every second but there will be unavoidable processes that slows how the processor a bit so the timing will be off. So I need the counter to increment in the next step by TWO (as an example, it depends on how long the lag) and then back to ONE when processes are back to normal. How would I go about it?
say a simple counter like this
unsigned long lastMillis = 0;
int counter = 0;
void loop() {
unsigned long currentMillis = millis();
if(currentMillis > lastMillis+1000) {
counter += 1;
lastMillis = millis();
}
}
This reminds me of a bit of lag math in network games where you have to predict where the play will be in X amount of seconds base on vector and compensate base on the lag.
If you're basing your timing off millis(), simply use rounding directly on the millis() value, and you'll always be within the rounding errror. For example:
Your current code will also have a large rounding error, as you're discarding the error every time you update counter. If the idea is to maintain a fixed time-base relative to the initial starting time, you want to do this:
unsigned long currentMillis = millis();
if(currentMillis > lastMillis+1000) {
counter += 1; // this might be a more complex operation taking > 1ms...
lastMillis = millis(); // now you've slipped forward in time...
}
Isn't the way to code a regular event with no slippage
#define DELAY 1000 // one value, one place, avoids code-rot when code gets changed in future
if (millis () > lastMillis+DELAY) { // no need for a currentMillis variable.
counter += 1;
lastMillis += DELAY ;
}
You step lastMillis a fixed amount everytime, then you are following a regular
interval, however long you are delayed, since the loop will simply trigger
multiple times until you've caught up. Sometimes this isn't whats wanted,
but
there will be unavoidable processes that slows how the processor a bit
Whilst I doubt that it actually slows down the processor I know what you mean. What sort of processes are these that take longer than a second ? Can they be eliminated, speeded up or written using non blocking code ?
RayLivingston:
Your current code will also have a large rounding error, as you're discarding the error every time you update counter. If the idea is to maintain a fixed time-base relative to the initial starting time, you want to do this:
UKHeliBob:
Whilst I doubt that it actually slows down the processor I know what you mean. What sort of processes are these that take longer than a second ? Can they be eliminated, speeded up or written using non blocking code ?
It's only sometimes. It's a web server where the client requests xml data from the arduino. It freezes the process for a fraction of a second not seconds.
RayLivingston:
Your current code will also have a large rounding error, as you're discarding the error every time you update counter. If the idea is to maintain a fixed time-base relative to the initial starting time, you want to do this: