/*
Matt Hobson
Spring, 2006
ELEN 599
File Name: sonar.c
Program Purpose:  This file defines the code needed to use the HCS12 timer
     system to control the Devantech SRF04 sonar module.  Subroutines
     include Timer initialization, pulse using Output Compare (Blue wire,
     PTT[0]), and distance measurement using Input Capture (White wire, 
     PTT[1]).
     
	 If the default bus speed for this module is 8Mhz (RAM with MON12, no prescale). 
	 Period = (1)/(bus speed)= 1/8MHz = 125nS 
	 
	 The default bus speed for this module is 24Mhz (MiniDragon+, no prescale). 
	 Period = (1)/(bus speed)= 1/24MHz = 41.67nS
*/
//******************************* INCLUDE FILES ********************************

#include <mc9s12dp256.h>	   //DP256 header file
#include <stdio.h>			   //Standard I/O C header 
//#include <math.h>              //Math header file

//********************************** DEFINES ***********************************

#define ClockPeriod 0.00000004167 //41.67nS for 24MHz bus speed
//#define ClockPeriod 0.000000125 //125nS for 8MHz bus speed
#define StartPing 100  //Small delay for output compare when function is called
#define Pulse 360      //# of pulses required for 15uS active-high pulse @ 24MHz
//#define Pulse 120     //# of pulses required for 15uS active-high pulse @ 8MHz
#define INconstant 0.000148 //Constant used to calculate distance in inches
//#define CMconstant 0.00058  //Constant used to calculate distance in centimeters

//****************************** GLOBAL VARIABLES ******************************

unsigned char m = 0x00;
unsigned int TOcount = 0;    //Counter for the # of Timer Overflow Flags (TOF)
unsigned int TOFedge1 = 0;   //Stores value of TOcount at time of rising edge
unsigned int TOFedge2 = 0;   //Stores value of TOcount at time of falling edge
unsigned int TOdiff = 0;     //Stores the difference of the TOF edges
unsigned char Oflow = 0;     //Keep track of when TOcount needs to roll over
unsigned int riseEdge = 0;   //Variable to hold the rising input edge
unsigned int fallEdge = 0;   //Variable to hold the falling input edge
unsigned long int ElapsedTicks = 0; //Holds total # of clock ticks for IC
float ElapsedTime = 0;   //Holds time(seconds) of Input Capture (IC)
float SRange = 0;        //Range of object in inches
float Feet1 = 0;         //Distance of object, in feet
float Inches = 0;        //Remainder of object distance
unsigned char Feet2 = 0; //Final feet value

//***************************** INIT_TIMER FUNCTION ****************************

void Init_Timer (void)  //Timer initialization code
{
   TIE   = 0x00;  //Interrupts off for Input Capture/Output Compare
   TIOS  = 0x81;  //Set PTT[0], PTT[7] as output compare, all others as input capture
   TSCR2 = 0x00;  //No prescale factor; clock = (bus speed)/(1)
   TCTL1 = 0x80;  //Set Output Compare line OC[7] to zero
   TCTL2 = 0x02;  //Set Output Compare line OC[0] to zero
   TFLG1 = 0XFF;  //Clear any Timer related flags
   TSCR1 = 0x80;  //Timer system enabled: TEN = 1
   TSCR2 = 0x80;  //Free-running Counter overflow interrupt enabled (TOI)
}

//***************************** PULSE_15US FUNCTION ****************************

void Pulse_15us (void)  //Output Compare pulse to start sonic pings
{ 
   TFLG1 = 0X01;           //Clear any flags on channel 0
   TCTL2 = 0x01;           //Toggle OC[0] line when event occurs
   TC0 = TCNT + StartPing; //Rising edge occurs 100 cycles after button press
   while ((TFLG1 & 0x01)== 0)   //Wait for flag (rising edge)
     {;}
   TFLG1 = 0X01;                //Clear flag on TC0
   TC0 += Pulse;                //Make pulse last for 15uS
   while ((TFLG1 & 0x01)== 0)   //Wait for flag
     {;} 
   TFLG1 = 0X01;           //Clear flag on TC0
   TCTL2 = 0x02;           //Set Output Compare line back to zero
}

//****************************** CAPTURE FUNCTION ******************************

