
#include "opora.h"

#define REVISION_2

void ClkConfig(void);
void PortConfig(void);
void UARTConfig(void);
void UART1_Handler(void);

uint32_t Temp, CurrentLed = 0;
int main()
{
	ClkConfig();
	PortConfig();
	UARTConfig();
	NVIC_EnableIRQ(UART1_IRQn);			//Enable UART1 interrupt
	while(1)	//Run Led
	{
		PORTD->RXTX = 0;
		PORTD->RXTX = 1<<(7+CurrentLed++);
		if(CurrentLed > 7) CurrentLed = 0;
		for(Temp=0;Temp<100000;Temp++);
	}
}

//--- Clock configuration ---
void ClkConfig()
{
#ifdef REVISION_2
	RST_CLK->HS_CONTROL = 0x00000001;			//HSE - On; Oscillator mode
	while((RST_CLK->CLOCK_STATUS&0x04)!=0x04);	//Wait until HSE not ready
	RST_CLK->PLL_CONTROL=(1<<2)|(2<<8);			//CPU PLL On, PLL MULL=2
	while((RST_CLK->CLOCK_STATUS&0x02)!=0x02);	//Wait until PLL not ready
	RST_CLK->PER_CLOCK|=0x08;					//EEPROM_CTRL Clock enable
	EEPROM->CMD=0;
	RST_CLK->PER_CLOCK&=(~0x08);				//EEPROM_CTRL Clock disable
	RST_CLK->CPU_CLOCK = 0x00000106;			//CPU Clock=3*8MHz=24MHz
#else
	RST_CLK->HS_CONTROL = 0x00000003;			//HSE - On; Generator mode
	while((RST_CLK->CLOCK_STATUS&0x04)!=0x04);	//Wait until HSE not ready
	RST_CLK->PER_CLOCK|=0x08;					//EEPROM_CTRL Clock enable
	EEPROM->CMD=0;
	RST_CLK->PER_CLOCK&=(~0x08);				//EEPROM_CTRL Clock disable
	RST_CLK->CPU_CLOCK = 0x00000102;			//CPU Clock = HSE (25MHz)
#endif	//REVISION_2
	RST_CLK->PER_CLOCK|=(1<<6)|(1<<23)|(1<<24);	//clock of UART1, PORTC, PORTD On
	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()
{
#ifdef REVISION_2
	UART1->IBRD = 0x000D;	// speed of UART1 = 115200 bit/s
	UART1->FBRD = 0x0001;	// speed of UART1 = 115200 bit/s
#else
	UART1->IBRD = 0x000D;	// speed of UART1 = 115200 bit/s
	UART1->FBRD = 0x0024;	// speed of UART1 = 115200 bit/s
#endif	//REVISION_2
	UART1->LCR_H = 0x0060;	// 8-bits word, FIFO disable, parity disable, 1 stop bit
	UART1->CR = 0x0301;		// UART1, Tx, Rx enable

	UART1->ICR = 1<<4;		// clear Rx_interrupt_flag
	UART1->IMSC = 0x0010;	// Rx interrupt enable
}

//--- UART1 interrupt routine ---
void UART1_Handler()
{
	uint32_t Temp;
	UART1->ICR = 1<<4;		// clear Rx_interrupt_flag
	Temp = UART1->DR + 1;
	while((UART1->FR&(1<<5)) == (1<<5));	//wait until Tx not ready
	UART1->DR = (uint8_t)Temp;
}


