How to use printf with STM32 UART

Say you have defined your UART using the STM32CubeIDE device configuration tool. It will have created a handle and made sure it is initialized in main(). Something like this:

UART_HandleTypeDef hlpuart1;

int main(void) {
    HAL_Init();
    SystemClock_Config();
    MX_GPIO_Init();
    MX_LPUART1_UART_Init();
    while(1) {
    }
}

You could then use code like this to write to the UART:

const char * hello_world = "Hello world\r\n";
HAL_UART_Transmit(&hlpuart1, (uint8_t *)hello_world, strlen(hello_world), HAL_MAX_DELAY);

But you want to write it like this:

printf("Hello %s\r\n", "world");

To make this work you have to implement a special function (_write) to tell the C-library how to process the output from the printf function.

int _write(int fd, char* ptr, int len) {
    HAL_UART_Transmit(&hlpuart1, (uint8_t *) ptr, len, HAL_MAX_DELAY);
    return len;
}