Instructables

Step 3: Exspearimintation

Picture of Exspearimintation
In this experiment, I sought to find out how long it took the digitalWrite() command to execute 1000 times, and then how long it took the “true c” style command to execute 1000 times. The code is fairly simple, and shown below:
 
void setup()
{
 Serial.begin(9600);
}
void loop()
{
 int initial = 0;
 int final = 0;
 initial = micros();
 for(int i = 0; i < 500; i++)
 {
    digitalWrite(13,HIGH);
    digitalWrite(13,LOW);
 }
 final = micros();
 Serial.print("Time for digitalWrite(): ");
 Serial.print(final-initial);
 Serial.println("");
 initial = micros();
 for(int i = 0; i < 500; i++)
 {
    PORTB |= _BV(PB5);
    PORTB &= ~_BV(PB5);
 
 }
 final = micros();
 Serial.print("Time for true c command: ");
 Serial.print(final-initial);
 while(1);
}
 
 
Feel free to try this out yourself. Here are the results I got:
(Seeeduino with ATMega168)
Time for digitalWrite(): 3804
Time for true c command: 348
 
So each style turned on the pin 500 times and turned it back off 500 times. digitalWrite() took 3804 microseconds, while the true c commands took just 348 microseconds. The true c commands are 10 times faster than the digitalWrite()!

Try out this experiment for yourself, all you need is an arduino and a computer.
 
Remove these adsRemove these ads by Signing Up
If you count down rather than up in the loop it will be even faster! On my Arduino Mega changing the loop to count down for the True C commands reduced the time taken from 288microseconds to 192 microseconds, big difference if you need it to be as fast as possible!
rcarvalho43 years ago
It's better change just the part after the logic operator:

PORTB |= 0b00100000;
PORTB &= ~0b00000000;

If you don't use the logic operators, but just the equal "=" sign, all the pins are going to be set like the byte you sent, not just pin B5. In the case where you set B5 high, you would set all ohter B pins to low.
n8hfi4 years ago
Part of the reason this works is that the DigitalWrite() and DigitalRead() do some error checking before it sets the register bit--in particular, it checks and turns off PWM if it's enabled for that pin.  Directly accessing the bit yourself is fine, but you're also assuming responsibility for skipping the check.

This is pretty safe if your sketch is simple and doesn't do much multitasking or multiplexing of pins, but can get perilous if you've got a complex one.
vilts4 years ago
 I wonder why I get this error:

In function void loop():
Error: 'PB5' was not declared in this scope.

I use 0018 software.


I used form PORTB = B.....;

and it took 3808 vs 284 microseconds.

I'm trying to get TLC5945 communicating with arduino, no luck with digitalWrites, hopefully this version works.