Electronic – Bitwise operation for UART, AVR

avrcmicrocontrolleruart

I'm trying to work on UART for AVR. After setting the baud rate registers UBRRnX, I'm trying to configure the UCSRnA register.
UCSR0A 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)

Best Answer

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.