STM32 UART Driver Implementation

Understanding the UART peripheral

April 2, 2024 (22d ago)


The first step is to enable peripheral clocks.

USART2 is enabled py the Advanced Peripheral Bus (APB) Clock.

_HAL_RCC_GPIOA_CLK_ENABLE;

Interal peripherals such as I2C, SPI, etc are mapped to GPIO pins. The GPIO is multiplexed, so you have to hope all the peripherals you are utilizing in a project are seperate.

Anyways do the following to set teh GPIO to alternate.

GPIOA->MODE |= (GPIO_MODER_MODER2_1 | GPIO_MODER_MODER3_1)
void uart_transmit(const char * buffer)
{
    while (*buffer != '\0')
    {
        // Place current char element into the USART Data Register (DR)
        USART2->DR = *buffer

        // Wait until the Transicaiton Complete (TC) bit is set in Status Register (SR)
        while (!(USART2->SR & USART_SR_TC)) {};

        // Increment address to next element to send    
        buffer++;
    }
}
int main(void)
{
    char data [] = "The STM32 HALs are fairly confusing, but thankfully they have decent documentation on thier chips"

    uart_transmit(&data);

}

Connect to a serial monitor and observed them bytes being sent your way.

Important to note, that this method is blocking meaning the CPU is busy transmitting this buffer that it cannot do any other operations.