/*
Title: Docking Payload C source for FAU OE AUV Dept. 
File: DockingPayload.C
Date:     Rev.   Description
8/30/04    A     Initial code from FAU
5/22/06    B     Changed startup mode to 3 and added ADCValidData Variable

*/

#include <p18f452.h>  	/* for the special function register declarations */
#include <usart.h> 		/* for Serial port UART*/
#include <portb.h>   	/* for the RB0/INT0 interrupt */
#include <timers.h>  	/* for delays*/
#include <string.h> 	/* for serial port command etc*/
#include <adc.h> 		/* for Health and Powerout monitoring */
#include <spi.h> 		/* for RTC and DAC */
//#include <dockPay.h>	/* Docking Payload include file*/
#include "dockPay.h"	/* Docking Payload include file*/
#include <stdlib.h>		/* foData conversions*/

/****************** Top function protypes ***********************/ 
void IntHighNotUsed 	(void);  	/* prototype needed for high interrupt 'goto'*/
void Initialize 		(void); 	/* prototype for Initialize function */
void ReadAllInputs 		(void); 	/* prototype of function for reading all inputs  */
void CommunicationMan	(void); 	/* prototype of function for Communication Manager */
void DetermineMode 		(void); 	/* prototype of function for Determining the Mode  */
void DetermineOutput 	(void); 	/* prototype of function for Determining outputs  */
void WriteAllOutput 	(void); 	/* prototype of function to write to all outputs */ 

/****************** Function protypes ***********************/ 
void ReadStrTimeOut	(char);			/*Read a string form the USART, return nul if time out*/
									/*Pass a w to wait for a string to start*/
									/*and any other char to exit if USART not ready*/



/*********************** Input Data *****************************/
char 			InCommand[3]; 	/* Command from Serial Port */
char			InData[22];		/* command Data */
char			InVolts[5];		/* Data from SV command*/
char			InCurrent[5];	/* Data from SV command*/
char			InString[22];	/*Data string from USART */
unsigned int 	V_UnReg;		/*Unregulated Voltage 0-102.4V FS, 0.1V per count*/
unsigned int 	V_PwrOut;		/*PwrOut Voltage 0-102.4V FS, 0.1V per count*/
unsigned int 	I_Load_40mA;	/*Load Current 0 to 40.96A FS, 40mA per count*/  
unsigned int 	I_Load_10mA;	/*Load Current 0 to 10.24A FS, 10mA per count*/
unsigned int 	Leak_Count;		/*Leak Voltage < 512 counts = Leak*/
int				Amb_Temp;		/*Temperture   0.5156 Deg. C per count and 0 Deg.C = = 131.5 Counts */ 
unsigned int 	V_Payload;		/*Payload Input Voltage 0-102.4V FS, 0.1V per count*/
char			One_Sec_Tick;		/*one Second tick from RTC*/




/*********************** Control Data *****************************/
char 			Mode; 			/* Docking Payload operational Mode */
								/* mission = 0*/
								/* homing = 1*/
								/* docking = 2*/
								/* docked-nocharge = 3*/
								/* docked-charge = 4*/
								/* failed-docked = 5*/
								/* failed-nondocked = 6*/
char			OldMode;		/* Old Value */
char			NewCommand;		/* Flag for new command = 1*/							
char			NewMode;		/* Flag for new mode = 1*/
char			ChargingError;	/* Flag for Charge error, 1 = error */
char			NewSetPoint;	/* Voltage  & Current set point for 1KW output*/
char			ADCDataValid;	/* Flag for valid ADC data */
char			ErrorFlag;
char 			X;
unsigned long int	Y;

/********************* 1KW DAC Setpoint Variables **********************/ 
union	HiLoByteInt 			/* For Int to High and Low byte to DAC*/	
	{
		int	Setpoint;
		char HiLoByte[2];
	};

union HiLoByteInt  SetPtV;
union HiLoByteInt  SetPtC;

#define SetPtVolts SetPtV.Setpoint			/*DAC Set point Voltage 20mV per count*/
#define LoSetPtVolts SetPtV.HiLoByte[0]
#define HiSetPtVolts SetPtV.HiLoByte[1]

#define SetPtCurrent SetPtC.Setpoint		/* DAC Setpoint Current 10mA per count*/
#define LoSetPtCurrent SetPtC.HiLoByte[0]
#define HiSetPtCurrent SetPtC.HiLoByte[1]




