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.
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.
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.
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.
Me, I'm trying to PWM on all the pins of an Arduino Duemilanove to dim some LEDs.
If anyone has problems, replace
" PORTB |= _BV(PB5);
PORTB &= ~_BV(PB5);"
with:
"PORTB = 0b00100000;
PORTB = 0b00000000;"
Which should toggle PB5 like the original code. PB5 shouldnt have to be declared, as winAVR should recognize it as a pin, but arduino 0018 may be doing something funky with that.