#include "stm32f0xx_hal.h"
#include "usart.h"
#include <stdio.h>
#include <string.h>

#ifdef __GNUC__    
  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)    
#else    
  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)    
#endif  


UART_HandleTypeDef UartHandle;


PUTCHAR_PROTOTYPE   
{   
    USART1->TDR = ch & 0x01FF;
    while (__HAL_USART_GET_FLAG(&UartHandle, USART_FLAG_TC) == RESET) {}
    //while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET) {}   
    return ch; 
}  


//
void usart_init(void)
{
    GPIO_InitTypeDef  GPIO_InitStruct;
    
    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_USART1_CLK_ENABLE();
    
    GPIO_InitStruct.Pin       = GPIO_PIN_6;
    GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull      = GPIO_PULLUP;
    GPIO_InitStruct.Speed     = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF0_USART1;
    
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
    
    GPIO_InitStruct.Pin = GPIO_PIN_7;
    GPIO_InitStruct.Alternate = GPIO_AF0_USART1;
    
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
    
    UartHandle.Instance        = USART1;

    UartHandle.Init.BaudRate   = 115200;
    UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
    UartHandle.Init.StopBits   = UART_STOPBITS_1;
    UartHandle.Init.Parity     = UART_PARITY_NONE;
    UartHandle.Init.HwFlowCtl  = UART_HWCONTROL_NONE;
    UartHandle.Init.Mode       = UART_MODE_TX_RX;
    UartHandle.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
    
    HAL_UART_DeInit(&UartHandle);
    HAL_UART_Init(&UartHandle);
}