/******************* Temp Variables  *********************************/
unsigned char 	TempChar ; 	/*Char not used*/


/********************************** Interrupt Vectors ******************************/

/* High interrupts Vector at address 0x8. Not used at this time*/
#pragma code HIGH_INTERRUPT_VECTOR = 0x8  
void high_ISR (void) 
{
_asm goto IntHighNotUsed _endasm
}


/************************************************************************************/
/****************************** Start of Program Code *******************************/
/************************************************************************************/
#pragma code  /* allow the linker to locate the remaining code */


/* If the buzzer is on, turn it off.  If it is off, turn it on.*/
#pragma interrupt IntHighNotUsed
void IntHighNotUsed (void) 
{
   /* add code here*/
	INTCONbits.INT0IF = 0;         /* clear flag to avoid another interrupt */
}

/*** Use only if High interrupts are needed***/
void EnableHighInterrupts (void)
{
	RCONbits.IPEN = 1;    /* enable interrupt priority levels */
	INTCONbits.GIEH = 1;  /* enable all high priority interrupts */
}

/************************************************************************************/
/************************************ Start of Main code ****************************/
/************************************************************************************/
void main (void) 
{
	Initialize( );
	while (1)
	{
	ReadAllInputs();

	CommunicationMan();

	DetermineMode(); 

	WriteAllOutput();

	}
}

/************************************************************************************/ 
/****************************** Initialize Micro Routine *****************************/
/************************************************************************************/

