/*******************************************************************************
--------------------------------------------------------------------------------
*** TestAll example
  
 This example uses most peripherals of the STR73xFZ2 and the REva board.
 It implements a UART terminal that allows the other side (host PC)
 to access everything on the board.
 You can duplicate and modify it as a starting point for your projects.
 
 Note that this program is too large to work in RAM mode with the STR73x;
 as a consequence, the project is configured to run in FLASH mode, with 
 debugging disabled (debugging in FLASH mode is only allowed with RLink Pro).
 
--------------------------------------------------------------------------------
*** FILES

  testallmain.c (this file) which contains the initializations and the main loop.
  revalib.c which contains utility functions for the REva.
  
--------------------------------------------------------------------------------
*** DEBUG

 
--------------------------------------------------------------------------------
*** JUMPERS

 On the REva board, you must set most jumpers:
 OUTPUT: D0->D7
 INPUT: SW1->SW4, BT5, BT6, L
 ANALOG: IN1, IN2, OUT, POT, TEMP
 COM: SCL, SDA, TX, RX, EN/EEPROM, pullups/I2C ; don't set WP/EEPROM (Write Protect) and A0/EEPROM
                         (change EEPROM I2C address) for a correct EEPROM handling.
 
 On the daughter board, select the RLink clock by setting the "DNG" jumper.
 
--------------------------------------------------------------------------------
********************************************************************************
--------------------------------------------------------------------------------

			Copyright (c), RAISONANCE

--------------------------------------------------------------------------------
 The present source code which is for guidance only aims at providing
 customers with information regarding their products in order for them to
 save time. As a result, RAISONANCE shall not be held liable for any
 direct indirect or consequential damages with respect to any claims arising
 from the content of such a source code and/or the use made by customers of 
 the information contained herein in connection with their products.
--------------------------------------------------------------------------------
*******************************************************************************/
 


// =========================================================================== 
// Project:        TestAll 
// File:           TestAllMain.c 
// Organization:  
// Author:        
// Date:           12/2/2004 
// =========================================================================== 

#include "73x_lib.h"
#include <UART0_stdio.h>

#include "REvaLib.h"

#define RTC_Prescaler_val 0x00008000


//---------------------------------------------------------------------------
//Function:       PeriphInit
//Purpose:        Periph configuration at RESET
// Date:           12/2/2004 
//---------------------------------------------------------------------------
void PeriphInit ( void ) 
{ 
	CMU_InitTypeDef   CMU_InitStructure;
	PRCCU_InitTypeDef   PRCCU_InitStructure;
	RTC_InitTypeDef   RTC_InitStructure;
#if USE_ANALOG
   init_adc();
#endif
   
   // I2C initialization
#if USE_EEPROM
   init_I2C();
#endif

#if USE_ANALOG
   init_PWM();
#endif

#if USE_IO
   init_IO();
#endif

//---------------------------------------CMU---------------------------------------------
  // CMU Initialization 
  CMU_DeInit( );
  CMU_StructInit(&CMU_InitStructure);
  // Enable the external oscillator 
  CMU_InitStructure.CMU_CKSEL0 = CMU_CKSEL0_CKOSC;
  CMU_Init( &CMU_InitStructure);

//-------------------------------------PRCCU---------------------------------------------
  // PRCCU Initialization 
  PRCCU_DeInit();
  PRCCU_StructInit(&PRCCU_InitStructure);  
  // PRCCU Config 
  PRCCU_InitStructure.PRCCU_DIV2 = DISABLE;
  PRCCU_Init(&PRCCU_InitStructure);

  // Set RTC clock------- 
  // (clock:0-->9) fOSC=8Mhz/RTCP=(2,4,8,16,32,64,128,256,512,1024)
  //                       -->EXTCLK=(4M,2M,1M,500K,250K,125K,62.5K,31.25K,15.625K,7.812K) 
  PRCCU_SetExtClkDiv(8);

//---------------------------------------EIC---------------------------------------------
  // EIC Clock Enable 
  CFG_PeripheralClockConfig(CFG_CLK_EIC , ENABLE);
  // EIC Config 
  EIC_IRQChannelPriorityConfig( RTC_IRQChannel, 1);
  EIC_IRQChannelConfig( RTC_IRQChannel , ENABLE );
  EIC_IRQCmd(ENABLE);

//---------------------------------------RTC---------------------------------------------
  // RTC Clock Enable 
  CFG_PeripheralClockConfig(CFG_CLK_RTC , ENABLE);

  // RTC Interrupt Config----------------------------- 
  RTC_ITConfig (RTC_IT_GL | RTC_IT_SEC, ENABLE);

  // RTC Configuration------------------------------- 
  RTC_InitStructure.RTC_Alarm = 0xFFFFFFFF;
  RTC_InitStructure.RTC_Counter = 0xFFFFFFFA;
  RTC_InitStructure.RTC_Prescaler = 0x3D09; // configure RTC =1S  (RCK=1000000/64=CKL32=15625Hz) 
  RTC_Init (&RTC_InitStructure);

}//end of  PeriphInit


