/**
 ******************************************************************************
 * @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 zapniLsi(void)
{
	// zapne periferii nastaveni napajeni
	RCC->APB1ENR |= RCC_APB1ENR_PWREN;

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

	// zapne LSI
	RCC->CSR |= RCC_CSR_LSION;

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

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

void nastavTim21(void)
{
	// zapne hodinovy signal pro TIM21
	RCC->APB2ENR |= RCC_APB2ENR_TIM21EN;

	// spoustec 1 reaguje na signal LSI
	TIM21->OR |= (TIM21_OR_TI1_RMP_2 | TIM21_OR_TI1_RMP_0);

	// kanal 2 reaguje na spoustec 1
	TIM21->CCMR1 |= TIM_CCMR1_CC2S_1;

	// povoli preruseni pri zachyceni spoustece
	TIM21->DIER |= TIM_DIER_CC2IE;

	// zapne linku preruseni ARM pro TIM21
	NVIC->ISER[0] |= (1 << TIM21_IRQn);

	// zapne kanal 2
	TIM21->CCER |= TIM_CCER_CC2E;
}

void spustTim21(void)
{
	// spusti casovac
	TIM21->CR1 |= TIM_CR1_CEN;
}

void TIM21_IRQHandler(void)
{
	static uint32_t cas1, cas2, frekvence;

	if (cas1 == 0U)
	{
		// cteni registru vynuluje priznak preruseni
		cas1 = TIM21->CCR2;
	}
	else
	{
		// cteni registru vynuluje priznak preruseni
		cas2 = TIM21->CCR2;

		frekvence = 2097000 / (cas2 - cas1);

		cas1 = 0U;
	}

	// vynuluje priznak preruseni
	NVIC->ICPR[0] |= (1 << TIM21_IRQn);
}

int main(void)
{
	// reset
	RCC->ICSCR &= ~(RCC_ICSCR_MSIRANGE_Msk);

	// nastavi kmitocet vicerychlostniho oscilatoru
	RCC->ICSCR |= ((6 << RCC_ICSCR_MSIRANGE_Pos) & RCC_ICSCR_MSIRANGE_Msk);

	//nastavTim21();

	//spustTim21();

	zapniLsi();

	while(1);
}