void Initialize (void)
{
	/********************** Setup Ports and Peripherals ******************/

	/**** Port A Setup ****/
		TRISAbits.TRISA4 = 0; 	/*Make RA4 an output for FanOn control */
		FanOn = on;  			/* Turn fan on*/	

	/**** Port B Setup ****/
		ClosePORTB(); 			/*Disable all Interrupts and Pullups*/
		EnablePullups();		/* Enable PullUps on Port B inputs */
		TRISBbits.TRISB0 = 1; 	/*Make RB0 an input pin for RTC_INT test*/
		TRISBbits.TRISB1 = 1; 	/*Make RB1 an input pin for RS232_INT test*/
		TRISBbits.TRISB2 = 0; 	/*Make RB2 an output pin for RS232_CTR0 */
		RS232_CTR0 = 0;			/* Set control nib to AUV Mission */
		TRISBbits.TRISB4 = 0; 	/*Make RB4 an output pin for DAC_CS_L */
		DAC_CS_L = 1;  			/* deselect DAC */
		TRISBbits.TRISB5 = 0; 	/*Make RB5 an output pin for RS232_CTR1 */
		RS232_CTR1 = 0;			/* Set control nib to AUV Mission */
          
	/**** Port C Setup ****/
		TRISCbits.TRISC0 = 0; 	/*Make RC0 an output pin for SPI_RTC_CS */
		RTC_CS = 0;  			/* deselect RTC */
		TRISCbits.TRISC1 = 0; 	/*Make RC1 an output pin for RS232CTR2 */
		RS232CTR2 = 0;  		/* Set control nib to AUV Mission  */
		TRISCbits.TRISC2 = 0; 	/*Make RC1 an output pin for RS232CTR3 */
		RS232CTR3 = 0;  		/* Set control nib to AUV Mission  */

	/**** Port D Setup ****/
		TRISDbits.TRISD0 = 0; 	/*Make RD0 an output pin for PC104_ON */
		PC104_ON = on;  		/* Turn on power to PC104 */
		TRISDbits.TRISD1 = 0; 	/*Make RD1 an output pin for RF_ETHERNET_ON */
		RF_ETHERNET_ON = on;  	/* Turn on power to RF ETHERNET  */
		TRISDbits.TRISD2 = 0; 	/*Make RD2 an output pin for MOD_USBL_ON */
		MOD_USBL_ON = on;  		/* Turn on power to ACOUSTIC MODEM and USBL */
		TRISDbits.TRISD3 = 0; 	/*Make RD3 an output pin for RESOLVER_ON */
		RESOLVER_ON = off;  	/* Turn off power to RESOLVER */
		TRISDbits.TRISD6 = 0; 	/*Make RD6 an output pin for PWROUT */
		PWROUT = off;  			/* Disable 1KW power Output */
		TRISDbits.TRISD7 = 0; 	/*Make RD7 an output pin for PWROUT_L */
		PWROUT_L = 1;  			/* Disable 1KW power Output */

	/**** Setup USART, 9600 Baud ****/
	OpenUSART(	USART_TX_INT_OFF &
			USART_RX_INT_OFF &
			USART_ASYNCH_MODE &
			USART_EIGHT_BIT &
			USART_CONT_RX &
			USART_BRGH_HIGH,
			25				); 	

	/***** Setup Timer 0 *****/ 
	OpenTimer0(	TIMER_INT_OFF &
			T0_16BIT &
			T0_SOURCE_INT &
			T0_PS_1_256 ); /* 4MhZ xTAL = 1uSec * 256 = 256uSec per count = 16.777 Sec FS*/ 
			
	/****** Setup ADC ******/
	OpenADC(	ADC_FOSC_8 &  /* FOSC/8 FOR 4 MHz Xtal/8 = .5MHz = 2uS (ADC min. is 1.6uS)*/
			ADC_RIGHT_JUST &
			ADC_8ANA_0REF,
			ADC_CH0 &	/*Unregulated Voltage 0-102.4V FS, 0.1V per count*/
			ADC_CH1 &	/*PwrOut Voltage 0-102.4V FS, 0.1V per count*/
			ADC_CH2 &   /*Load Current 0 to 40.96A FS, 40mA per count*/  
			ADC_CH3 &	/*Load Current 0 to 10.24A FS, 10mA per count*/
			ADC_CH4 &	/*Leak Voltage < 512 counts = Leak*/
			ADC_CH5 &	/*Temperture   0.5156 Deg. C per count and 0 Deg.C = = 131.5 Counts */ 
			ADC_CH6 &	/*Spare */
			ADC_CH7 &	/*Payload Input Voltage 0-102.4V FS, 0.1V per count*/
			ADC_INT_OFF);

	/****** Setup SPI ******/
	OpenSPI(	SPI_FOSC_16,	/* 4MHz/16 = 250KHz SPI Clock Rate */
	MODE_00,			/*SSPSTAT register = 0x40 Data transmitted on rising edge of clock
						SSPCON1 register = 0x00 Idle state of clock is low*/ 
	SMPMID);		/* Input data sampled a middle of data output*/

	/*********************** Initialize Real Time Clock (RTC) ***********************/

	/* Now set the RTC to alarm every second */
	RTC_CS = 1;  		/* Select RTC */		
	WriteSPI(0x8B);		/* Set RTC address to start at Sec Alarm 1 Register address */
	WriteSPI(0x80);		/* Write RTC Seconds Alarm register mask bit */
	WriteSPI(0x80);		/* Write RTC minutes Alarm register mask bit */
	WriteSPI(0x80);		/* Write RTC hour Alarm register mask bit */
	WriteSPI(0x80);		/* Write RTC days Alarm register mask bit */
	WriteSPI(0x06);		/* Write RTC Control Reg data till no collision */
	RTC_CS = 0;  		/* DeSelect RTC */




	/******************************* Initialize DAC **********************************/
	/*DAC channel A is the 1KW charger output voltage setpoint 0-81.92V = 0 to 4095 counts = 20mV per count*/
	/*DAC channel B is the 1KW charger output Current setpoint 0-40.96 = 0 to 4095 counts = 10mA per count*/
	/* Set both to zero at reset*/
	/*Note the 4 MSBs of the 16 bite value are the address pointer in the DAC*/
	/* DAC A Voltage setpoint = 0000 DDDD DDDD DDDD */ 
	/* DAC B Current setpoint = 0001 DDDD DDDD DDDD */
	/* DAC O/P Wakeup  = 1111 XXXX XXX1 X000 */

	DAC_CS_L = 0;		/* select DAC */
	WriteSPI(0x00);		/*Set DAC A to 0 */		
	WriteSPI(0x00);		/*Set DAC A to 0 */		
	DAC_CS_L = 1;		/* Deselect DAC */

	DAC_CS_L = 0;		/* select DAC */
	WriteSPI(0x10);		/*Set DAC B to 0*/		
	WriteSPI(0x00);		/*Set DAC B to 0*/		
	DAC_CS_L = 1;		/* Deselect DAC */

	DAC_CS_L = 0;		/* select DAC */
	WriteSPI(0xF0);		/*Wake DAC A & B*/		
	WriteSPI(0x10);		/*Wake DAC A & B*/		
	DAC_CS_L = 1;		/* Deselect DAC */


	/*********************************** Initialize Variables *************************/

	strcpypgm2ram(InCommand,"");	/* Set Input Command to No new command*/
	strcpypgm2ram(InString,""); /* Set InString to null */
	strcpypgm2ram(InVolts,""); /* Set point Voltage */
	strcpypgm2ram(InCurrent,""); /* Set point current */

	Mode = 3;	
	V_UnReg	= 0;	
	V_PwrOut = 0;	
	I_Load_40mA	= 0;
	I_Load_10mA	= 0;
	Leak_Count = 0;	
	Amb_Temp = 0;	
	V_Payload =	0;	
	One_Sec_Tick = 0;
	ADCDataValid = 0;

}
/*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
/*^^^^^^^^^^^^^^^^^^^^^^ End of Initialize Micro Routine ^^^^^^^^^^^^^^^^^^^^^^^^^^*/
/*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/



/************************************************************************************/
/****************************** Read all Inputs Routine *****************************/
/************************************************************************************/
void ReadAllInputs (void)
{
	NewCommand = no;	
	/*************** Read RTC and toggle 1 second tick **************/
	if (RTC_INT == 0)	
	{
		/* Read RTC alarm register to clear RTC_INT and Set 1 sec tick*/
		One_Sec_Tick = 1;	/*Set 1 second tick*/

		/* Clear RTC_INT by reading the second alarm reg*/
		RTC_CS = 1;  		/* Select RTC */		
		WriteSPI(0x0B);		/* Set RTC address to start at Sec Alarm 1 Register address */
		TempChar = ReadSPI();		/* Read RTC Seconds Alarm register mask bit */
		RTC_CS = 0;  		/* DeSelect RTC */
	}
	else	/* clear 1 second tick */
	{
		One_Sec_Tick = 0;
	}

	/******************* Read Health and Powerout*******************/
	if (One_Sec_Tick)
	{
		SetChanADC(ADC_CH0);
		Delay10TCYx(1); /*Delay for 10 instr. cycles = 10uS*/
		ConvertADC();
		while (BusyADC());
		V_UnReg = ReadADC(); /*PwrOut Voltage 0-102.4V FS, 0.1V per count*/

		SetChanADC(ADC_CH1);
		Delay10TCYx(1); /*Delay for 10 instr. cycles = 10uS*/
		ConvertADC();	
		while (BusyADC());
		V_PwrOut = ReadADC(); /*Unregulated Voltage 0-102.4V FS, 0.1V per count*/

		SetChanADC(ADC_CH2);
		Delay10TCYx(1); /*Delay for 10 instr. cycles = 10uS*/
		ConvertADC();	
		while (BusyADC());
		I_Load_40mA = ReadADC();	/*Load Current 0 to 40.96A FS, 40mA per count*/  

		SetChanADC(ADC_CH3);
		Delay10TCYx(1); /*Delay for 10 instr. cycles = 10uS*/
		ConvertADC();	
		while (BusyADC());
		I_Load_10mA= ReadADC();		/*Load Current 0 to 10.24A FS, 10mA per count*/

		SetChanADC(ADC_CH4);
		Delay10TCYx(1); /*Delay for 10 instr. cycles = 10uS*/
		ConvertADC();	
		while (BusyADC());
		Leak_Count = ReadADC(); /*Leak Voltage < 512 counts = Leak*/
		ADCDataValid = 1;		/* Set ADC data valid flag */

		SetChanADC(ADC_CH5);
		Delay10TCYx(1); /*Delay for 10 instr. cycles = 10uS*/
		ConvertADC();	
		while (BusyADC());
		Amb_Temp = ReadADC();/*Temperture   0.5156 Deg. C per count and 0 Deg.C = = 131.5 Counts */ 

		SetChanADC(ADC_CH7);
		Delay10TCYx(1); /*Delay for 10 instr. cycles = 10uS*/
		ConvertADC();	
		while (BusyADC());
		V_Payload = ReadADC(); /*Payload Input Voltage 0-102.4V FS, 0.1V per count*/

	}
}

