/*******************************************************************************
--------------------------------------------------------------------------------
*** TestAll example
  
 This example uses most peripherals of the ST72F321BJ6 and the REva board.
 Except the SPI, which would conflict with the ICC (debug) and the buttons.
 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.
 
--------------------------------------------------------------------------------
*** FILES

 The project has been initially generated by RBuilder, and then modified.
 The modified files, which you will be interested in, are:
  testallmain.c (this file) which contains the initializations and the main loop.
  revalib.c which contains utility functions for the REva.
  timerint.c which contains the timer interrupt service routine.
  
--------------------------------------------------------------------------------
*** DEBUG

 If you want to debug using ICC, you must disable the watchdog
  using the DEBUGICC macro.
 
--------------------------------------------------------------------------------
*** 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
 
 On the daughter board, select the RLink clock by setting the "DNG" jumper.
 
--------------------------------------------------------------------------------
*** POWER
 If you are not using the USB 5V as power, then you must change the value of the
  ALIMVOLTAGEMV macro to the real value of the power, in mV.
 
--------------------------------------------------------------------------------
********************************************************************************
--------------------------------------------------------------------------------

			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:           (initial version generated by RBuilder) */
/* Date:           12/2/2004 */
/* =========================================================================== */

#include "ST7lib_config.h"
#include <stdio.h>
#include <intrist7.h>
#include "timer.h"
#include "REvaLib.h"

//define DEBUGICC at 1 if you plan to debug using ICC
// this disables the watchdog and SPI
#define DEBUGICC 1
//#define DEBUGICC 0


/*---------------------------------------------------------------------------*/
/*Function:       PeriphInit*/
/*Purpose:        Periph configuration at RESET*/
/* Date:           12/2/2004 */
/*---------------------------------------------------------------------------*/
void PeriphInit ( void ) 
{
   /* A/D Converter initialization */
   ADC_Init(ADC_DEFAULT);
   ADC_Select_Channel(0);
   
   /* SCI initialization */
   SCI_Init(SCI_DEFAULT_PARAM1, SCI_DEFAULT_PARAM2);
   SCI_Select_Baudrate(0x0);
   SCIERPR =  0x27;  /* Set RX Baudrate (real= 9615)  */
   SCIETPR =  0x27;  /* Set TX Baudrate (real= 9615)  */
   SCI_Mode(SCI_TX_ENABLE|SCI_RX_ENABLE);
   
   /* I2C initialization */
   I2C_Init(I2C_ACK_ENABLE);
   I2CCCR = 0x88;    /* I2C Clock configuration */
   
   /* PWM Auto Reload Timer inialization */
   PWMART_Init(PWMART_DEFAULT);
   PWMART_Counter_Enable(PWMART_REG_CAR, 0, PWMART_CLK_16);
   
   /* 16-bit timers initialization */
   TIMERA_Init(TIMER_FCPU_8);	   /* Timer A */
   TIMERA_IT_Enable(TIMER_OCMP_IT_ENABLE);
   
   /* Watch Dog initialization */
#if DEBUGICC
#define WDGREFRESH
#else
#define WDGREFRESH WDG_Refresh(0x64)
#endif
   WDGREFRESH;
   
   /* I/O Port initialization */
   IO_Init();
   IO_Input(IO_PULL_UP, IO_PORT_C, 0xaf);
   IO_Output(IO_OPEN_DRAIN, IO_PORT_F, 0xd7);

   EnableInterrupts;
   
}/*end of  PeriphInit*/

//this buffer is used for storing temp data (mainly from/to the EEPROM)
unsigned char mybuffer[0x100];


//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=getchar(); //read high weight nibble
	car1=readhex(car1); //convert in hex number
	
	car2=getchar(); //read low weight nibble
	car2=readhex(car2); //convert in hex number
	
	return ((car1<<4)+car2);
}

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

//this must equal the ST7's alimentation voltage in mV
#define ALIMVOLTAGEMV (4700)
//#define ALIMVOLTAGEMV (3330)

extern volatile unsigned long t_50ms;

