
#ifndef __UART_C
#define	__UART_C

#include "opora.h"
#include "DMA.h"
#include "CBuffer.h"

extern DMAManagementStructureTypeDef	ManagementStructure[2];
extern CBufferTypeDef					Buffer;
extern uint32_t cnt;

void UARTInit()
{
	//Clock settings for PortC
	RST_CLK->PER_CLOCK |= 1<<23;	//clock of PORTC enable

	//PortC[3], PortC[4] - UART1
	PORTC->FUNC|=0x00000140;
	PORTC->ANALOG|=0x0018;
	PORTC->PWR|=0x000003C0;

	//Clock settings for UART1
	RST_CLK->PER_CLOCK|=1<<6;		//clock of UART1 On
	RST_CLK->UART_CLOCK=1<<24;		//enable CLK of UART1

	//UART1 settings
	UART1->IBRD=0x0008;		//speed of UART1 = 115200 bit/s (HCLK=16MHz)
	UART1->FBRD=0x002C;		//speed of UART1 = 115200 bit/s (HCLK=16MHz)

	UART1->LCR_H=0x0070;	//8-bits word, FIFO enable, parity disable, 1 stop bit
	UART1->IFLS=0x10;		//interrupt occur, when received 8 bytes
	UART1->DMACR=1;			//enable DMA request, when received data

	UART1->ICR=0x10;		//reset Rx interrupt
	UART1->IMSC=0x10;		//Rx interrupt enable
	
	UART1->CR=0x0201;		// UART1 enable, Rx enable
}

void UART1_Handler()
{
	uint32_t value;

	UART1->ICR=0x10;		//reset Rx interrupt	
	value=ManagementStructure[1].DestinationEndPointer-(uint32_t)(&Buffer.Data[0]);
	if(value==(LENGTH-1))	ManagementStructure[1].DestinationEndPointer=(uint32_t)(&Buffer.Data[7]);	//Destination end pointer address
	else					ManagementStructure[1].DestinationEndPointer+=8;							//Destination end pointer address
	ManagementStructure[1].Control=0x0C000071;															//DMA cycle = 8
	DMA->CHNL_ENABLE_SET=0x2;																			//enable channel 1 from UART1
	Buffer.Length+=8;
	cnt+=8;
}

#endif	//__UART_C