/************************************************************************************/
/****************************** Get New Command *************************************/
/************************************************************************************/
void CommunicationMan (void)
{
  	if (!NewCommand)
  	{
		/****************** Get Command from serial port ***************/
		ReadStrTimeOut('T');	/*check for command string*/
		if (strlen(InString) == 2)
		{
			strcpy(InCommand,InString);
			if(!strcmppgm2ram(InCommand,"ss"))
			{
				putrsUSART("SS OK\r\n");
				putrsUSART("enter mode\r\n");
				putrsUSART("mission, homing, docking, docked-nocharge, docked-charge\r\n");
				ReadStrTimeOut('W');	/*Get New mode type string*/
				if(	(!strcmppgm2ram(InString,"mission")) ||
					(!strcmppgm2ram(InString,"homing"))	||
					(!strcmppgm2ram(InString,"docking"))||
					(!strcmppgm2ram(InString,"docked-nocharge"))||
					(!strcmppgm2ram(InString,"docked-charge"))||
					(!strcmppgm2ram(InString,"failed-docked"))||
					(!strcmppgm2ram(InString,"failed-nondocked")) )
				{	
					strcpy(InData,InString);
					putrsUSART("GOOD\r\n");	
					NewCommand = yes;
				}
			}
			if(!strcmppgm2ram(InCommand,"sv"))
			{
				putrsUSART("SV OK\r\n");
				putrsUSART("vv.vv ii.ii\r\n");	

				ReadStrTimeOut('W');	/*Get New mode type string with wait on first byte*/
				if( strcmppgm2ram(InString,"e1") && (strlen(InString) == 11) ) 
				{
					InVolts[0] = InString[0];
					InVolts[1] = InString[1];
					InVolts[2] = InString[3];
					InVolts[3] = InString[4];
					InVolts[4] = '\0';
					InCurrent[0] = InString[6];
					InCurrent[1] = InString[7];
					InCurrent[2] = InString[9];	
					InCurrent[3] = InString[10];	
					InCurrent[4] = '\0';
					SetPtVolts   = atoi( InVolts)/2;
					SetPtCurrent = atoi( InCurrent);
					if ((SetPtVolts >= 0) && (SetPtVolts < 4096) && (SetPtCurrent >= 0) && (SetPtCurrent <4096) 
						&& ( ( (SetPtVolts/50) * (SetPtCurrent/100) ) <= 1000) )
					{
						NewCommand = yes;
						putrsUSART("GOOD\r\n");	
						NewSetPoint = 1;
					}
				}
			}
			if(!strcmppgm2ram(InCommand,"rs"))
			{
				if (Mode == 0)
				{
				putrsUSART("The state is mission\r\n");
				}
				if (Mode == 1)
				{
				putrsUSART("The state is homing\r\n");
				}
				if (Mode == 2)
				{
				putrsUSART("The state is docking\r\n");
				}
				if (Mode == 3)
				{
				putrsUSART("The state is docked-nocharge\r\n");
				}
				if (Mode == 4)
				{
				putrsUSART("The state is docked-charge\r\n");
				}
				if (Mode == 5)
				{
				putrsUSART("The state is failed-docked\r\n");
				}
				if (Mode == 6)
				{
				putrsUSART("The state is failed-nondocked\r\n");
				}
				putrsUSART("Leak reading is ");
				Y = ((1023-Leak_Count)*100)/1023;
				ultoa(Y, InData);
				putsUSART(InData);
				putrsUSART(" %\r\n");

				putrsUSART("Temperature is ");
				Y = (Amb_Temp - 131)/2;
				ultoa(Y, InData);
				putsUSART(InData);
				putrsUSART(" C\r\n");
	
				putrsUSART("Unregulated voltage from Docking Station is ");
				Y = V_UnReg/10;
				ultoa(Y, InData);
				putsUSART(InData);
				putrsUSART(".");
				Y = V_UnReg - (Y * 10);
				ultoa(Y, InData);
				putsUSART(InData);
				putrsUSART(" V\r\n");

				putrsUSART("AUV Payload Bus Voltage is ");
				Y = V_Payload/10;
				ultoa(Y, InData);
				putsUSART(InData);
				putrsUSART(".");
				Y = V_Payload - (Y * 10);
				ultoa(Y, InData);
				putsUSART(InData);
				putrsUSART(" V\r\n");

				putrsUSART("Battery Charge voltage is ");
				Y = V_PwrOut/10;
				ultoa(Y, InData);
				putsUSART(InData);
				putrsUSART(".");
				Y = V_PwrOut - (Y * 10);
				ultoa(Y, InData);
				putsUSART(InData);
				putrsUSART(" V\r\n");

				if(Mode != 0 )
				{
					putrsUSART("Battery Charge Current is (0 to 40.95A) ");
					Y = (I_Load_40mA * 4)/100;
					ultoa(Y, InData);
					putsUSART(InData);
					putrsUSART(".");
					Y = (I_Load_40mA * 4) - (Y * 100);
					ultoa(Y, InData);
					putsUSART(InData);
					putrsUSART(" A\r\n");

					putrsUSART("Battery Charge Current is (0 to 10.23A) ");
					Y = (I_Load_10mA)/100;
					ultoa(Y, InData);
					putsUSART(InData);
					putrsUSART(".");
					Y = (I_Load_10mA) - (Y * 100);
					ultoa(Y, InData);
					putsUSART(InData);
					putrsUSART(" A\r\n");
				}
				NewCommand = yes;
			}
			if(!strcmppgm2ram(InCommand,"dc"))
			{
				putrsUSART("Command Set:\r\n");
				putrsUSART("ss = Set State\r\n");
				/*putrsUSART("sc = Set Clock\r\n");*/
				putrsUSART("sv = Set Power Out Voltage and Current\r\n");
				putrsUSART("rs = Read Status\r\n");
				NewCommand = yes;
			}
			if (NewCommand == no)
			{
				putrsUSART("Error\r\n");				
				strcpypgm2ram(InCommand,"");
			}
		}
		else
		{
			strcpypgm2ram(InCommand,"");
			if (strlen(InString) != 0)
			{
				putrsUSART("Error\r\n");				
			}
		}
 	}
}




