# Difference in DigitalWrite Measurements

I am working a project requires precision control of a square wave. As part of the project I am
characterizing the execution time of the digitalWrite command. To start with I implemented the following code in the loop and measured the pulse widths with an oscilloscope.

digitalWrite (52,HIGH);
digitalWrite (52,LOW);

The resulting measurements were W+: 3.898 microseconds
W-: 4.045 microseconds

I figured pulse widths are the same with about 0.147 microseconds to execute the loop. Now when I reverse the calls and start with the low portion of the wave the pulse widths change.

digitalWrite (52,LOW);
digitalWrite (52,HIGH);

The resulting measurements were W+: 4.161 microseconds
W-: 3.780 microseconds

Assuming the widths are the same the loop takes 0.381 microseconds to execute.

I am trying to figure out why the order of HIGH-LOW or LOW-HIGH is making such a significant difference in the time it takes to execute the code

Why don't you simply examine the generated code?

If you want full control over the process and much faster execution, use direct port manipulation rather than calls to Arduino routines. The C/C++ code often translates as one line to one machine code instruction.

Direct port manipulation is the path I will go down in the future. Just trying to figure out (for my own knowledge) why the order of toggling (HIGH-LOW or LOW-HIGH) effects the execution time of the digitalWrite function calls.

Show the whole code you used to test it? I bet you're measuring more than you think you are.

jmol:
Direct port manipulation is the path I will go down in the future. Just trying to figure out (for my own knowledge) why the order of toggling (HIGH-LOW or LOW-HIGH) effects the execution time of the digitalWrite function calls.

That's a question you can ask the compiler. Ask it by looking at the generated assembler code. Many factors affect
the precise details of generated code, such as what optimize options have been selected when running
the compiler, and what other variables are competing for use of machine registers, and what machine
instructions are available.