/******************************************************************************
//	init_main.c				Persistor and PicoDOS starter C file  
//	
//*****************************************************************************
//	
//	Apr2011, used to initialize CF2 EEPROM and MSP430 modules.
//  Used to do calibration of MSP430 sensors
//
//	
//*****************************************************************************
//
//==== Future Expansion =======================================================
//		last update:  
//
*******************************************************************************/

#include	<cfxbios.h>		// Persistor BIOS and I/O Definitions
#include	<cfxpico.h>		// Persistor PicoDOS Definitions

#include	<assert.h>
#include	<ctype.h>
#include	<errno.h>
#include	<float.h>
#include	<limits.h>
#include	<locale.h>
#include	<math.h>
#include	<setjmp.h>
#include	<signal.h>
#include	<stdarg.h>
#include	<stddef.h>
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<time.h>


#include    "cf2_qsm332.h"
#include    "spi_cmd.h"
#include    "tcm2.h"
#include    "pitch_roll.h"
#include    "gpio_mux.h"
#include    "pump.h"
#include    "dat_fnx.h"
#include    "gps.h"
#include    "nav.h"
#include    "sbd.h"
#include    "adp.h"
#include    "ntk.h"
#include    "sbe.h"
#include    "lifo.h"
#include    "setup.h"


// definitions ----------------------------------------------------------------
#define	SCI_BAUD	9600L				// whatever is appropriate
// system clock is HIGH_CLOCK_SPEED defined in setup.h
#define	WTMODE		nsStdSmallBusAdj	// choose: nsMotoSpecAdj or nsStdSmallBusAdj
#define SCIWAIT		900					// # of milli-secs to wait btwn char before timeout

// globals --------------------------------------------------------------------
char Verbose  =0; // for diagnostics, can turn on/off more info
char IRQ_Flag =0; // flag, whose value determines what caused the interrupt
struct all_param     all;
short iparam [ MAX_PARAM ]; // global parameter settings MAX_PARAM

// prototypes -----------------------------------------------------------------
void     main_menu      ( void    );
void     set_vac_off    ( void    );
void     set_V14_gain   ( void    );
void     set_V07_gain   ( void    );
void     set_prV_gain   ( void    );
void     set_prI_gain   ( void    );


IEV_C_PROTO   ( Spur_ISR  );	// interrupt service routine prototype
IEV_C_PROTO   ( Irq2_ISR  );	// interrupt service routine prototype
IEV_C_PROTO   ( Irq4_ISR  );	// interrupt service routine prototype
//define others to safeguard
IEV_C_PROTO   ( Irq3_ISR  );
IEV_C_PROTO   ( Irq5_ISR  );
IEV_C_PROTO   ( Irq7_ISR  );
IEV_C_PROTO   ( Div0_ISR  );


