Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Last updated: Friday 13 November 2026 @ 17:29:40

USART — serial communication with AVR C

Programming for Engineers

USART and UART

In this practical, replace Arduino's Serial interface with direct access to the ATmega328P USART registers. Configure asynchronous serial communication, transmit text, observe it in PuTTY, then investigate communication between two microcontrollers.

ATmega328PUARTUSARTRegisters9600 baudAVR-GCC
Practical Checklist
Chapter checklist 0 / 10 completed

1. From Arduino Serial to the USART

Arduino makes serial communication appear straightforward because the core configures the peripheral for you.

const char message[] = "Hello world!\n";

void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.print(message);
    delay(1000);
}

The Arduino core sets the baud-rate registers, enables the transmitter, selects the frame format, and writes bytes to the USART Data Register (UDR0) when the hardware can accept them.

Our embedded C implementation will configure those registers explicitly, without depending on the Arduino Serial API.

2. How asynchronous serial communication works

For 8N1, each transmitted character uses one start bit, eight data bits and one stop bit. The idle line is high; a low start bit announces a new character. Data is normally transmitted least-significant bit first.

Part of the frameNumber of bitsPurpose
Start1Signals the beginning of a frame (logic low)
Data8The character’s byte value
Parity0Disabled in 8N1
Stop1Signals the end of the frame (logic high)

3. Configure the USART registers

3.1 UBRR0H and UBRR0L — baud rate

The baud-rate setting is a 12-bit value held in the USART Baud Rate Registers (UBRR0H and UBRR0L). In asynchronous normal-speed mode (U2X0 = 0), the relationship is:

$$ \mathrm{BAUD} = \frac{f_{\mathrm{CPU}}}{16(\mathrm{UBRR0}+1)} $$

Rearranging:

$$ \mathrm{UBRR0} = \frac{f_{\mathrm{CPU}}}{16,\mathrm{BAUD}} - 1 $$

At 16 MHz and 9600 baud:

$$ 103.17 \approx \frac{16,000,000}{16 \times 9600} - 1 $$

Choose UBRR0 = 103 (hexadecimal 0x0067). The resulting nominal baud rate is approximately 9615.4 baud, an error of about +0.16%.

#define F_CPU 16000000UL
#define USART_BAUDRATE 9600UL
#define BAUD_PRESCALER ((F_CPU / (16UL * USART_BAUDRATE)) - 1UL)

UBRR0H = (uint8_t)(BAUD_PRESCALER >> 8);
UBRR0L = (uint8_t)BAUD_PRESCALER;

3.2 UCSR0A — status flags

BitNameInterpretation
UDRE0Data Register EmptyHardware is ready to accept another byte in UDR0
TXC0Transmit CompleteA frame has completed transmission and no pending data remains
RXC0Receive CompleteUnread receive data is available
U2X0Double USART Transmission SpeedSelects 8× rather than 16× oversampling in asynchronous mode

To wait until the transmit data register can accept the next byte:

while (!(UCSR0A & (1 << UDRE0))) {
    // Wait until UDR0 can accept another byte.
}

3.3 UCSR0B — enable TX and RX

Enable the transmitter and receiver by setting TXEN0 and RXEN0:

UCSR0B = (1 << RXEN0) | (1 << TXEN0);

3.4 UCSR0C — frame format

For 8N1, select eight data bits (UCSZ01 = 1, UCSZ00 = 1), asynchronous mode, no parity, and one stop bit:

UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);

The other format-selection bits are cleared by this assignment. UCSZ02 in UCSR0B also remains clear because the configuration above sets only RXEN0 and TXEN0.

3.5 UDR0 — transmit and receive data

Writing to UDR0 queues one byte for transmission. Reading from UDR0 retrieves a received byte, once RXC0 indicates data is available.

while (!(UCSR0A & (1 << UDRE0))) {
}
UDR0 = 'A';
while (!(UCSR0A & (1 << RXC0))) {
}
uint8_t received = UDR0;

4. Create uart.c

  1. Return to the embeddedC directory from the Blink practical, and create a project for UART:

    mkdir -p ~/embeddedC/uart
    cd ~/embeddedC/uart
    touch uart.c
  2. Enter the following programme into uart.c:

    #define F_CPU 16000000UL
    
    #include <avr/io.h>
    #include <util/delay.h>
    #include <stdint.h>
    
    #define USART_BAUDRATE 9600UL
    #define BAUD_PRESCALER ((F_CPU / (16UL * USART_BAUDRATE)) - 1UL)
    
    static void USART_Init(void) {
        UCSR0A = 0;  // Normal asynchronous speed (U2X0 = 0)
        UBRR0H = (uint8_t)(BAUD_PRESCALER >> 8);
        UBRR0L = (uint8_t)BAUD_PRESCALER;
    
        UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // 8N1
        UCSR0B = (1 << RXEN0) | (1 << TXEN0);
    }
    
    static void USART_Transmit(uint8_t data) {
        while (!(UCSR0A & (1 << UDRE0))) {
            // Wait for space in the transmit buffer.
        }
        UDR0 = data;
    }
    
    static void USART_SendString(const char *text) {
        while (*text != '\0') {
            USART_Transmit((uint8_t)*text);
            text++;
        }
    }
    
    int main(void) {
        USART_Init();
    
        while (1) {
            USART_SendString("Hello world!\r\n");
            _delay_ms(1000);
        }
    }
    Walk through the programme
    • F_CPU specifies the assumed processor clock for the delay routines and baud-rate calculation.
    • USART_Init() selects normal asynchronous speed, writes the baud-rate divisor, and enables 8N1 transmission and reception.
    • USART_Transmit() waits for UDRE0 before writing a byte into UDR0.
    • USART_SendString() sends each character until the C string's null terminator ('\0').
    • "\r\n" appends carriage return and line feed so terminal output appears on a new line.
    • _delay_ms(1000) pauses for approximately one second; it is a blocking delay.

