GCC AVR bit toggle

Do you have a question? Post it now! No Registration Necessary

Translate This Thread From English to

Threaded View
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?


Re: GCC AVR bit toggle
Quoted text here. Click to load it

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).

Quoted text here. Click to load it

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.



Quoted text here. Click to load it

Re: GCC AVR bit toggle
eeh schrieb:
Quoted text here. Click to load it

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

Site Timeline