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)
Best Answer
In this case:
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: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:
which is equal to this:
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:
where
x
is the unchanged/previous value of the bit. Ifx
is 1, 1 OR 0 will remain 1 and ifx
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.