/**
 ******************************************************************************
 * @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
 *
 ******************************************************************************
 */

#include "stm32l073xx.h"

#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


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 | RCC_CSR_LSEDRV_Msk);

	// cekej, nez je LSE pripraven
	while((RCC->CSR & RCC_CSR_LSERDY) != RCC_CSR_LSERDY);
}


void zmenDelicku(void)
{
	// zapis sekvenci k odblokovani zapisu do RTC registru
	RTC->WPR = 0xCA;
	RTC->WPR = 0x53;

	// zapne inicializacni rezim RTC
	RTC->ISR |= RTC_ISR_INIT;

	// cekej, dokud neni RTC v inicializacnim rezimu
	while((RTC->ISR & RTC_ISR_INITF) != RTC_ISR_INITF);

	RTC->PRER = 0x00007FFF;

	// vypne inicializacni rezim RTC
	RTC->ISR &= ~RTC_ISR_INIT;
}

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

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

	// zvoli LSE jako zdroj hodinoveho signalu pro RTC a zapne jej
	RCC->CSR |= (RCC_CSR_RTCSEL_LSE | RCC_CSR_RTCEN);

	zmenDelicku();
}


int main(void)
{
	zapniLse();

	nastavRtc();

	// nastavi odstaveny rezim pri operaci "wfi"
	SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;

	// vypne napetovou referenci
	// zapne pohotovstni rezim pri zavolani "wfi"
	PWR->CR |= (PWR_CR_ULP | PWR_CR_PDDS);

	asm("wfi");
}