//if zero, getch does not send an echo. if not zero, it does.
unsigned char Echo_ON=1;

#if USE_EEPROM
//this buffer is used for storing temp data from/to the EEPROM
unsigned char mybuffer[0x100];
#endif


//this must equal the STR7's alimentation voltage in mV
#define ALIMVOLTAGEMV (5000)

unsigned long t_1s = 0;

//---------------------------------------------------------------------------
//Function:       getch
//Purpose:        Getch in polling mode on SCI
// Date:           12/2/2004 
//---------------------------------------------------------------------------
u8 getch()
{
	u8  value;
	value=getchar();

   if(Echo_ON)
   	putchar(value); //echo
	return(value);
}


//this function reads a byte in hex from the SCI
//  that's two hex digits for one unsigned char
unsigned char readhex2()
{
	char car1;
	char car2;
	
	car1=getch(); //read high weight nibble
	car1=readhex(car1); //convert in hex number
	
	car2=getch(); //read low weight nibble
	car2=readhex(car2); //convert in hex number
	
	return ((car1<<4)+car2);
}

//---------------------------------------------------------------------------
//Function:       main()
//Purpose:        main routine
// Date:           12/2/2004 
//---------------------------------------------------------------------------
int main ( )
{
  #ifdef DEBUG
  debug();
  #endif
	
   //Configure the internal peripherals
   PeriphInit();

  	printf("\n *** REva test program ***");

   while ( 1 )
   {
		u8 c;
		unsigned short addr;
		
		//display the prompt
	  	printf("\n>");
	  	
   	//read the command
   	c=getch();
   	
   	// analyze and execute the command
   	switch(c)
   	{
			// **** Analogic functions
	   	
#if USE_ANALOG
	   	case 'T': //read temp sensor
	   	case 't':
	   		addr=ReadTemp(ALIMVOLTAGEMV);
	  			printf("\n%d.%dC",(int)(addr/10),(int)(addr%10));
	   		break;
	   		
	   	case 'P': //read pot
	   	case 'p':
	   		addr=ReadPot();
	  			printf("\n%d%%",(int)(addr));
	   		break;
	   		
	   	case 'I': //read IN1
	   	case 'i':
	   		addr=ReadI1(ALIMVOLTAGEMV);
	  			printf("\n%dmV",(int)(addr));
	   		break;
	   		
	   	case 'J': //read IN2
	   	case 'j':
	   		addr=ReadI2(ALIMVOLTAGEMV);
	  			printf("\n%dmV",(int)(addr));
	   		break;
	
	   	case 'O': //output on OUT
	   	case 'o':
		   	{
		   		char c1, c2, c3, c4;
		   		c1 = getch() - '0';
		   		c2 = getch() - '0';
		   		c3 = getch() - '0';
		   		c4 = getch() - '0';
		   		addr=(((((c1*10)+c2)*10)+c3)*10)+c4;
		   	}
	   		SetOUT(addr, ALIMVOLTAGEMV);
	   		break;
#endif
	   	
			// **** Memory access functions
			// note that these allow to access the Registers
			// so they could make some of the other commands crash
			// by unconfiguring some peripherals.
	   		
	   	case 'R': //read EEPROM or RAM or code or ...
	   	case 'W': //write EEPROM or RAM or code or ...
	   		c-='A'; //make it lower case
	   		c+='a';
	   	case 'r': //read EEPROM or RAM or code or ...
	   	case 'w': //write EEPROM or RAM or code or ...
		   	{
					char d; //that's the character indicating which space to read or write
					unsigned char cnt; //that's the number of bytes to read or write
					unsigned char tmpcnt; //that's the counter of bytes read or written
					unsigned int realaddr; //that's the address of the data in its original space
					unsigned char *addr; //that's the pointer to the RAM/code space where we put or get the data
					
		   		//read destination space ('e' for EEPROM, and 'm' for memory)
		   		d = getch();
		   		
		   		//read address
		   		realaddr = readhex2() * 0x100;
		   		realaddr += readhex2();
		   		
		   		//read count
		   		cnt = readhex2();
		   		
		   		//use the buffer if accessing the EEPROM, or directly the code/RAM space
		   		switch(d)
		   		{
#if USE_EEPROM
		   			case 'E':
		   				d='e';
		   			case 'e':
		   				realaddr&=0xFF;
		   				addr=mybuffer;
		   				break;
#endif
		   			case 'F':
		   				d='f';
		   			case 'f':
		   				realaddr+=0x40000000;
				   		addr=(unsigned char *)(realaddr);
				   		if(c=='w')
				   			d='0';
		   				break;
		   			case 'R':
		   				d='r';
		   			case 'r':
		   				realaddr+=0x20000000;
				   		addr=(unsigned char *)(realaddr);
		   				break;
		   			default:
		   				d='0';
		   				break;
		   		}
	   		
		   		//check for error in command
	   			//(we can only write in RAM or EEPROM)
   				if(d=='0')
   					break;

		   		if(c=='w')
		   		{
		   			//if writing
		   			//read the values to write
		   			tmpcnt=0;
		   			while(tmpcnt<cnt)
				   		addr[tmpcnt++] = readhex2();
			   		
			   		//write the EEPROM if needed
#if USE_EEPROM
			   		if(d=='e')
			   			{
		   				cnt&=0x0F;
							WriteEEPROM((unsigned char)realaddr, cnt, addr);
							}
#endif
		   		}
		   		else
		   		{
		   			//if reading...
		   			//read the values from the EEPROM if needed
#if USE_EEPROM
			   		if(d=='e')
			   			ReadEEPROM((unsigned char)(realaddr&0xFF), cnt, addr);
#endif
		   			
		   			//display the values
			   		putchar('\n');
		   			tmpcnt=0;
		   			while(tmpcnt<cnt)
		   			{
			   			printf(" %.2X",(int)addr[tmpcnt++]);
			   		}
		   		}
	   		
		   	}

	   		putchar('\n');
   		
	   		break;
	   		
			// **** Time functions

	   	case 'Z': //reset the clock
	   	case 'z':
				t_1s=0;
	   		break;
				
	   	case 'C': //show the clock (the time since the last 'z')
	   	case 'c':
			  	{
				  	//read t_1s only on time because it could change during calculations
			   	unsigned long now=t_1s;
					printf("\r%.5d sec",(int)now);
	   		}
   			break;
   	
			// **** Misc. functions
			
	   	case 'E': //toggle echo on SCI
	   	case 'e':
	   		Echo_ON=1-Echo_ON;
	   		break;
	   		
#if USE_IO
	   	case 'L': //write the LEDs value (could be done with 'wm...')
	   	case 'l':
	      	{
              unsigned char value = 0;            
		        value = readhex2();
	   		  writeIO(value);
	   		}
	   		break;
	   		
	   	case 'B': //read the buttons value (could be done with 'rm...')
	   	case 'b':
	   		printf("\n%.2X", (int)(readIO()) );
	   		break;
#endif	
   		
	   	default:
	   		//unknown command. print the help.
			  	printf("\n *** REva test program ***");
		   	printf("\n ");
#if USE_ANALOG
		   	printf("\nT: read temperature from sensor.");
		   	printf("\nP: read potentiometer percentage.");
		   	printf("\nI: read IN1 in mV.");
		   	printf("\nJ: read IN2 in mV.");
		   	printf("\nOxxxx: output on OUT in mV (4 decimal digits expected).");
#endif
		   	printf("\n ");
		   	printf("\nRRaaaacc: read RAM (4 hex digits for a, 2 for c).");
		   	printf("\nRFaaaacc: read FLASH (4 hex digits for a, 2 for c).");
#if USE_EEPROM
		   	printf("\nRE00aacc: read EEPROM (2 hex digits for a, 2 for c).");
#endif
		   	printf("\nWRaaaaccxxx...: write RAM (2 hex digits for every byte).");
#if USE_EEPROM
		   	printf("\nWE00aa0cxxx...: write EEPROM (2 hex digits for every byte).");
#endif
		   	printf("\n ");
		   	printf("\nZ: reset clock.");
		   	printf("\nC: display clock.");
		   	printf("\n ");
		   	printf("\nE: toggle echo on SCI.");
#if USE_IO
		   	printf("\nLxx: write on the LEDs port (2 hex digits expected).");
		   	printf("\nB: display the values of the buttons and switches.");
#endif
		   	printf("\n ");
		   	printf("\n ");
	   		break;
   	}

   }
   
   return 0;
}//end of main