/******************************************************************************\
**	main
\******************************************************************************/
int main(int argc, char **argv)
	{
	short	i, done, err;
	short	result = 0, tmo;
	char ch;
	struct spi_param     ss1;   // struct for spi comms
	struct time_param    ti;    // struct for timing of various events
	struct compass_param compass; // struct with compass parameters
	struct gps_param     gps;     // struct with gps parameters
	struct sbd_param     sbd;     // struct with Iridium SBD parameters
	struct lifo_param    lifo;    // struct with LIFO parameters
	struct flight_param  flight;  // flight params
	//struct miss_param    mis;     // struct with the mission parameters
	struct except_param  exc;     // exception parameter list
	struct eng_param     eng;     // engineering parameter list
	struct drift_param   drift;   // drift parameters
	struct hyd_param     hyd;     // hydraulics params
	struct dat_param     dat;     // daq/processing params
	struct adp_param     adp;     // adp parameters
	struct motor_stat    mot;     // motor stats for last op
	struct ublox_param   ubx;     // ublox gps positions, for surface drift
	struct pwr_param     pwr;     // power #'s for pitch, roll & hyd
	struct nav_param     nav;     // nav parameters
	struct route_param   rte;     // route parameters
	struct pp_daq         pp;     // mar11, polyplus daq struct
	
	// TUChParams    tuart_cfg;
	
	struct tpu_uart tu_port[N_TU_PORTS] = {
	     FROM_SAT , TO_SAT , BAUD_SAT , 0,
	     FROM_MUX1, TO_MUX1, BAUD_MUX1, 0,
	     FROM_MUX2, TO_MUX2, BAUD_MUX2, 0, 
	     FROM_SBE,  TO_SBE,  BAUD_SBE,  0 }; // 4 TPU uart ports, defined as above

	CSSetSysAccessSpeeds(nsFlashStd, nsRAMStd, nsCFStd, WTMODE);
	TMGSetSpeed(HIGH_CLOCK_SPEED);
	SCIConfigure(SCI_BAUD, 'N', true);
	SCIRxSetBuffered(true);		// enable the built-in 2k-word buffer
	init_pins(); // initialize the pins for other tasks

//	INITIALIZE THE TPU UART MODULE
	TUInit(calloc, free);		// give TU manager access to our heap

	// Identify the progam and build
	cprintf("\nProgram: %s: %s %s \n", __FILE__, __DATE__, __TIME__);
	// Identify the device and its firmware
	cprintf("Persistor  CF%d SN:%ld   BIOS:%d.%02d   PicoDOS:%d.%02d\n", CFX,
		BIOSGVT.CFxSerNum, BIOSGVT.BIOSVersion, BIOSGVT.BIOSRelease, 
		BIOSGVT.PICOVersion, BIOSGVT.PICORelease);
	/* Identify the arguments */
	cprintf("\n%d Arguments:\n", argc);
	for (i = 0; i < argc; i++)
		cprintf("  argv[%d] = \"%s\"\n", i, argv[i]);
		/**/
		
//i = sizeof(nav); cprintf("size of nav_param  = %d\n", i );
//i = sizeof(lifo);cprintf("size of lifo_param = %d\n", i );
//i = sizeof(dat); cprintf("size of dat_param  = %d\n", i );
	
//
//	Install handlers for the interrupts we want to catch
//
	// IEVInsertAsmFunct (  Irq4RxISR, level4InterruptAutovector); //R
	// IEVInsertAsmFunct (  Irq4RxISR, spuriousInterrupt);
	IEVInsertCFunct   ( &Irq2_ISR,  level2InterruptAutovector);
	IEVInsertCFunct   ( &Irq4_ISR,  level4InterruptAutovector);
	IEVInsertCFunct   ( &Spur_ISR,  spuriousInterrupt        );
	// define others
	IEVInsertCFunct   ( &Irq3_ISR,  level3InterruptAutovector);
	IEVInsertCFunct   ( &Irq5_ISR,  level5InterruptAutovector);
	IEVInsertCFunct   ( &Irq7_ISR,  level7InterruptAutovector);
	IEVInsertCFunct   ( &Div0_ISR,  zeroDivision );


	TMGSetupCLKOUTPin(false, false);
	SCITxWaitCompletion();
	PITSet51msPeriod(PITOff);	// disable timer (drops power)

	
	LEDInit();
	PITAddChore(hibernate_task,3);  // empty chore for PIT
	
	// initialize the TPU serial ports
	all.tu_port = tu_port; // set all.tu_port address same as the local
	for (i=0;i<N_TU_PORTS; i++) //iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
	{
	  tu_port[i].tup = 
	     TUOpen( tu_port[i].rxch, tu_port[i].txch, tu_port[i].baud, 0);
       cprintf("    TUP: %lX    RX: %2u    TX: %2u    BAUD: %6lu\n",
			tu_port[i].tup, tu_port[i].rxch, 
			tu_port[i].txch, tu_port[i].baud);
	  if (tu_port[i].tup == 0 )
	  { //ERROR!!
	    cprintf("TPU UART OPEN ERROR, port#=%d\n",i);
	    return 0;
	  }
	} //iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
	
	//=== allocate memory for various buffers =========================
    err = alloc_lifo(&lifo);  // allocate memory  for lifo
    if (err) 
    { cprintf("alloc_lifo err %d\n",err); return(0); } // abort if bad
    
    err = alloc_dat_ram(&dat);  // allocate memory  for data
    if (err) 
    { cprintf("alloc_dat err %d\n", err); return(0); } // abort if bad

    #if ADP==1 || NTK==1  // if ADP float,
       adp_alloc(&adp); // allocate memory for ADP
    #endif


	// assign rest of 'all' structure =================================
	all.sspi = &ss1;     // spi comms structure
	all.time = &ti;      // UX time of various events
	all.comp = &compass; // compass structure
	all.gps  = &gps;     // gps structure
	all.sbd  = &sbd;     // sbd iridium structure
	all.lifo = &lifo;    // lifo area
	all.flt  = &flight;  // flight params
	//all.mis  = &mis;     // mission parameters
	all.exc  = &exc;     // exception parameters
	all.eng  = &eng;     // engineering params
	all.drift= &drift;   // drift params
	all.hyd  = &hyd;     // hydraulic params
	all.dat  = &dat;     // data params
	all.adp  = &adp;     // adp params
	all.mot  = &mot;     // motor statistics
	all.ubx  = &ubx;     // ublox params
	all.pwr  = &pwr;     // power #'s for hyd, pitch and roll
	all.nav  = &nav;     // point to the nav struct
	nav.route= &rte;     // point to the route in the nav.
	all.pp   = &pp;      // mar11, point to the polyplus struct.
	
	// initialize parameters ==========================================
	init_all (); // initialize params in all, independent of op_mode
    clear_lifo_stat(all.lifo); // reset status of old messages but don't erase
    init_sensors();
    dat.i = 0; // reset the data buffer area to index=0
    all.exc->n_reset  = 0;  // no spurious resets yet
    all.exc->exc_stat = 0; // zero out the exception status
    all.time->ti0 = RTCGetTime ( 0, 0 );  // UX time for this dive
    all.time->ti_cyc = all.time->ti0; // UX time for this cycle
    
    
    //---following will set up eeprom parameters, even if 
    //---they have not been defined before
    VEEStoreLong( "OPMODE", 0L );
    //set_op_mode(0); // put in normal operation-mode = user mode

    set_default_param(); // initialize the parameter array
    
  
	// initialize the SPI and start up the watchdog ===================
    spi_set_wdog( 1, 255 );
	init_gpio_iparam();
    cprintf("Do you want to reset GPIO flash to default (y/n)? >\n");
    if (YesNo() ) gp_set_default ( );

    // initialize the pitch module
    if ( init_pr_iparam ( CS_PITCH ) == 0 )
    { // pitch module is responding
      cprintf("Do you want to reset PITCH flash to default (y/n)? >\n");
      if (YesNo() ) pr_set_default ( all.sspi );
    }
    
    // initialize the roll module
    if ( init_pr_iparam ( CS_ROLL ) == 0 )
    { // roll module is responding
      cprintf("Do you want to reset ROLL flash to default (y/n)? >\n");
      if (YesNo() ) pr_set_default ( all.sspi );
    }
	
    // initialize the hydraulic module
    if ( init_hyd_iparam () == 0 )
    { // hydraulic module is responding
      cprintf("Do you want to reset HYDRAULIC flash to default (y/n)? >\n");
      if (YesNo() ) hyd_set_default ( );
    }
	
	main_menu();
	
	done = false;
	tmo = 0;
	while (!done) //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	{  //cycle until we get a quit command


	    EIAEnableRx(1);
		SerInFlush(); // delete old anything in the buffer
        if (ch !=' ' && ch>0 ) cprintf("   BAS>\n"); // display directory prompt
	    ch = -1;  //illegal input char
	    ch = SCIRxGetCharWithTimeout(1000 ); // get a character
	    tmo = check_tmo ( &ch, tmo );
	    // increments the tmo counter if ch<0, and
	    // goes to sleep mode after max_tmo.  Returns *ch as upper-case
	    
	    switch(ch) //====================================================
	    { // and depending upon the ch, do the appropriate action =======
	    
        case 0x1B : //ESC key , abort program
                   
                    cprintf("Do you really want to quit (y/n)? >\n");
                    if (YesNo() )
                      { done=1; } // set flag to quit
                    else { ch = ' ';} 
                    break;
                    
        case '?' :  break; // causes directory prompt to be displayed
        case ' ' :  break; // wait for another character
        case  -1 :  break; // wait for another character
	    case '+' :  toggle_verbose(); // toggle verbose mode
				    break;


	    case 'C' :  // go test compass module
	                test_compass ( );
				    break;
	   
	    case 'D' :  // test the dat_fnx module
	                daq_test ( );
				    break;
	   
	    case 'F' :  // go test compass module
	                flash_test (  );
				    break;
	   
	    case 'G' :  // go test compass module
	                test_gps (  );
				    break;
	   
	    case 'H' :  // go test the hydraulic module
	                test_hyd (  );
				    break;
	   
	    case 'I' :  // go test Iridium SBD
	                test_sbd (  );
				    break;

	    case 'L' :  // put into low-power mode
	                sleep_check ( STAY_LOWPWR, PIT_IRQ2_RXD, FALSE );
	                main_menu();
				    break;
	   
	    case 'M' :  // go test pitch and roll modules
	                test_pitch_roll (  );
				    break;

	    case 'P' :  // go test SBE CTD module
	                test_param ( );
				    break;
				    
        case 'U' :  main_menu(); 
                    break; // show the main menu

	    case 'V' :  // set vacuum to zero offset
	                set_vac_off ( );
				    break;
	    case 'W' :  // go test GPIO/MUX msp430
	                test_gpio (  );
				    break;
	    case '0' :  // reset the dive # and op_mode
	                set_surf_num ( 0 );
	                set_prof_num ( 0 ); //0902, include profile #
	                set_op_mode  ( 0 );
	                cprintf("Dive# and op_mode now = 0\n");
				    break;


	    case '1' :  // gain for the 14V input
	                set_V14_gain ( );
				    break;

	    case '2' :  // gain for the 7V input
	                set_V07_gain ( );
				    break;

	    case '3' :  // gain for pitch volts
	                set_prV_gain ( );
				    break;

	    //case '4' :  // gain for the 7V input
	    //            set_prI_gain ( );
		//		    break;

	    case '9' :  // hidden test
	                i = 99 / iparam[ IA_use_set ];
	                cprintf("I divide-by-zero = %d, flag = %d\n",i, IRQ_Flag );
				    break;



        default  :  cprintf(" input unknown \n");

	    } //==============================================================
	    
	  
	} // end while !done
	//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  
  cprintf("freeing memory\n");
  #if ADP==1 || NTK==1
    free( adp.buf);
  #endif
  free(lifo.buf  );
  free( dat.dat  );
  free( dat.eptr );
  // Various exit strategies
  //	BIOSReset();			// full hardware reset
  //	BIOSResetToPBM();		// full reset, but stay in Pesistor Boot Monitor
      BIOSResetToPicoDOS();	// full reset, but jump to 0xE10000 (PicoDOS)
	return result;

}	//____ main() ____//
//*****************************************************************************