5. Adapt the Makefile and upload

  1. Copy the Makefile from your previous Blink project:

    cp ../blink/Makefile .
    vim Makefile
  2. In Vim, press Esc, then enter the following Ex command (including the initial colon):

    :%s/\<blink\>/uart/g

    This replaces occurrences of the whole word blink with uart. Save and quit with :wq.

    Replacing blink with uart in the Makefile

  3. Connect your board to the computer and identify its serial port:

    Get-CimInstance Win32_SerialPort | Select-Object Name, DeviceID, Description

    Windows PowerShell serial-port listing

    wmic path Win32_SerialPort get caption,name,deviceid

    wmic is a legacy utility and may not be installed on newer Windows systems. If unavailable, use PowerShell or Device Manager instead.

    Windows serial ports

  4. Set the corresponding port in your Makefile, replacing the example COM6 with the actual value:

    PORT = COM6
  5. Rebuild and upload the firmware:

    make clean
    make
    make upload

6. Observe serial output with PuTTY

  1. Open PuTTY. It is installed on the university machines; install it separately if needed on a personal computer.

  2. Choose Serial as the connection type. Set Serial line to your board's actual COM port and Speed to 9600. Under Connection → Serial, check for 8 data bits, 1 stop bit, no parity and no flow control.

  3. Open the connection. You should see a line approximately once per second:

    Hello world!
    Hello world!
    Hello world!

    Configuring PuTTY to monitor serial data

7. Two-way UART communication

The USART also supports receiving data. A useful starting point is an echo programme: when a byte arrives, the board sends that byte back.

  1. Create a new project directory and a file named uart_two_way.c:

    mkdir -p ~/embeddedC/uart_two_way
    cd ~/embeddedC/uart_two_way
    touch uart_two_way.c
  2. Enter the following programme:

    #define F_CPU 16000000UL
    
    #include <avr/io.h>
    #include <stdint.h>
    
    #define USART_BAUDRATE 9600UL
    #define BAUD_PRESCALER ((F_CPU / (16UL * USART_BAUDRATE)) - 1UL)
    
    static void USART_Init(void) {
        UCSR0A = 0;
        UBRR0H = (uint8_t)(BAUD_PRESCALER >> 8);
        UBRR0L = (uint8_t)BAUD_PRESCALER;
        UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // 8N1
        UCSR0B = (1 << RXEN0) | (1 << TXEN0);
    }
    
    static void USART_Transmit(uint8_t data) {
        while (!(UCSR0A & (1 << UDRE0))) {
        }
        UDR0 = data;
    }
    
    static uint8_t USART_Receive(void) {
        while (!(UCSR0A & (1 << RXC0))) {
        }
        return UDR0;
    }
    
    int main(void) {
        USART_Init();
    
        while (1) {
            uint8_t received = USART_Receive();
            USART_Transmit(received); // Echo the received byte.
        }
    }
  3. Copy your existing UART Makefile and replace the programme name:

    cp ../uart/Makefile .
    vim Makefile

    In Vim command mode:

    :%s/\<uart\>/uart_two_way/g

    Check that uart_two_way.c, uart_two_way.o, uart_two_way.elf and uart_two_way.hex are referenced correctly.

  4. Close PuTTY, then build and upload the new firmware:

    make clean
    make
    make upload
  5. Reopen PuTTY at 9600 baud, 8N1, no flow control. Type a few characters. They should be echoed by the board and displayed in the terminal. Disable local echo in PuTTY if you want to distinguish characters returned by the board from characters displayed locally.

7.1 Connect two boards

  1. Once your demonstrator has approved the hardware arrangement, connect the boards' serial lines TX → RX and RX → TX, with a shared GND.

  2. Verify communication in one direction using a known transmitter (for example, the original uart.c) and receiver hardware capable of observing or handling that data. Reverse the roles to verify the other direction.

  3. For a bidirectional test, use a defined initiator and responder. The echo programme alone does not start an exchange: if both boards run only the blocking echo loop, both wait forever for the first byte.

  4. Capture or observe the exchanged bytes using a demonstrator-approved serial monitoring setup; avoid attaching an additional TX driver to the same RX line. Compare what the initiator sends with what the responder returns.

    Two-board UART demonstration

8. Review and reflection

Registers

Explain the roles of UBRR0H/L, UCSR0A/B/C, and UDR0 in an asynchronous transmission.

Timing

Explain why clock frequency, baud divisor and framing must agree between communicating devices.

Debugging

Distinguish a firmware upload problem from an incorrect COM port, baud-rate mismatch or electrical UART connection issue.