/* =========================================================================== */
/* Project:        TestAll */
/* File:           TestAllmain.c */
/* Organization:    */
/* Author:           (initial version generated by RBuilder) */
/* Date:           3/8/2006 */
/* =========================================================================== */

#include "ST7lib_config.h"
#include <stdio.h>

#define DEBUG 0

#include <intrins.h>
#if DEBUG 
#define Breakpoint {_trap_();}
#else
#define Breakpoint
#endif
#define Nop {_nop_();}

#include "REvaLib.h"

#define getchar _getchar
char getchar(void);


/* --------------------------------------------------------------------------- */
/* Function:       PeriphInit */
/* Purpose:        Periph configuration at RESET */
/* Date:           3/8/2006 */
/* --------------------------------------------------------------------------- */
void PeriphInit ( void ) {
   
   /* A/D Converter initialization */
   ADC_Init(ADC_DEFAULT);
   ADC_Select_Channel(1);
  
   /* 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);
 
   /* 16-bit timers initialization */
   TIMERA_Init(TIMER_FCPU_8);   /* Timer A */
   TIMERA_IT_Enable(TIMER_OCMP_IT_ENABLE);

   /* PWM Auto Reload Timer inialization */
   //#ifndef _RAISONANCE_
   PWMART_Init(PWMART_DEFAULT);
   PWMART_Counter_Enable(PWMART_REG_CAR, 0xff, PWMART_CLK_16);
   //#endif
   /* Watch Dog initialization */
#if DEBUG 
#define WDGREFRESH 
#else
#define WDGREFRESH WDG_Refresh(0x64)
#endif

   WDGREFRESH;

   
   /* I/O Port initialization */
   IO_Init();
   IO_Input(IO_PULL_UP_IT, IO_PORT_A, 0x55);
   IO_Input(IO_PULL_UP_IT, IO_PORT_B, 0x5);
   IO_Output(IO_OPEN_DRAIN, IO_PORT_F, 0xff);
   EICR0 = 0xAA;

   EnableInterrupts;

}/* end of  PeriphInit */



// interrupt routine
volatile int itcnt=0;
void buttons_ISR() trap
{
	itcnt++;
}



//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 ) 
{
Breakpoint;
Nop;

   /*Configure the internal peripherals*/
   PeriphInit();
   
   // start counter for clock
   TIMERA_OCMP_Mode(TIMER_OCMP_1,0x8000,TIMER_OUTPUT_F);

  	printf("\n *** REva test program ***");
  	
Breakpoint;
Nop;
   while ( 1 )
   {
		char c;
		//unsigned char cnt, tmpcnt;
		unsigned short addr;
		
		//display the prompt
	  	printf("\n>");
	  	
   	//read the command
   	c=getchar();
   	
Breakpoint;
Nop;
   	// 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=(unsigned short)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();
		   		
		   		//Directly the code/RAM space
		   		switch(d)
		   		{
		   			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();
		   		}
		   		else
		   		{
		   			//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':
	   		{
		   		unsigned char rdval;
		   		int z;
					//buttons on port B
		   		rdval = IO_Read(IO_PORT_B);
		   		for (z=1; z>=0; z--)
		   			{
		   			printf("\nBT%d: ", z+5 );
		   			printf("\t%s", ((rdval>>(2*z)) & 0x01)?"OFF":"ON" );
		   			}
					//switches on port A
		   		rdval = IO_Read(IO_PORT_A);
		   		for (z=3; z>=0; z--)
		   			{
		   			printf("\nSW%d: ", z+1 );
		   			printf("\t%s", ((rdval>>(2*z)) & 0x01)?"OFF":"ON" );
		   			}
	   		}
	   		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("\nWMaaaaccxxx...: write memory (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*/

/*---------------------------------------------------------------------------*/
/*Function:       putchar*/
/*Purpose:        Putchar in polling mode on SCI*/
/* Date:           12/2/2004 */
/*---------------------------------------------------------------------------*/
int putchar(/*unsigned*/ 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 */
/*---------------------------------------------------------------------------*/


char getchar(void)
{
   unsigned char c;
   while(SCI_IsReceptionCompleted()!=SCI_RECEIVE_OK) WDGREFRESH;
   c = SCI_GetByte();
   if(Echo_ON) putchar(c); //echo
   return(c);
}

