#include <stdio.h>
#include <ADuCM360.H>
#include <string.h>

float Volt;      
void delay (long int length);
void SER_Init (void);
void Send_Uart(char x);
void Send (char Buff[]);

int main (void) {
	SER_Init();
	
	pADI_GP1->GPOEN  =  0x8 ;                    // GPIO1.3 is output    
	pADI_GP1->GPSET  =  0x8;                 	 	 // switch LED off       

	pADI_ANA->REFCTRL = 0x0;										 // enable refirence
	pADI_ANA->IEXCDAT = 0xE;										 // set output 0,2mA
	pADI_ANA->IEXCCON = 0x70;										 // setup Iexc for AIN6 
	
	pADI_ADC1->CON = 0x8C001;										 // Enable ADC1, AIN0/AIN1 input 
	pADI_ADC1->MDE = 0x51;           					   // g=32 nekonecne mereni 
	pADI_ADC1->FLT = 0x8D7C;         						 // 30Hz sampling rate, chop off

	while(1) {
		Volt = 0;
		
		int d = 0;
		while (d==0) {	
			d = pADI_ADC1->STA&1;										 // prectu status registr
	  }
		
		Volt = pADI_ADC1->DAT;            				 // prectu ADC data register
		Volt = Volt * 1.2 / 268435456;						 // prepocet
		
		char buffer[16] ; 
		sprintf(buffer, "%f", Volt);		
		Send(buffer);															 // posilani

		pADI_GP1->GPCLR = 0x8;                     // Turn on LED        
		delay(1000000);
		pADI_GP1->GPSET = 0x8;                     // Turn off LED       
		delay(1000000);
  }
}
void delay (long int length)
{
	while (length >0)
	length--;
}
void SER_Init (void) {
  pADI_UART->COMCON= 0x0; 										 // uart enable
  pADI_GP0->GPCON |= 0x3C;										 // P0.1/P0.2 pro UART
  pADI_UART->COMLCR= 0x3; 										 // no parity, 1 stop bit, 8 data bits
  pADI_UART->COMDIV= 0x2; 										 // comdiv=2
  pADI_UART->COMFBR= 0x915C; 									 // baud rate 115200 divm=2 divn=348 0b1001000101011100
}
void Send_Uart (char x){
	while (!(pADI_UART->COMLSR == 0))
  pADI_UART->COMTX=x; 												 // posilani 1 symbolu
}
void Send (char Buff[]) {
  int cnt=0;
  int cnt1=0;
  Send_Uart(0x02); 														 // zacatek zpravy
  delay(700);

  cnt1=strlen(Buff); 													 // cnt1=delka bufferu
  while (cnt<cnt1)
  {
		if (Buff[cnt]!=0)
		{
			Send_Uart(Buff[cnt]);
			delay(500);
		}
		cnt++;
	}

	delay(700);
	Send_Uart(0x0d); 														 // konec zpravy
}
