
#include "opora.h"
#include "config.h"

//--- Clock configuration ---
void ClkConfig()
{
	RST_CLK->PER_CLOCK|=0x08;						//EEPROM Clock enable
	EEPROM->CMD = 0;

#ifndef REVISION_2
	RST_CLK->HS_CONTROL = 0x00000003;			//HSE - On; Generator mode On
	while((RST_CLK->CLOCK_STATUS&0x04)!=0x04);	//Wait until HSE not ready
	RST_CLK->CPU_CLOCK = 0x00000102;			//CPU Clock = HSE (25MHz)
#else
	RST_CLK->HS_CONTROL = 0x00000001;			//HSE - On; Generator mode On
	while((RST_CLK->CLOCK_STATUS&0x04)!=0x04);	//Wait until HSE not ready
	RST_CLK->CPU_CLOCK = 0x00000002;			//CPU_C1 = HSE (8MHz)
	RST_CLK->PLL_CONTROL = 0x00000200;			//PLL_MUL = 2
	RST_CLK->PLL_CONTROL |= 0x00000004;			//PLL On
	while((RST_CLK->CLOCK_STATUS&0x02)!=0x02);	//Wait until PLL CPU not ready
	RST_CLK->CPU_CLOCK = 0x00000106;			//CPU Clock = CPU_C3 = 3*8 MHz = 24MHz
#endif	//REVISION_2
	
	RST_CLK->PER_CLOCK |= (1<<24)|(1<<6)|(1<<23)|(1<<27); //clock turn on: PORTD, UART1, PORTC, BKP
	RST_CLK->UART_CLOCK = 1<<24;				//enable CLK of UART1
}

//--- Ports configuration ---
void PortConfig()
{
	//*** Config port D for Leds ***
	PORTD->FUNC = 0x00000000;
	PORTD->RXTX = 0x0000;
	PORTD->OE = 0x7F80;
	PORTD->ANALOG = 0x7F80;
	PORTD->PWR = 0x3FFFC000;

	PORTC->FUNC = 0x00000140;
	PORTC->RXTX = 0x0000;
	PORTC->ANALOG = 0x0018;
	PORTC->PWR = 0x000003C0;
}

//--- UART configuration ---
void UARTConfig()
{
#ifndef REVISION_2
	UART1->IBRD = 0x000D;	// speed of UART1 = 115200 bit/s
	UART1->FBRD = 0x0024;	// speed of UART1 = 115200 bit/s
#else
	UART1->IBRD = 0x000D;	// speed of UART1 = 115200 bit/s
	UART1->FBRD = 0x0001;	// speed of UART1 = 115200 bit/s
#endif	//REVISION_2

	UART1->LCR_H = 0x0070;	// 8-bits word, FIFO enable, parity disable, 1 stop bit
	UART1->CR = 0x0301;		// UART1, Tx, Rx enable
}

//--- BKP configuration ---
void BkpInit()
{
	if((BKP->REG_0F&(1<<4)) != (1<<4))			//if RTC disable
	{
		BKP->REG_0F |= 0x80000005;				//Reset RTC, select LSE for clocking RTC, oscillator mode, LSE On
		BKP->REG_0F &= 0x7FFFFFFF;

		while((BKP->REG_0F&(1<<13)) != (1<<13));	//wait until LSE not ready

		while((BKP->RTC_CS&(1<<6)) != 0);		//wait until write data in RTC
		BKP->RTC_PRL = 0x00008000;				//RTC div - 32768
		
		while((BKP->RTC_CS&(1<<6)) != 0);		//wait until write data in RTC
		BKP->REG_0F |= 0x00000010;				//RTC enable
		BKP->REG_0E = 0x0000802D;

		while((BKP->RTC_CS&(1<<6)) != 0);		//wait until write data in RTC

		BKP->RTC_ALRM = TIMEOUT-1;				//wakeup across (TIMEOUT-1) s

		while((BKP->RTC_CS&(1<<6)) != 0);		//wait until write data in RTC
		BKP->RTC_CS = 0x00000020;				//interrupt enable
	}
	else										//if RTC enable
	{
		while((BKP->RTC_CS&(1<<6)) != 0);		//wait until write data in RTC	
		BKP->RTC_ALRM = BKP->RTC_CNT + (TIMEOUT - 1);

		while((BKP->RTC_CS&(1<<6)) != 0);		//wait until write data in RTC	
		BKP->RTC_CS |= 0x00000020;				//enable ALR_IE interrupt
	}
}
