Skip to main content

Subsection 3.3.5 Sending and Receiving Data

After initialization, transmitting a byte requires waiting until the transmit data register is empty (TXE bit in USART_ISR), then writing the byte to USART_TDR. Receiving a byte requires waiting until a byte has been received (RXNE bit), then reading USART_RDR.
Figure 3.3.12. USART Interrupt and Status Register (USART_ISR). The TXE bit (bit 7) is set when the transmit data register is empty and ready for a new byte. The RXNE bit (bit 5) is set when a received byte is waiting to be read.
// Transmit one byte
void uart2_write(int ch) {
    // Wait until TX data register is empty
    while (!(USART2->ISR & USART_ISR_TXE_TXFNF)) {}
    USART2->TDR = (ch & 0xFF);
}

// Receive one byte (blocking)
int uart2_read(void) {
    // Wait until a byte has been received
    while (!(USART2->ISR & USART_ISR_RXNE_RXFNE)) {}
    return (USART2->RDR & 0xFF);
}
With the retarget layer in uart.c, printf calls uart2_write for each character. This lets you use the full C standard I/O library over the serial port.