With this simple code:
void setup() {
pinMode(12, OUTPUT);
}
void loop() {
digitalWrite(12, LOW);
digitalWrite(12,HIGH);
}
I monitored pin D12 with my oscilloscope and found that it takes 5uS for each level. Thus the code gives 100kHz square wave as shown in the figure below. Note that oscilloscope setting was 5 uS/DIV.
Now I modified the above code such that it directly writes to PORTB (pin D12 is mapped to bit B4 of PORTB). This avoids using digitalWrite() function. The modified version of the code is shown below:
void setup() {
pinMode(12, OUTPUT);
}
void loop() {
PORTB = B00000000;
PORTB = B00010000;
}
Result: (0.5 uS/DIV)
The frequency of the waveform is around 1.11 MHz which is about 10 times faster than using digitalWrite(). However the waveform does not look symmetry. Duration of the HIGH is around 0.8uS while that of the LOW is around 0.1uS.
I then swap the 2 line of code:
From
PORTB = B00000000;
PORTB = B00010000;
to
PORTB = B00010000;
PORTB = B00000000;
The result was: (again 0.5uS/DIV)
Obviously, the duration of the HIGH and the LOW are swapped. I think the reason is the Arduino loop takes around 0.7uS.
Conclusions:
- Write directly to port is much faster than using digitalWrite().
- Arduino loop() takes about 0.7 uS to execute.