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.

It depends on the timing needs. We're talking about microseconds here. Sometimes microseconds matter, many times they don't.

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...

plubarj:
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...

It's not necessarily a nasty habit to waste a few cycles. When you've got something that can do 16 million things a second, doing a few extra unnecessary things now and then isn't really that much of a waste and there are trade-offs for that savings.

Yes, the test for the boolean would be faster but you're trading code space. The direct port write would be even faster than the boolean test but then you're trading readability.

Personally, if I didn't have something timing critical to worry about, I'd just leave the digitalWrite there. Usually I'm more concerned with saving code space than cycles.

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!