In this simple example, the LED flashes on for 100ms every second. Given are two approaches:
Example 1
digitalWrite applies HIGH and LOW repeatedly, even when not needed. This is simple code.
unsigned long startMS = 0;
void setup()
{
pinMode (13, OUTPUT);
}
void loop()
{
unsigned long diffMS = millis() - startMS;
if (diffMS > 1000) startMS = millis();
// Is it good practice to digitialWrite every iteration?
if (diffMS < 100) digitalWrite (13, HIGH);
else digitalWrite (13, LOW);
}
Example 2
Flags are set to manage only when the LED needs to change state. This introduces additional logic and code.
unsigned long startMS = 0;
boolean curSetting = false;
boolean lastSetting = false;
void setup()
{
pinMode (13, OUTPUT);
}
void loop()
{
unsigned long diffMS = millis() - startMS;
if (diffMS > 1000) startMS = millis();
// Is this better than digitalWrite every iteration?
if (diffMS < 100) curSetting = true;
else curSetting = false;
if (curSetting != lastSetting) {
digitalWrite (13, curSetting);
lastSetting = curSetting; }
}
The first one uses less memory (SRAM) which is always a good thing.
The second one uses less CPU which is always a good thing.
If your application is lean enough that you don't care about memory or CPU time, pick the one you can understand a year from now. In my case, that would be the first one.
There is a 24-byte difference between the two, a rather small difference.
How many clock cycles does it take for a digitialWrite? My guess is that the logic comparison between cursetting and lastsetting in example 2 equals the CPU usage. If I'm correct then example 1 wins on CPU and memory.
Even better practice is to not idle wait (or ISR wait) but to sleep the processor while doing nothing thus decreasing power consuption. Of course for the Arduino it does not matter to much but once you run it on batteries you will notice the difference immediately.
There is a 24-byte difference between the two, a rather small difference.
24? How did you arrive at that number?
How many clock cycles does it take for a digitialWrite?
digitalWrite, relative to a boolean comparison and assignment, is expensive. For the vast majority of applications, the difference is not important because other things (like floating-point math) are much more significant.
My guess
Why would you guess? You have full access to the source code.
The last part of what I wrote is by far the most important. Pick the one that is easy to understand in the future.