void main_menu ( void )
{ //print out menu selections *************************************************
 cprintf("INIT MAIN MENU, compiled %s %s\n", __DATE__, __TIME__ );
 write_header ( NULL ); // display info
 if ( ADP) cprintf("  Acoustic Doppler Profiler, ");
 if ( NTK) cprintf("  Nortek AD2CP, ");
 if (ISUS) cprintf("  ISUS Nitrate Sensor,");
 if ( DOX) cprintf("  DOx Sensor,");
 cprintf("\n");
 if (DEBUG)  cprintf("********* in DEBUG mode !!! \n");
 cdrain(); // wait for the above to print
 cprintf("                         ESC Abort prog :  U.pdate menu \n"
         "     V.acuum Offset \n"
         "     1=calibrate 14V GPIO\n"
         "     2=calibrate 07V GPIO \n"
         "     3=calibrate PITCH Volts \n"
       //"     4=calibrate PITCH Amps \n"
       "\n     C.ompass          : Flash Test     :  G.PS module \n"
         "     H.ydraulics       : I.ridium SBD   :  \n"
         "     D.AQ test         : L.owpower         : M.otors Pitch&Roll\n"
         "     + Toggle Verbose  : W.atchdog, GPIO-MUX\n" 
         "     P.arameter Settings \n"
         "     0.Reset Dive#,op_mode\n");

 return;
} //***************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************