/************************************************************************************/
/******************** Determine Mode and output Values  *****************************/
/************************************************************************************/
void DetermineMode (void)
{
		OldMode = Mode;
	/* If new command update mode.  If health errors reset mode to safe mode.*/
	if 	(NewCommand == 1)
	{
		if (!strcmppgm2ram(InString,"mission"))			{Mode = 0;}
		if (!strcmppgm2ram(InString,"homing"))			{Mode = 1;}
		if (!strcmppgm2ram(InString,"docking"))			{Mode = 2;}
		if (!strcmppgm2ram(InString,"docked-nocharge"))	{Mode = 3;}
		if (!strcmppgm2ram(InString,"docked-charge"))	{Mode = 4;}
		if (!strcmppgm2ram(InString,"failed-docked"))	{Mode = 5;}
		if (!strcmppgm2ram(InString,"failed-nondocked")){Mode = 6;}
	}
	if (Mode == 4)
	{
/* <<<<<< Temp. del. for testing >>>>>>>>*/
	/*	if (V_UnReg < 654)   	/* Voltage input to 1KW charger*/ 
	/*	{					/*Unregulated Vin 0-102.4V = FS, = 0 to 1024 counts*/	
	/*		Mode = 3;		/* Less then 65V*/
	/*	} */


		if (I_Load_40mA > 1000)	/*Load Current 0 to 40.96A FS, 40mA per count, 30A/.03 = 1000 counts */ 
		{
			Mode = 3;		/* > 30Amps */
		}
	}	
	if ((Leak_Count < 512) && (ADCDataValid == 1))	/* 1/2 scale /*Leak Voltage < 512 counts = Leak*/
	{
		Mode = 0;	/* Safe mode all power off*/
	}

	if (Amb_Temp > 238)	  	/*Temperture   0.5156 Deg. C per count and 0 Deg.C = = 131.5 Counts */ 
	{
		Mode = 0;			/* 55/0.5156 + 131 = 238 counts for 55 Deg. C */
	}

	if (Mode != OldMode)
		{
			NewMode = 1; 	/* flag for new mode*/
		}

	if ((Mode != 4) && ((SetPtVolts != 0) || (SetPtCurrent != 0)) )  /* if not charging zero out setpoints*/
	{
		SetPtVolts = 0;
		SetPtCurrent = 0;
		NewSetPoint = 1;
	}

}

