GCC AVR bit toggle

Oct 31, 2005 2 Replies

I want to ask if I want to toggle an IO bit such as bit 5 of Port A. Which one of the following is correct?



DDRA|=BV(5); PORTA^=BV(5);



or



unsigned char uc; DDRA&=~BV(5); uc=PINA&BV(5); DDRA|=BV(5); PORTA=uc^BV(5);



If the second one is correct, could I find do it faster (use fewer instructions) to replace them?



This sets the pin to "output". Normally this is done once at the start of the program (unless the pin is used for input and output).

This tells the pin to invert its output state.

Normally you know (or should know!) the current state of a pin's output. Thus "toggling" means driving high "PORTA |= BV(5);" or driving low "PORTA &= ~BV(5);". It is very rare to want to invert the current output state like this.

eeh schrieb:

If you have one of the latest ATmegas (48, 88) you can toggle pins with one instruction: PINA = BV(5);

Join the Discussion

Have something to add? Share your thoughts — no account required.

Didn't find your answer?

Ask the community — no account required