//***calibration routines *****************************************************

void set_vac_off ( void ) //***************************************************
{ // take bench readings and set the offset to this value
  short ival, k, n=10, m=0;
  long  vac =0;
  struct spi_param *ss;
  
  ss = all.sspi;
  setup_spi ( CS_GPIO, ss ); // re-init the SPI info
  
  cprintf("Taking %d vacuum samples \n", n);
  
  for (k=0;k<n;k++) //------------------------------------
  { // take the average
    ival = r_get_a2d ( CS_GPIO, AD_AUX_VAC ); // get the value
    cprintf("vac_cnts = %4d\n",ival);
    if (ival>0) 
    { vac += ival; m++; }
    DelayMilliSecs(200);
  } //----------------------------------------------------
  
  if (m>0) //=============================================
  { // valid
    vac = (vac + m/2)/ m; //round up
    ival = vac; // cast as short
    cprintf("Avg = %d \n", ival);
    cprintf("Set new offset to this value?\n");
    if (YesNo() )
    {
      spi_flash_write( F_G_VOFF,ival, ss ); 
      init_gpio_iparam(  ); //displays result
    } 
    // else stays the same
  } //====================================================
  else { cprintf("NO VALID readings taken\n"); }

  return;
} //***************************************************************************

void   set_V14_gain ( void ) //************************************************
{ // take bench readings and set the 14V gain
  short ival, k, n=10, m;
  long  v14 =0, v7=0;
  float f14, f7=0, gn;
  struct spi_param *ss;
  
  ss = all.sspi;
  setup_spi ( CS_GPIO, ss ); // re-init the SPI info
  
  printf("Taking %d V14 samples: SET V to 14.0 V \n", n);
  printf("Give the present input Voltage\n");
  scanf("%f",&f14);
  
  
  m=0;
  for (k=0;k<n;k++) //------------------------------------
  { // take the average
    ival = r_get_a2d ( CS_GPIO, AD_AUX_V_14 ); // get the value
    cprintf("v_cnts = %4d\n",ival);
    if (ival>0) 
    { v14 += ival; m++; }
    DelayMilliSecs(200);
  } //----------------------------------------------------
  
  if (m>0) //=============================================
  { // valid
    v14 = (v14 + m/2)/m; //round up
    printf("Avg cnts = %5ld at %5.2f V \n", v14, f14);
    // else stays the same
  } //====================================================
  else { cprintf("NO VALID readings taken\n"); }
  /* code assumes no offset, just use the 14V value
  
  cprintf("Taking %d V samples: SET V to 7.0 V \n", n);
  printf("Give the present input Voltage\n");
  scanf("%f",&f7);
  
  m =0;
  for (k=0;k<n;k++) //------------------------------------
  { // take the average
    ival = r_get_a2d ( CS_GPIO, AD_AUX_V_14 ); // get the value
    cprintf("v_cnts = %4d\n",ival);
    if (ival>0) 
    { v7 += ival; m++; }
    DelayMilliSecs(200);
  } //----------------------------------------------------
  
  if (m>0) //=============================================
  { // valid
    v7 = (v7 + m/2)/m; //round up
    printf("Avg cnts = %5ld at %5.2f V \n", v7, f7);
    // else stays the same
  } //====================================================
  else { cprintf("NO VALID readings taken\n"); }
  
  gn = ( f14 - f7 )/ (v14 - v7);  // volts/cnt
  */
  gn = f14/v14;
  gn = gn*10000 + 0.5;  // gn*cnts 
  ival = gn;  // nearest integer

  if (ival>0) //==========================================
  { // valid
    cprintf("New gain = %d \n", ival);
    cprintf("Set V14 gain to this value?\n");
    if (YesNo() )
    {
      spi_flash_write( F_G_C2U_V14,ival, ss ); 
      init_gpio_iparam(  ); //displays result
    } 
    // else stays the same
  } //====================================================
  else { cprintf("Gain was not valid = %d\n", ival); }

  return;
} //***************************************************************************


