I seem to be having a weird issue regarding cbi/sbi instructions on Atmega8-16AU.

I have it connected to an external 16Mhz crystal.

I am able to verify that it is running at 16Mhz by using _delay_ms(1000) and checking with a logic analyzer that indeed a delay of 1 second is produced during toggling of an output pin.

However when I call the following the assembly function:

    sbi PORTC,4
    cbi PORTC,4

I would expect PC4 to be HIGH for 2 clock cycles ((1/16M)*2) or 0.125us. However when I check using a logic analyzer, the pin is actually HIGH for 1.5us! That's almost 24 cycles.

enter image description here

I understand that some cycles would be used for jumping and returning to the function from the main routine but that should not affect the actual HIGH time of pin PC4.

Can someone explain whats going on here. I have a feeling that I'm missing something very basic here.

There are no interrupts running and my fuse settings are

LFuse : 0xFF
HFuse : 0xC9
  • \$\begingroup\$ Do you have any interrupts running? \$\endgroup\$ Mar 12, 2016 at 18:48
  • 1
    \$\begingroup\$ Do you define F_CPU anywhere? \$\endgroup\$ Mar 12, 2016 at 19:00
  • 1
    \$\begingroup\$ Trying this myself on an Arduino board (ATmega328P at 16MHz) I see the pulse lasts 0.125us, exactly what you expect. I suspect your processor is not running at 16MHz. \$\endgroup\$ Mar 12, 2016 at 19:16
  • 1
    \$\begingroup\$ That's right, I just thought that maybe the _delay_ms(1000) "worked" because the board was actually running at 1MHz and you didn't set F_CPU, which default to 1MHz. \$\endgroup\$ Mar 12, 2016 at 19:20
  • 1
    \$\begingroup\$ Do you have an oscilloscope with an analog input? Looks like you're using a logic analyzer. It would be interesting to see what the pin is actually doing. \$\endgroup\$ Mar 12, 2016 at 19:31

1 Answer 1


After a bit of troubleshooting I found the answer.

I was seeing quite sporadic behavior with regards to timing. Sometimes i would get the correct timing of 62.5ns and sometimes not.

After eliminating all the possibilities, It had to be the crystal.

Replacing the crystal solved the issue. All the timings are now correct

  • 1
    \$\begingroup\$ How did your delay test fail to identify the problem? \$\endgroup\$ Mar 13, 2016 at 18:32
  • \$\begingroup\$ The best I could figure out was that the delay behavior was also sporadic and I happened to test it on one of the runs where it worked. \$\endgroup\$
    – Ankit
    Mar 13, 2016 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.