/****************************************************************************/
/* Copyright 2005 MBARI.                                                    */
/* Monterey Bay Aquarium Research Institute Proprietary Information.        */
/* All rights reserved.                                                     */
/****************************************************************************/
#include <16f876A.h>

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#use delay(clock=4000000, restart_wdt)
#include "Gulper_Main.h"
#include "RS485.c"
#include "Command_Handler.c"


#if DEBUG
#device ICD=TRUE
#fuses XT,WDT,NOPROTECT,PUT,NOBROWNOUT,NOLVP
#else
#fuses XT,WDT,NOPROTECT,PUT,NOLVP
#endif

//#define  RS485_RX_BUFFER_SIZE 64
#define  RS485_USE_EXT_INT    FALSE


int8 in_char = 0;
int8 next_in = 0;
int8 next_out = 0;
int8 *command;
int8 data[1];
Boolean uart_TX = false;       // Used for BIT uart checking 

#define INTS_PER_SECOND 15     // (20000000/(4*256*256))


#INT_TIMER1                        // This function is called every time
void clock_isr() {                 // timer 1 overflows (65535->0), which is
                                   // approximately 15 times per second for
    if(--int_count==0) {           // this program.
      ++seconds;
      int_count = INTS_PER_SECOND;
    }
}


// Purpose: Holds software in infinite loop to allow watchdog to reset
void software_reset() {
  for(;;) {
    null;
  }
}



//
// Main execution loop
//
main()
{
  
 long int value;
char toggle;
/*
int resolution; 
float scale=0.004; 
float scaled_value;
float bus_volt_scale=6.00;
int	GF_offset=512;
*/
  // Set up the system clocks
  int_count=INTS_PER_SECOND;
  setup_wdt(WDT_288MS); // Initialize the watchdog. See fuses WDT also
  
  // Initialize Serial and enable interrupts
// rs485_init();
 
  // Initialize Outputs
 
  
  // Set up analog input for AN0
  setup_adc(ADC_CLOCK_INTERNAL);
  setup_adc_ports(AN0_AN1_AN4_VREF_VREF);
  //set_adc_channel(0);

  // Check for WDT reset and output error if necessary
  switch ( restart_cause() )
  {
    case WDT_TIMEOUT:
    {
      sprintf(response_message, "WDT\r\n");
      send_error_response(response_message);
      break;
    }
    case NORMAL_POWER_UP:
    {
      break;
    }
  }

       
	toggle=0;
/* Begin Loop */    
    	set_adc_channel(4);
    for(;;)
	{ 
		  // strobe the dog
		  restart_wdt(); 

		if ( kbhit())
	  	{
			getch();			
			toggle = !toggle;
			putc('!');
		}

	
		if ( toggle )
		{
			output_bit(PIN_C1, HI);
			delay_ms(1000);
		}
		else
		{
			output_bit(PIN_C1, LO);	
			delay_ms(1000);	
	  	} 
		
		delay_ms(1000);
		value = READ_ADC();
	    printf("\n\r Ch0:%Ld ",value);
	// Main control loop
   
   }
	
	

}