void   set_V07_gain ( void ) //************************************************
{ // take bench readings and set the 7V gain
  short ival, k, n=10, m;
  long  v7 =0, v5=0;
  float f7, f5=0, gn;
  struct spi_param *ss;
  
  ss = all.sspi;
  setup_spi ( CS_GPIO, ss ); // re-init the SPI info
  
  printf("Taking %d V074 samples: SET V to 7.0 V \n", n);
  printf("Give the present input Voltage\n");
  scanf("%f",&f7);
  
  
  m=0;
  for (k=0;k<n;k++) //------------------------------------
  { // take the average
    ival = r_get_a2d ( CS_GPIO, AD_AUX_V_07 ); // get the value
    cprintf("v_cnts = %4d\n",ival);
    if (ival>0) 
    { v7 += ival; m++; }
    DelayMilliSecs(200);
  } //----------------------------------------------------
  
  if (m>0) //=============================================
  { // valid
    v7 = (v7 + m/2)/m; //round up
    printf("Avg cnts = %5ld at %5.2f V \n", v7, f7);
    // else stays the same
  } //====================================================
  else { cprintf("NO VALID readings taken\n"); }
  
  
  gn = f7/ v7 ;  // volts/cnt
  gn = gn*10000 + 0.5;  // gn*cnts 
  ival = gn;  // nearest integer

  if (ival>0) //==========================================
  { // valid
    cprintf("New gain = %d \n", ival);
    cprintf("Set V07 gain to this value?\n");
    if (YesNo() )
    {
      spi_flash_write( F_G_C2U_V07,ival, ss ); 
      init_gpio_iparam(  ); //displays result
    } 
    // else stays the same
  } //====================================================
  else { cprintf("Gain was not valid = %d\n", ival); }

  return;
} //***************************************************************************

