Timing question: if before a digitalWrite?

Hi
In a loop, I have to set a digital output.

I can make a simple digitalWrite at any occurrence, even if the pin has already set to High previously.

My question: is it better/faster to test if the pin is already set before making my digitalWrite? Or another alternative would be to use a boolean variable, which may be faster to test than reading the pin status. But maybe even testing a boolean is slower than writing to the pin even if it is already setup.

I'm not sure my question is understandable...
Thanks in advance for your help :slight_smile:

I think digitalRead() is probably slow enough that it's not worth it, even though digitalWrite() is also kinda slow.

If speed is an issue, use direct port manipulation (note that in this case, it's definitely not worth the test). It is much faster - digitalRead/Write needs to convert the pin number to a port register and bit.

Hey, thank you for the very fast answers!

And with the second alternative, which would be to declare a boolean that would mirror the status of the pin. So, I would have to test this boolean for writing to the pin only when it has to be done.
Is a test on a boolean faster than a digitalWrite?

It not that I'm very speed oriented; more because I start on Arduino and I try not to take nasty habits...

The only reason to test the setting of an I/O pin before doing digitalWrite() would be if you did not want to do the write() in some circumstance.

If you intend to make the pin HIGH or LOW regardless of its current state there is no advantage wasting CPU cycles to check it first.

Setting a HIGH pin to HIGH (i.e. no change) is probably much faster than than checking it and then not doing the digitalWrite(). Hope that makes sense.

...R

Great!
Thank you very much for all info.
All the best!