/**
 ******************************************************************************
 * @file           : main.c
 * @author         : Auto-generated by STM32CubeIDE
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics.
 * All rights reserved.</center></h2>
 *
 * This software component is licensed by ST under BSD 3-Clause license,
 * the "License"; You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *                        opensource.org/licenses/BSD-3-Clause
 *
 ******************************************************************************
 */

#if !defined(__SOFT_FP__) && defined(__ARM_FP)
  #warning "FPU is not initialized, but the project is compiling for an FPU. Please initialize the FPU before use."
#endif

#include "stm32l073xx.h"

void zapniLse(void)
{
	// zapne periferii nastaveni napajeni
	RCC->APB1ENR |= RCC_APB1ENR_PWREN;

	// vypne ochranu pred zapisem do RCC->CSR registru
	PWR->CR |= PWR_CR_DBP;

	// zapne LSE s nejvyssim ridicim proudem
	RCC->CSR |= (RCC_CSR_LSEON | (3 << RCC_CSR_LSEDRV_Pos));

	// cekej, dokud neni LSE pripraven
	while((RCC->CSR & RCC_CSR_LSERDY) != RCC_CSR_LSERDY);

	// vypne periferii nastaveni napajeni
	RCC->APB1ENR &= ~RCC_APB1ENR_PWREN;
}

void nastavUart(void)
{
	// zapne hodinovy signal pro port A
	RCC->IOPENR |= RCC_IOPENR_IOPAEN;

	// vynuluje nastaveni rezimu PA2 (vstupni rezim)
	GPIOA->MODER &= ~GPIO_MODER_MODE2;

	// nastavi  PA2 do alternativniho rezimu
	GPIOA->MODER |= GPIO_MODER_MODE2_1;

	// nastavi pinu PA2 alternativni rezim 4 - UART
	GPIOA->AFR[0] |= (4U << GPIO_AFRL_AFSEL2_Pos);

	// zvoli LSE jako zdroj hodinoveho signalu
	RCC->CCIPR |= RCC_CCIPR_USART2SEL_Msk;

	// zapne hodinovy signal pro USART2
	RCC->APB1ENR |= RCC_APB1ENR_USART2EN;

	// 32768 Hz / 26 = 2427 (v toleranci 2400)
	// uprava hodnoty BRR dle manualu
	USART2->BRR = 0x15;

	// povoli USART, odesilani dat a nastavi
	// osminasobne prevzorkovani
	USART2->CR1 |= (USART_CR1_UE | USART_CR1_TE | USART_CR1_OVER8);
}

int main(void)
{
	zapniLse();

	nastavUart();

	// odesle data
	USART2->TDR = 'x';

	// cekej, dokud neni prenos dat hotov
	while((USART2->ISR & USART_ISR_TC) != USART_ISR_TC);

	while(1);
}