void   set_prV_gain ( void ) //************************************************
{ // take bench readings and set the pitch/roll module V gain
  short ival, k, n=10, m;
  long  v7 =0, v5=0;
  float f7, f5=0, gn;
  struct spi_param *ss;
  
  ss = all.sspi;
  setup_spi ( CS_PITCH, ss ); // re-init the SPI info
  
  printf("Taking %d V samples of Pitch module: SET V to 14.0 V \n", n);
  printf("Give the present input Voltage\n");
  scanf("%f",&f7);
  
  
  m=0;
  for (k=0;k<n;k++) //------------------------------------
  { // take the average
    ival =  r_get_a2d ( CS_PITCH, AD_VOLT ); // get the value
    cprintf("v_cnts = %4d\n",ival);
    if (ival>0) 
    { v7 += ival; m++; }
    DelayMilliSecs(200);
  } //----------------------------------------------------
  
  if (m>0) //=============================================
  { // valid
    v7 = (v7 + m/2)/m; //round up
    printf("Avg cnts = %5ld at %5.2f V \n", v7, f7);
    // else stays the same
  } //====================================================
  else { cprintf("NO VALID readings taken\n"); }
  
  
  gn = f7/ v7 ;  // volts/cnt
  gn = gn*10000 + 0.5;  // gn*cnts 
  ival = gn;  // nearest integer

  if (ival>0) //==========================================
  { // valid
    cprintf("New gain = %d \n", ival);
    cprintf("Set V gain to this value?\n");
    if (YesNo() )
    {
      spi_flash_write( F_C2U_V,ival, ss ); 
      init_pr_iparam( CS_PITCH ); //displays result
    } 
    // else stays the same
  } //====================================================
  else { cprintf("Gain was not valid = %d\n", ival); }

  return;
} //***************************************************************************


/*NO - can't be done on the bench, as motor controller only allows the motor
// on if pot counts is believable ---------------
void   set_prI_gain ( void ) //************************************************
{ // take bench readings and set the pitch/roll module I gain
  short ival, k, n=10, m, ch;
  long  amps =0 ;
  float ma, gn;
  struct spi_param *ss;
  
  ss = all.sspi;
  setup_spi ( CS_PITCH, ss ); // re-init the SPI info
  ival = spi_cmd_ver  ( CS_PITCH );
  display_ver ();
  
  printf("Taking %d Current samples of Pitch module: SET V to 12.0 V \n", n);
  printf("!!!This runs the motor, disregarding the pot counts. Bench Test ONLY\n");
  printf("Add load to simulate motor:\n");
  printf("   hook-up wires at J4 to amp-meter to 200-ohm load\n");
  printf("Turning on the motor circuit....\n");
  printf("MONITOR THE CURRENT WHILE THE CIRCUIT IS ON\n");
  send_p_r_run  ( CS_PITCH, 0,  1000 )  ;
  printf("input a char when ready to start the averaging\n");
  ch = SCIRxGetChar ( );
  
  m=0;
  for (k=0;k<n;k++) //------------------------------------
  { // take the average
    ival =  r_get_a2d ( CS_PITCH, AD_AMPS ); // get the value
    cprintf("v_cnts = %4d\n",ival);
    if (ival>0) 
    { amps += ival; m++; }
    DelayMilliSecs(200);
  } //----------------------------------------------------
  xfr_SPI_byte( CS_PITCH, SPI_STOP );  // turn off!
  
  if (m>0) //=============================================
  { // valid
    amps = (amps + m/2)/m; //round up
    printf("Give the average current (ma) \n");
    scanf("%f",&ma);
    printf("Avg cnts = %5ld at %5.2f mA \n", amps, ma);
    // else stays the same
  } //====================================================
  else { cprintf("NO VALID readings taken\n"); }
  
  
  gn = ma/ amps;  // volts/cnt
  gn = gn*10000 + 0.5;  // gn*cnts 
  ival = gn;  // nearest integer

  if (ival>0) //==========================================
  { // valid
    cprintf("New gain = %d \n", ival);
    cprintf("Set I gain to this value?\n");
    if (YesNo() )
    {
      spi_flash_write( F_C2U_I,ival, ss ); 
      init_pr_iparam( CS_PITCH ); //displays result
    } 
    // else stays the same
  } //====================================================
  else { cprintf("Gain was not valid = %d\n", ival); }

  return;
} //***************************************************************************

*/