/*---------------------------------------------------------------------------*/
/*Function:       main()*/
/*Purpose:        main routine*/
/* Date:           12/2/2004 */
/*---------------------------------------------------------------------------*/
void main ( void ) 
{
	
   /*Configure the internal peripherals*/
   PeriphInit();
   
   // start counter for clock
   TIMERA_OCMP_Mode(TIMER_OCMP_1,0x8000,TIMER_OUTPUT_F);

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

   while ( 1 )
   {
		char c;
		unsigned short addr;
		
		//display the prompt
	  	printf("\n>");
	  	
   	//read the command
   	c=getchar();
   	
   	// analyze and execute the command
   	switch(c)
   	{
			// **** Analogic functions
	   	
	   	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=getchar()-'0';
		   		c2=getchar()-'0';
		   		c3=getchar()-'0';
		   		c4=getchar()-'0';
		   		addr=(((((c1*10)+c2)*10)+c3)*10)+c4;
		   	}
	   		SetOUT(addr, ALIMVOLTAGEMV);
	   		break;
	   	
			// **** 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 short 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=getchar();
		   		
		   		//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)
		   		{
		   			case 'E':
		   				d='e';
		   			case 'e':
		   				addr=mybuffer;
		   				break;
		   			case 'M':
		   				d='m';
		   			case 'm':
		   				addr=(unsigned char *)(realaddr);
		   				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(d=='e')
							WriteEEPROM((unsigned char)(realaddr&0xFF), cnt, addr);
		   		}
		   		else
		   		{
		   			//if reading...
		   			//read the values from the EEPROM if needed
			   		if(d=='e')
			   			ReadEEPROM((unsigned char)(realaddr&0xFF), cnt, addr);
		   			
		   			//display the values
			   		putchar('\n');
		   			tmpcnt=0;
		   			while(tmpcnt<cnt)
		   			{
			   			printf(" %02X",(int)addr[tmpcnt++]);
			   		}
		   		}
	   		
		   	}

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

	   	case 'Z': //reset the clock
	   	case 'z':
				t_50ms=0;
	   		break;
				
	   	case 'C': //show the clock (the time since the last 'z')
	   	case 'c':
			  	{
				  	//read t_50ms only on time because it could change during calculations
			   	unsigned long now=t_50ms;
					printf("\r%02d:%02d:%02d",
						(int)(now/72000),(int)((now/1200)%60),(int)((now/20)%60));
	   		}
   			break;
   	
			// **** Misc. functions
			
	   	case 'D': //test watchdog
	   	case 'd':
	   		c=' ';
	   		//this infinite loop does not refresh the watchdog.
	   		// therefore, the wdg will reset the device
	   		// a short time after this loop starts executing!
	   		//when debugging, you can use this to test breakpoints and STOP,
	   		// but not the watchdog because it makes the debugger crash.
	   		while(1)
	   			putchar(c++);
	   		break;
	   	
	   	case 'E': //toggle echo on SCI
	   	case 'e':
	   		Echo_ON=1-Echo_ON;
	   		break;
	   		
	   	case 'L': //write the LEDs value (could be done with 'wm...')
	   	case 'l':
	   		IO_ByteWrite(IO_PORT_F, readhex2());
	   		break;
	   		
	   	case 'B': //read the buttons value (could be done with 'rm...')
	   	case 'b':
	   		printf("\n%02X", (int)(IO_Read(IO_PORT_C)) );
	   		break;
	   		
	   	default:
	   		//unknown command. print the help.
			  	printf("\n *** REva test program ***");
		   	printf("\n");
		   	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).");
		   	printf("\n");
		   	printf("\nRMaaaacc: read memory (4 hex digits for a, 2 for c).");
		   	printf("\nRE00aacc: read EEPROM (2 hex digits for a, 2 for c).");
		   	printf("\nWMaaaaccxxx...: write memory (2 hex digits for every byte).");
		   	printf("\nWE00aaccxxx...: write EEPROM (2 hex digits for every byte).");
		   	printf("\n");
		   	printf("\nZ: reset clock.");
		   	printf("\nC: display clock.");
		   	printf("\n");
		   	printf("\nD: test watchdog.");
		   	printf("\nE: toggle echo on SCI.");
		   	printf("\nLxx: write on the LEDs port (2 hex digits expected).");
		   	printf("\nB: display the values of the buttons and switches.");
		   	printf("\n");
		   	printf("\n");
	   		break;
   	}

   }
}/*end of main*/


#if 1
/*---------------------------------------------------------------------------*/
/*Function:       putchar*/
/*Purpose:        Putchar in polling mode on SCI*/
/* Date:           12/2/2004 */
/*---------------------------------------------------------------------------*/
int putchar(char c)
{
   if (c == '\n')
   {
      SCI_PutByte ('\r');
      while (!SCI_IsTransmitCompleted()) WDGREFRESH;
   }
   SCI_PutByte (c);
   while (!SCI_IsTransmitCompleted()) WDGREFRESH;
   return ((int)c);
}

/*---------------------------------------------------------------------------*/
/*Function:       getchar*/
/*Purpose:        Getchar in polling mode on SCI*/
/* Date:           12/2/2004 */
/*---------------------------------------------------------------------------*/
int getchar(void)
{
   unsigned char c;
   while(SCI_IsReceptionCompleted()!=SCI_RECEIVE_OK) WDGREFRESH;
   c = SCI_GetByte();
   if(Echo_ON) putchar(c); //echo
   return((int)c);
}


#endif