void Distance (void)     //Input capture distance measurement
{  
   TOcount = 0;
   
   TCTL4 = 0x04;  //Set Input Capture to look for rising edges only
   while ((TFLG1 & 0x02)== 0)  //Wait for rising edge
     {;}
   TOFedge1 = TOcount; //Store value of TOcount when rising edge occurs
   riseEdge = TC1;   //Store the first latched value of the free running timer
   TFLG1 = 0x02;  //Clear flag on TC1
   TCTL4 = 0x08;  //Set Input Capture to look for falling edges only 
   while ((TFLG1 & 0x02)== 0)  //Wait for falling edge
     {;}
   TOFedge2 = TOcount; //Store value of TOcount when falling edge occurs
   fallEdge = TC1;   //Store the second latched value of the free running timer
   TFLG1 = 0x02;  //Clear flag on TC1
   
   if (TOFedge1 > TOFedge2)  //For the special case of the input capture event
   {                         //happening when TOcount rolls over.
      TOdiff = TOFedge2 + (65536 - TOFedge1);
   }
   else   //For the normal case: TOFedge2 > TOFedge1
   {   
	  TOdiff = TOFedge2 - TOFedge1;
   }
   ElapsedTicks = (TOdiff * 65536) + fallEdge - riseEdge; //Total # of ticks
   ElapsedTime = ElapsedTicks * ClockPeriod;  //Time (seconds)
   SRange = ElapsedTime / INconstant; //Calculate distance in inches
   
//   printf("TOcount is %3u \n", TOcount);
//   printf("Rising Edge is %6u \n", riseEdge);
//   printf("Falling Edge is %6u \n", fallEdge);
//   printf("Elapsed Ticks is %lu \n", ElapsedTicks);
//   printf("ElapsedTime is %9.6f \n", ElapsedTime);
//   printf("Range is %6.2f \n", SRange);
/*   
   Feet1 = Range / 12.00;  //Determine distance in feet (floating point)
   
   
   if ((Feet1 >= 10) && (Feet1 < 11))
     {Inches = Range - 120;   //floating point
	  Feet2 = 10;             //integer
	 }
   if ((Feet1 >= 9) && (Feet1 < 10))
     {Inches = Range - 108;
	  Feet2 = 9;
	 }
   if ((Feet1 >= 8) && (Feet1 < 9))
     {Inches = Range - 96;
	  Feet2 = 8;
	 }
   if ((Feet1 >= 7) && (Feet1 < 8))
     {Inches = Range - 84; 
	  Feet2 = 7;
	 }
   if ((Feet1 >= 6) && (Feet1 < 7))
     {Inches = Range - 72; 
	  Feet2 = 6;
	 }
   if ((Feet1 >= 5) && (Feet1 < 6)) 
     {Inches = Range - 60; 
	  Feet2 = 5;
	 }
   if ((Feet1 >= 4) && (Feet1 < 5))
     {Inches = Range - 48; 
	  Feet2 = 4;
	 }
   if ((Feet1 >= 3) && (Feet1 < 4))
     {Inches = Range - 36; 
	  Feet2 = 3;
	 }
   if ((Feet1 >= 2) && (Feet1 < 3))
     {Inches = Range - 24; 
	  Feet2 = 2;
	 }
   if ((Feet1 >= 1) && (Feet1 < 2))
     {Inches = Range - 12; 
	  Feet2 = 1;
	 }
   if ((Feet1 > 0) && (Feet1 < 1))
     {Inches = Range; 
	  Feet2 = 0;
	 }
	 
   printf("Object Distance is %3u feet %5.2f inches \n\n", Feet2, Inches);
*/

}

//******************************* SONAR FUNCTION *******************************

void sonar (void)
{
   Pulse_15us();
   Distance();
}

//*************************** GRIPPER_ENCODER FUNCTION *************************

//void gripper_encoder (void)
//{
//}

//**************************** CHUTE_ENCODER FUNCTION **************************

//void chute_encoder (void)
//{
//}

//****************************** PULSE_HANDLER ISR *****************************
/* NOT USED HERE...

#pragma interrupt_handler Pulse_handler()	//Interrupt pragma for TC0, OC

void Pulse_handler (void)	    //ISR to create 15us output pulse
{
   TFLG1 = 0X01;         //Clear flag on TC0           
}
*/
//****************************** RANGE_HANDLER ISR *****************************
/* NOT USED HERE...
#pragma interrupt_handler Range_handler()	//Interrupt pragma for TC1, IC

void Range_handler (void)       //ISR to measure the distance of object
{
   TFLG1 = 0x02;   //Clear flag on TC1
   Finished  = 1;  //Set flag to indicate ISR has completed measurement cycle
}
*/
//***************************** OVERFLOW_HANDLER ISR ***************************

#pragma interrupt_handler Overflow_handler()	//Interrupt pragma for TOF

void Overflow_handler ()  //Occurs every 2.73mS @ 24MHz
{
   TFLG2 = 0X80;   //Clear the TOF flag
/*  
      if(m==0x00)       //Blue LED Heartbeat
      {PORTK |= 0x08;}  //Turn on Blue LED
      if(m==0xFF)
      {PORTK &= ~0x08;} //Turn off Blue LED
      m = ~m;   
*/	  
   if (TOcount == 65535)
   {
	 TOcount = 0;  //Roll over the Flag counter
	 Oflow = 1;    //Set the overflow bit to 1, indicating a rollover
   }
   if (Oflow != 1) //Don't increment if a rollover just occured
   {
	 TOcount++;    //Increment Timer Overflow counter
   }
   Oflow = 0;      //Reset rollover bit
}

//******************************************************************************