//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*** Interrupt Service Routines
//*****************************************************************************

/******************************************************************************\
**	Spur_ISR			Interrupt handler for Spurious interrupt
\******************************************************************************/
IEV_C_FUNCT( Spur_ISR )
{	// ISR when a spurious interrupt 
	#pragma unused(ievstack)
    IRQ_Flag = SPUR_F; // set global flag that RxD occurred
	// RTE(); this is added by the IEV_C_FUNCT
} //***************************************************************************

/******************************************************************************\
**	Irq4_ISR			Interrupt handler for IRQ4 = rs232 RxD detected
\******************************************************************************/
IEV_C_FUNCT( Irq4_ISR )
{	// ISR when IRQ4 = rs232 RxD is detected
	#pragma unused(ievstack)
    IRQ_Flag = IRQ4_F; // set global flag that RxD occurred
	PinIO(IRQ4RXD);		// making it an input turns off ISR
	// RTE(); this is added by the IEV_C_FUNCT
} //***************************************************************************



/******************************************************************************\
**	Irq2_ISR			Interrupt handler for IRQ2 (tied to GPIO msp430)
\******************************************************************************/
IEV_C_FUNCT( Irq2_ISR )
{	
	#pragma unused(ievstack)
    IRQ_Flag = IRQ2_F; // set global flag that RxD occurred
	PinIO(IRQ2);		// making it an input turns off ISR

	// RTE(); this is added by the IEV_C_FUNCT
} //***************************************************************************



/******************************************************************************\
**	Irq3_ISR			Interrupt handler for IRQ3
\******************************************************************************/
IEV_C_FUNCT( Irq3_ISR )
{	// ISR when a spurious interrupt 
	#pragma unused(ievstack)
    IRQ_Flag = IRQ3_F; // set global flag that RxD occurred
	// RTE(); this is added by the IEV_C_FUNCT
} //***************************************************************************


/******************************************************************************\
**	Irq5_ISR			Interrupt handler for IRQ5
\******************************************************************************/
IEV_C_FUNCT( Irq5_ISR )
{	// ISR when a spurious interrupt 
	#pragma unused(ievstack)
    IRQ_Flag = IRQ5_F; // set global flag that RxD occurred
	// RTE(); this is added by the IEV_C_FUNCT
} //***************************************************************************

/******************************************************************************\
**	Irq7_ISR			Interrupt handler for IRQ7
\******************************************************************************/
IEV_C_FUNCT( Irq7_ISR )
{	// ISR when a spurious interrupt 
	#pragma unused(ievstack)
    IRQ_Flag = IRQ7_F; // set global flag that RxD occurred
	// RTE(); this is added by the IEV_C_FUNCT
} //***************************************************************************

/******************************************************************************\
**	zeroDivision			Interrupt handler for divide-by-zero
\******************************************************************************/
IEV_C_FUNCT( Div0_ISR )
{	// ISR when a divide-by-zero 
	#pragma unused(ievstack)
    IRQ_Flag = DIV0_F; // set global flag that divide-by-zero occurred
    all.exc->exc_stat |= 0x8000;   // flag that it is a divide-by-zero
	// RTE(); this is added by the IEV_C_FUNCT
} //***************************************************************************


