#include "sysinit.h"

//interni cristal 16MHz fcpu=((HSI/PPLM)*N)/R
#define PLLM 		1U		//clock divider
#define N				9U		//clock multiplier




	void sys_init(void)		
	{
		RCC->CR |=  RCC_CR_HSION;			//HSI as source for PLL
		while(!(RCC->CR & RCC_CR_HSIRDY));
		
		RCC->APB2ENR |=  RCC_APB2ENR_SYSCFGEN;
		FLASH->ACR	 &=  ~FLASH_ACR_LATENCY;
		FLASH->ACR	 |=  FLASH_ACR_LATENCY_4WS|FLASH_ACR_PRFTEN;		//flash memory prefatch 
		RCC->CR			 &= ~RCC_CR_PLLON;
		while((RCC->CR & RCC_CR_PLLRDY));
		
		RCC->CFGR 		&= ~(RCC_CFGR_PPRE1|RCC_CFGR_PPRE2);
		RCC->CFGR 		|=  RCC_CFGR_PPRE1_DIV1|RCC_CFGR_PPRE2_DIV1;					//APB peripheral clock = sys clock
		RCC->PLLCFGR	&= ~(RCC_PLLCFGR_PLLM|RCC_PLLCFGR_PLLN|RCC_PLLCFGR_PLLR);
		RCC->PLLCFGR	|=	N<<RCC_PLLCFGR_PLLN_Pos|RCC_PLLCFGR_PLLSRC_HSI;
		RCC->CR 			|=  RCC_CR_PLLON;
		RCC->PLLCFGR	|= 	RCC_PLLCFGR_PLLREN;
		while(!(RCC->CR & RCC_CR_PLLRDY));
		
		RCC->CFGR =  RCC_CFGR_SW_PLL;
		while(((RCC->CFGR&RCC_CFGR_SWS)!=RCC_CFGR_SWS_PLL));		//PLL as source for clock speed

		SystemCoreClockUpdate();		//system clock speed set to 72MHz
		(void) SystemCoreClock;

		RCC->APB1ENR1 |= RCC_APB1ENR1_PWREN;					//clock enable
		RCC->AHB2ENR   |=   RCC_AHB2ENR_GPIOCEN;			//input -	button																								
		GPIOC->MODER   &= ~0x03U<<26;
		GPIOC->OTYPER  &= ~0x01U<<13;
		GPIOC->OSPEEDR &= ~0x03U<<26;
		GPIOC->PUPDR   &= ~0x03U<<26;
		SYSCFG->EXTICR[3] |=	SYSCFG_EXTICR4_EXTI13_PC;
		EXTI->IMR1 		|= 0x01U<<13;
		EXTI->FTSR1   |=0x01U<<13;
		NVIC_SetPriority(EXTI15_10_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(),0,4));	//interupt on button
		NVIC_EnableIRQ(EXTI15_10_IRQn);
		/*
			outputs for LEDs 
			PB5 RED
			PB6 GREEN
		*/
		RCC->AHB2ENR   |=   RCC_AHB2ENR_GPIOBEN;																
		GPIOB->MODER   &= ~(0x03U<<10|0x03U<<12);
		GPIOB->MODER   |=  0x01U<<10|0x01U<<12;
		GPIOB->OTYPER  &= ~(0x01U<<5|0x01U<<6);
		GPIOB->OSPEEDR &= ~(0x03U<<10|0x03U<<12);
		GPIOB->PUPDR   &= ~(0x03U<<10|0x03U<<12);
		GPIOB->BSRR		  =  0x01U<<5|0x01U<<6;
		GPIOB->BSRR		  =  0x01U<<21|0x01U<<6;
	}
	
	
	void sleep_mode(void)
	{
		USART1->CR1 &= ~USART_CR1_RXNEIE;
		NVIC_DisableIRQ(USART1_IRQn);
		SysTick->CTRL = 0;
		PWR->SCR  = 0x11F;
		SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk;
		__wfi();
		
		USART1->ICR    =   USART_ICR_IDLECF|USART_ICR_ORECF|USART_ICR_PECF|USART_ICR_LBDCF|USART_ICR_NCF|USART_ICR_FECF|USART_ICR_CMCF;
		SCB->ICSR |= SCB_ICSR_PENDSTCLR_Msk;
		SysTick->CTRL |= (0X01U<<2)|(0X01U)|(0X01U<<1);
		USART1->CR1 |= USART_CR1_RXNEIE;
		NVIC_EnableIRQ(USART1_IRQn);
	}
	
	
	void EXTI15_10_IRQHandler(void)
	{
		EXTI->PR1 =0x01<<13;
	}
		
