# Bitwise operation for UART, AVR

I'm trying to work on UART for AVR. After setting the baud rate registers UBRRnX, I'm trying to configure the UCSRnA register.

I'm trying to set the 2nd bit, U2XO. Which is the right way to do it? UCSR0A = (1 << U2X0)

or

UCSR0A = UCSR0A | (1 << U2X0) (Notice the OR operator in the 2nd statement)

In this case:

UCSR0A = (1 << U2X0);


1<<U2XO = 00000010, 1 is shifted to left to U2XO position so when you give this value to UCSR0A the register's content will be:

UCSR0A = 00000010


This operation will set all bits to 0 but the U2X0, for example if RXC0 would have been set to 1, then this operation would clear it to 0. If you are not aware of this that could cause some headache later.

In this one:

UCSR0A = UCSR0A | (1 << U2X0);


which is equal to this:

UCSR0A |= (1<<U2X0);


Here you set only the second bit to one and leave the rest unchanged which is preferable, because you won't change something accidentally. The content will be:

// UCSRA0 = xxxxxxxx               before operation something is in the register
UCSR0A = UCSR0A | (1 << U2X0);     // OR current with 00000010
// UCSRA0 = xxxxxx1x               something OR 1 will be 1


where x is the unchanged/previous value of the bit. If x is 1, 1 OR 0 will remain 1 and if x is 0, 0 OR 0 will remain 0.

So I suggest the second way, because that way it is easier to track which bit is set and which not and you won't change previously applied configuration by mistake.

• Thanks! Now I get it. I didn't know the 1st case would clear all the other bits in the register. – am3 Aug 3 '15 at 19:47
• Yes, it would because you just make it equal to that value which has only one bit set, the second (U2X0). – Bence Kaulics Aug 3 '15 at 19:52
• Note that while this is true in general, there are some exceptions. Interrupt flags, for instance, will clear when they are set to 1, so performing a bitwise OR is some cases can clear other flags if a read-modify-write instead of a bit set is emitted by the compiler. They must be cleared by strict assignment to the register if not being handled by a ISR. – Ignacio Vazquez-Abrams Aug 4 '15 at 0:58
• @Ignacio Thanks for the important addition, I will clarify my answer.And register description is always a mandatory reading before modifying any bits in the register, so these details will be revealed. – Bence Kaulics Aug 4 '15 at 7:18