Search code examples
carduinobitwise-operatorsarduino-unousart

How does this simple line of C code work?


I need 9 bit UART data on an Arduino Uno and so I have to do some manual setup of the Arduino UART. Basically, I don't understand this line of example code (from the datasheet), it is meant to enable a UART Tx and Rx pin on the Arduino, which done in simple and easy to understand machine language just means loading an immediate value to UCSR0B (USART Control and Status Register B) in a way that the RXE (Recieve Enable) bit, and TXE (Transmission Enable) bit are both high. In other words, load 00011000 into USCR0B.

Here's the example C code from the datasheet:

USCR0B = (1 << RXE) | (1 << TXE);

Solution

  • RXE and TXE are the bit indices, so (1<<RXE) | (1<<TXE) is a mask, where the TXE and RXE bits are both equal to 1 (and all other bits are 0).

    E.g. I don't happen to know the actual values of RXE and TXE, but suppose TXE is bit 3 and RXE is bit 4, then the relevant header file definitions might look something like this:

    #define TXE 3  // TX Enable = bit 3
    #define RXE 4  // RX Enable = bit 4
    

    and the mask calculation will work like this:

                1<<TXE  = 00001000 = 0x08
                1<<RXE  = 00010000 = 0x10
    (1<<RXE) | (1<<TXE) = 00011000 - 0x18