/************************************************************************************/
/******************************* Write All Output ***********************************/
/************************************************************************************/
void WriteAllOutput (void)
{
	/********************** Set DAC per New set point **************************/
	if (NewSetPoint == 1) /* Update DAC voltage and current set pionts*/
	{
		DAC_CS_L = 0;		/* select DAC 1KW Voltage set point*/
		WriteSPI(HiSetPtVolts);		/*Set DAC A to 0*/		
		WriteSPI(LoSetPtVolts);		/*Set DAC A to 0 */		
		DAC_CS_L = 1;		/* Deselect DAC */

		DAC_CS_L = 0;		/* select DAC */
		WriteSPI(HiSetPtCurrent | 0x10); /*Set bit 4 of high byte to address DAC B Current set point*/	
		WriteSPI(LoSetPtCurrent);		/*Set DAC B to 0*/		
		DAC_CS_L = 1;		/* Deselect DAC */

		NewSetPoint = 0;	/*Clear New set point*/
	}

	/********************* Set power supplies per Mode ************************/
	if ( NewMode )
	{
		if (Mode == 0)	/* Mission*/
		{
			/* Set power supply bits*/
			FanOn = on;  			/* Turn fan on */
			PC104_ON = on;  		/* Turn on power to PC104 */
			RF_ETHERNET_ON = on;  	/* Turn on power to RF ETHERNET  */
			MOD_USBL_ON = off;  	/* Turn off power to ACOUSTIC MODEM and USBL */
			RESOLVER_ON = off;  	/* Turn off power to RESOLVER */
			PWROUT = off;  			/* Disable 1KW power Output */
			PWROUT_L = 1;  			/* Disable 1KW power Output */
			/* RS232 nib = mode */
			RS232CTR3 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232CTR2 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232_CTR1 = 0;			/* Set RS232 control nib to AUV Mission */
			RS232_CTR0 = 0;			/* Set RS232 control nib to AUV Mission */
		}

		if (Mode == 1)		/* Homing */
		{
			FanOn = on;  			/* Turn fan on*/
			PC104_ON = on;  		/* Turn on power to PC104 */
			RF_ETHERNET_ON = on;  	/* Turn on power to RF ETHERNET  */
			MOD_USBL_ON = on;  		/* Turn on power to ACOUSTIC MODEM and USBL */
			RESOLVER_ON = off;  	/* Turn off power to RESOLVER */
			PWROUT = off;  			/* Disable 1KW power Output */
			PWROUT_L = 1;  			/* Disable 1KW power Output */
			/* RS232 nib = mode */
			RS232CTR3 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232CTR2 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232_CTR1 = 0;			/* Set RS232 control nib to AUV Mission */
			RS232_CTR0 = 1;			/* Set RS232 control nib to AUV Mission */
		}

		if (Mode == 2)		/* Docking */
		{
			FanOn = on;  			/* Turn fan on*/
			PC104_ON = on;  		/* Turn on power to PC104 */
			RF_ETHERNET_ON = on;  	/* Turn on power to RF ETHERNET  */
			MOD_USBL_ON = on;  		/* Turn on power to ACOUSTIC MODEM and USBL */
			RESOLVER_ON = on;  		/* Turn on power to RESOLVER */
			PWROUT = off;  			/* Disable 1KW power Output */
			PWROUT_L = 1;  			/* Disable 1KW power Output */
			/* RS232 nib = mode */
			RS232CTR3 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232CTR2 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232_CTR1 = 1;			/* Set RS232 control nib to AUV Mission */
			RS232_CTR0 = 0;			/* Set RS232 control nib to AUV Mission */
		}

		if (Mode == 3) 	/* Docked-nocharge */
		{
			FanOn = on;  			/* Turn fan on*/
			PC104_ON = on;  		/* Turn on power to PC104 */
			RF_ETHERNET_ON = on;  	/* Turn on power to RF ETHERNET  */
			MOD_USBL_ON = off;  	/* Turn off power to ACOUSTIC MODEM and USBL */
			RESOLVER_ON = on;  		/* Turn on power to RESOLVER */
			PWROUT = off;  			/* Disable 1KW power Output */
			PWROUT_L = 1;  			/* Disable 1KW power Output */	
			/* RS232 nib = mode */
			RS232CTR3 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232CTR2 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232_CTR1 = 1;			/* Set RS232 control nib to AUV Mission */
			RS232_CTR0 = 1;			/* Set RS232 control nib to AUV Mission */
		}

		if (Mode == 4)		/* Docked-charge*/
		{
			FanOn = on;  			/* Turn fan on*/
			PC104_ON = on;  		/* Turn on power to PC104 */
			RF_ETHERNET_ON = on;  	/* Turn on power to RF ETHERNET  */
			MOD_USBL_ON = off;  	/* Turn off power to ACOUSTIC MODEM and USBL */
			RESOLVER_ON = on;  		/* Turn on power to RESOLVER */
			PWROUT = on;  			/* Enable 1KW power Output */
			PWROUT_L = 0;  			/* Enalbe 1KW power Output */	
			/* RS232 nib = mode */
			RS232CTR3 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232CTR2 = 1;  		/* Set RS232 control nib to AUV Mission  */
			RS232_CTR1 = 0;			/* Set RS232 control nib to AUV Mission */
			RS232_CTR0 = 0;			/* Set RS232 control nib to AUV Mission */
		}

		if (Mode == 5)		/* Failed-docked*/
		{
			FanOn = on;  			/* Turn fan on*/
			PC104_ON = on;  		/* Turn on power to PC104 */
			RF_ETHERNET_ON = on;  	/* Turn on power to RF ETHERNET  */
			MOD_USBL_ON = off;  	/* Turn off power to ACOUSTIC MODEM and USBL */
			RESOLVER_ON = off;  	/* Turn off power to RESOLVER */
			PWROUT = off;  			/* Disable 1KW power Output */
			PWROUT_L = 1;  			/* Disalbe 1KW power Output */			
			/* RS232 nib = mode */
			RS232CTR3 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232CTR2 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232_CTR1 = 1;			/* Set RS232 control nib to AUV Mission */
			RS232_CTR0 = 1;			/* Set RS232 control nib to AUV Mission */
		}

		if (Mode == 6)		/* Failed-nondocked */
		{
			FanOn = on;  			/* Turn fan on*/
			PC104_ON = on;  		/* Turn on power to PC104 */
			RF_ETHERNET_ON = on;  	/* Turn off power to RF ETHERNET  */
			MOD_USBL_ON = on;  		/* Turn on power to ACOUSTIC MODEM and USBL */
			RESOLVER_ON = off;  	/* Turn off power to RESOLVER */
			PWROUT = on;  			/* Enable 1KW power Output */
			PWROUT_L = 0;  			/* Enalbe 1KW power Output */	
			/* RS232 nib = mode */
			RS232CTR3 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232CTR2 = 0;  		/* Set RS232 control nib to AUV Mission  */
			RS232_CTR1 = 0;			/* Set RS232 control nib to AUV Mission */
			RS232_CTR0 = 1;			/* Set RS232 control nib to AUV Mission */
		}
		NewMode = 0;

	}
	if (RS232_INT)
	{
		/* RS232 nib = mode */
		RS232CTR3 = 1;  		/* Set RS232 control nib to AUV Mission  */
		RS232CTR2 = 0;  		/* Set RS232 control nib to AUV Mission  */
		RS232_CTR1 = 0;			/* Set RS232 control nib to AUV Mission */
		RS232_CTR0 = 0;			/* Set RS232 control nib to AUV Mission */		
	}
}


