/**
 ******************************************************************************
 * @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 nastavUart(void)
{
	// zapne hodinovy signal pro port A
	RCC->IOPENR |= RCC_IOPENR_IOPAEN;

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

	// nastavi  PA2 a PA3 do alternativniho rezimu
	GPIOA->MODER |= (GPIO_MODER_MODE2_1 | GPIO_MODER_MODE3_1);

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

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

	// 16 MHz / 1667 = 9598 Baud
	USART2->BRR = 1667U;

	// nastavi 7bitove adresu a jeji hodnotu
	USART2->CR2 |= (USART_CR2_ADDM7 | (0xAA << USART_CR2_ADD_Pos));

	// povoli preruseni pri splneni podminky a nastavi podminku preruseni
	// 0 -> shoda adresy, 2 -> detekce startovaciho bitu, 3 -> prijem dat
	USART2->CR3 |= (USART_CR3_WUFIE | (0 << USART_CR3_WUS_Pos));

	// povoli linku preruseni ARM jadra pro USART2
	NVIC->ISER[0] |= (1U << USART2_IRQn);

	// povoli USART, odesilani a prijem dat a funkci behem odstaveneho rezimu
	USART2->CR1 |= (USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_UESM);

	// zvoli HSI jako zdroj hodinoveho signalu
	RCC->CCIPR |= RCC_CCIPR_USART2SEL_1;
}

void USART2_IRQHandler(void)
{
	// vynuluje priznak probuzeni kontroleru
	USART2->ICR |= USART_ICR_WUCF;

	// vynuluje priznak preruseni linky ARM
	NVIC->ICPR[0] |= (1U << USART2_IRQn);

	// odesle znak
	USART2->TDR = 'x';
	while((USART2->ISR & USART_ISR_TC) != USART_ISR_TC);

	if(USART2->RDR == 0xAB)
	{
		// vypne navrat odstaveneho rezimu po opusteni ISR
		SCB->SCR &= ~SCB_SCR_SLEEPONEXIT_Msk;
	}
}

int main(void)
{
	nastavUart();

	// nastavi HSI jako zdroj hodinoveho signalu
	// po probuzeni (vychozi MSI)
	RCC->CFGR |= RCC_CFGR_STOPWUCK;

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

	// vrati se do odstaveneho rezimu po opusteni ISR
	SCB->SCR |= SCB_SCR_SLEEPONEXIT_Msk;

	// zapne odstaveny rezim probuzeny prerusenim
	asm("wfi");

	USART2->TDR = 'y';

	while(1);
}
