///////////////////////////////////////////////////////////
//	Program:		again.c
//	Description:	Another test program
//	Programmer:		Scott Nortman
//	Date:			3/24/00
///////////////////////////////////////////////////////////

/**************************** Constants *********************************/
#define pulse_handler TOC2_isr
#define TOLERANCE 10 
#define valve_sensor analog(1)
/**************************** End of Constants **************************/

/*************************** Interrupts *********************************/
#pragma interrupt_handler TOC2_isr, RTI_isr, TOF_isr;
/*************************** End of Interrupts **************************/

/************************** Includes ************************************/
#include <tjpbase.h>
#include <analog.h>
#include <vectors.h>
#include <mil.h>
#include <hc11.h>
/************************ End of includes *******************************/
/************************** Global Variables*****************************/
long duty_cycle;	//duty_cycle in e clocks
long period;		//period in e clocks
int desired;		
long count = 0;	
/************************ End of Global Variables ***********************/

/**************************** Main **************************************/
void main(void)
{
	
	/* VT100 clear screen */ 
	char clear[]= "\x1b\x5B\x32\x4A\x04"; 
	
	/* VT100 position cursor at (x,y) = (3,12) command is "\x1b[3;12H"*/
  	char place[]= "\x1b[1;1H";	/*Home*/
 
	SET_BIT(TMSK2, 0x40);		//Enble RTI interrupt
	SET_BIT(TCTL1, 0x40);		//TOC2 toggle
	CLEAR_BIT(TCTL1, 0x80);  	//Enable toggle on TOC2

	INTR_OFF();
	printf("%s", clear);  
  	printf("%s", place);
  	printf("Enter the desired period in e clocks / 1000:\n");
	period = (read_int() * 1000);
	TOC2 = 0;
	desired = 150;
	INTR_ON();
	
	while(1)
	{
		SET_BIT(TMSK1, 0x40);	//Enable TOC		
		if (desired < valve_sensor)
		{
			CLEAR_BIT(PORTA, 0x20);
		}
		else if (desired > valve_sensor) 
		{
			SET_BIT(PORTA, 0x20);
		}
		else if ((desired <= valve_sensor + TOLERANCE) && (desired >= valve_sensor - TOLERANCE))
		{
			CLEAR_BIT(TMSK1, 0x40);		//Disable TOC2
		}
		
	}/*End While*/
  	
}/*End Main*/

/**************************** End of Main *******************************/
void pulse_handler()
{
	TOC2 += (period / 2);		//Add period / 2
	CLEAR_FLAG(TFLG1, 0x40)		//Clear the interrupt flag
}

void RTI_isr(void)
{
	printf("%d\n", valve_sensor);
	count += 1;
	if (count >=500)
	{
		count = 0;
		if (desired == 150)
		{
			desired = 100;
		}
		
		else if (desired == 100)
		{
			desired = 150;
		}
	}
	CLEAR_FLAG(TFLG2, 0x40);
}

void TOF_isr(void)
{
	CLEAR_FLAG(TFLG1, 0x80);
}