/************************************************************************************/
/********************************** Functions ***************************************/
/************************************************************************************/


void ReadStrTimeOut(char Wait)	/* Read a string form the USART, return nul if no data or e1 if time out*/
{
	if (DataRdyUSART() || (Wait == 'W'))
	{
		char i = 0; /* string pointer, exit if 21*/
		while (i != 21)	
		{
			INTCONbits.TMR0IF = 0;  			/* Clear Timer0 over flow bit*/
			WriteTimer0(2^16-31250);  			/*Set time out to 8 sec (256uSec per count)*/	
			while ((!INTCONbits.TMR0IF) && (!DataRdyUSART())); /*wait for byte or time out*/	
			if (!INTCONbits.TMR0IF) 			/*If Not Time out then data ready*/
			{
				InString[i] = ReadUSART();		/* add USART byte to string*/
				if (InString[i] == 13)			/* Line feed*/
				{
					InString[i] = '\0';
					i = 19;						/* now get CR then exit */
					if (strlen(InString) == 0)
					{	
						strcpypgm2ram(InString,"dc");
					}
				}	
				if (InString[i] == 10)			/* Carriage return*/
				{
					InString[i] = '\0';
					i = 20;						/* force exit */
					if (strlen(InString) == 0)
					{	
						strcpypgm2ram(InString,"dc");
					}
				}	
			}	
			else 
			{
				i = 20;							/* 20 + 1 = 21, exit with time out*/
				strcpypgm2ram(InString,"e1"); 	/* Set string to error 1 time out*/
				ErrorFlag = 1;
			}
			++i;
		}
	}
	else
	{
		strcpypgm2ram(InString,""); 			/* Set string to null and return*/
	}
}
