/*
 * usart.c
 * http://www.skybeeper.com/index.php/en/english-en/25-tighten-scanf
 */
#include "usart1.h"

/*
+=============================================================================+
/file usart1.c
+=============================================================================+
*/
/*
 * how to count BRR
 * BRR = P_frequency /(16*baudrate)
 * for example:
 * 24 000 000/(16*9600)= 156,25
 * 156 dec = 0x9C
 * 0,25*16 = 4dec = 0x4 hex
 * BRR = 0x009C+0x0004 = 0x09C4
 *
 * this way of counting BRR is equal and gives results directly in hex
 * BRR  = (PLL_FREQUENCY+UART1_BAUDRATE/2)/UART1_BAUDRATE;
 */

void Usart1Init(void){

	RCC->APB2ENR |= (RCC_APB2ENR_AFIOEN | RCC_APB2ENR_USART1EN);  //Clock
	AFIO->MAPR &= ~(AFIO_MAPR_USART1_REMAP);		//UART1 at the original pins
	GPIOA->CRH  = 0x0090;  							//GPIO_CRH_BIT9 = Alternate function, 10MHz
    USART1->BRR  = (PLL_FREQUENCY+UART1_BAUDRATE/2)/UART1_BAUDRATE;
	             //0x008B;  Baud=FREQUENCY/(16*8,69)=115107;	// BRR simplified thanks to Uwe Hermann
    USART1->CR1 |= (USART_CR1_RE | USART_CR1_TE | USART_CR1_UE);  // RX, TX enable
}



void Usart1Put(char ch)
{
	USART_SendData(USART1, (char) ch);

  	while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)
	{
	}
}

char Usart1Get(void){

	while ( USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET);
	return (char)USART_ReceiveData(USART1);
}
