I want to use loop() iterations counter to execute some tasks periodically or tasks like debouncing. My other sketch is running every loop() at least 20 ms, and if i am using 5 ms time to wait to debounce a button, it will still be at least 20 ms waiting, also cpu will have to compare two not zero values, which is a bit slower. I think it is more difficult for cpu than just incrementing and decrementing one variable and comparing it to 0. So i came up with pattern like that:
boolean onOff=1; // arduino led state. My task here is LED blinking.
byte loopCounter=2; // number of iterations made by loop(). Set as little variable as possible to save ram and cpu time.
//Code will be executed every "loopCounter" iteration of loop().
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
if (--loopCounter == 0) { //comparing with 0 should be a bit faster and easier for Arduino to process. Correct me if i am wrong.
loopCounter=2; // That digit sets how often your code will be executed. Every 2(3,4... set your own value) iterations of loop().
digitalWrite(13, onOff= !onOff); // the task itself.
}
}
It may be more convenient in some ways than millis() and micros() patterns. Also i do want want to use hardware timers for timing. It may be convenient in cases, when you don't care when exactly task will be done, you just want it to be done ASAP (as soon as possible), but not during that particular iteration of loop(). Basicly you can use it as a timer if you know how it takes one iteration to be done. So, if your sketch runs 1 iteration of loop() for 1 ms, and you need some action to be done every 1 sec, 1ms*1000 == 1 sec. So you need it to be done every 1000 iterations.
- So, is that really can save some ram and cpu time?
- Is comparing with zero is faster for arduino than comparing with not zero?
- Are millis() and micros() timing patterns using more operations (setting value to variable, computing the difference between 2 values and than comparing it to a period you have set) instead of decrementing and comparing to zero with my pattern?
Any side-effects of using my pattern? I can only think of very unaccurate timing and delays more than you think if your sketch done smth more than usual, because of button push for example or some sensor changed value.
Thank you!
digitalWrite
will be the slow thing there, not comparing to zero, or comparing two numbers. Try looking up the digitalWriteFast library.millis()
is one of the fastest function of the Arduino core. It just returns a copy of a global variable (timer0_millis
) which is updated by a timer interrupt. The copy is performed with interrupts disabled in order to avoid a race condition. See the implementation.I know about digitalWrite, thank you. But readability is more important
- what's unreadable about:digitalWriteFast (13, onOff= !onOff);
?