
#include "opora.h"

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

int main()
{
	ClkConfig();
	UARTConfig();
	PortConfig();
	NVIC_EnableIRQ(UART1_IRQn);			//Enable UART1 interrupt
	SysTickInit();
	while(1);
}

void SysTick_Handler(void)
{
	static uint32_t Sec=1, mSec=0;
	if(mSec++ ==9)
	{
		mSec=0;
		Sec++;
	
		if((Sec%2)==0)	//прошло 2 секунды
		{
			UART1->DR=(uint8_t)Sec;
		}
	}
}

//--- Clock configuration ---
void ClkConfig()
{
	RST_CLK->HS_CONTROL = 0x00000001;			//HSE - On; Oscillator 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 (8MHz)
	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, F_UART1=HCLK
}

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

	//*** Config port C for SIR UART1 ***
	PORTC->FUNC = 0x00003C0;
	PORTC->ANALOG = 0x0018;
	PORTC->PWR = 0x000003C0;
}

//--- UART configuration ---
void UARTConfig()
{
	UART1->IBRD=0x0004;	// speed of UART1 = 115200 bit/s
	UART1->FBRD=0x0016;	// speed of UART1 = 115200 bit/s

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

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

//--- UART1 interrupt routine ---
void UART1_Handler()
{
	UART1->ICR = 0x10;		// clear Rx_interrupt_flag
	PORTD->RXTX=((uint8_t)UART1->DR)<<7;
}

void SysTickInit()
{
	SysTick->LOAD = 0x000C34FF;	//Pause 100 ms (HCLK = 8MHz)
	SysTick->CTRL = 0x00000003;	//Enabel SysTick, Interrupt Enable
}


