How often will this program toggle the digital pin

for(int i=0;i<10000;i++){
    PORTD |= 0x8;
    PORTD &= ~0x8;
  }

How fast will this code toggle the pin?

Depends on the clock speed of the processor

16mhz

You can't tell from the C code, you need to look at the machine code that's generated by the compiler.

16mHz is very slow, and 16MHz is the wrong answer too.

About 1.45MHz, with an 18% duty cycle on a Nano, according to my scope.

If you take out the loop count, about 2.63MHz, and the duty cycle goes to 33%.

And if you want the duty cycle to be 50%, toggle the pin instead of setting/resetting:

for(int i=0;i<10000;i++){
    PORTD ^= 0x8;  //This is Exclusive OR equals.
  }

It will also run one instruction cycle faster.

Thanks its working now. BTW I do not know how to look at the assembly code.

Something to consider... Approximately every millisecond the timer 0 interrupt service routine runs. The loop is suspended for that brief moment. There will be a "hiccup" in the output.

Something to consider... Approximately every millisecond the timer 0 interrupt service routine runs. The loop is suspended for that brief moment. There will be a "hiccup" in the output.

Or disable interrupts before calling the function and reenable them after it returns?

Lefty

asm(" ldi r16,8 \n\t out 0x0a,r16 \n\t .rept 10000 \n\t out 0x09,r16 \n\t .endr \n\t");

Should be 8MHz minus a bit for interrupts and loop overhead. Unfortunately I don’t have a scope or frequency meter to test it.

I’m quite impressed by the 2.63MHz just from plain C code.

Something i was playing with a few months ago http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1279055639/12