/*
Matt Hobson
Spring 2006
ELEN 599
Filename: Navigation.c
Purpose: Contains all of the functions pertaining to the robot's movements
         on the track. 
		 
		 Port A = Line Tracking System:
		    0 = Far Right Sensor
			1 = Right Sensor 
			2 = Middle Sensor
			3 = Left Sensor
			4 = Far Left Sensor

********************************** INCLUDE ************************************/

#include <mc9s12dp256.h>
#include <stdio.h>

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

#define Pushbutton 0x01  //PORTK[0]
//#define SlotSensor 0x02  //Optical slot sensor
#define BarcodeSwitch 0x04 //Transistor to control power to barcode scanner

//***DRIVE MOTOR DEFINES:
#define Forward 0x02   //Forward direction of drive motors
#define Reverse 0x01   //Reverse direction of drive motors
#define LeftTurn 0x00  //Left zero-radius turn of drive motors
#define RightTurn 0x03 //Right zero-radius turn of drive motors
#define DrvBrake 0x20  //Brake the drive motors (Must also take PWM line high)
#define DrvClear 0xDC  //Clear the two drive bits and turn off drive brake

//DRIVE MOTOR SPEED:
#define Normal 70   //Normal speed for line tracking
#define NComp 25    //Speed to compensate for Normal speed line tracking errors
#define Fast 100    //Fast speed for straight sections
#define FComp 95    //Speed to compensate for Fast speed line tracking errors
#define Slow 65     //Slow speed for approaches
#define SComp 60    //Speed to compensate for Slow speed line tracking errors
#define Creep 40    //Really slow
#define High 254    //Turns PWM signal into logic high (for braking)
#define Stop 0      //Stop

//***Line Tracking Sensor Info:

//HOME POSITION AND INTERSECTION:
#define All 0x1F  //All line tracking sensors on the line
//STRAIGHT LINE TRACKING:
#define Mid 0x04  //Middle sensor only on the line
#define Mid_Left 0x06  //Middle and right sensors on the white line
#define Mid_Right 0x0C   //Middle and left sensors on the white line
#define Left 0x02      //Right sensor only on the white line
#define Right 0x08       //Left sensor only on the white line
//BOUNDARY CONDITIONS:
#define FarLeft 0x10  //Outside right sensors
#define FarRight 0x01   //Outside left sensors
//PLANE MARKER
#define PlaneMarker 0x0E   //Middle, Left, and Right sensors (3" strip at plane)

//SONAR DISTANCE:
#define Chute_Dist_Stop 9  //Distance from chute for robot to stop
#define Chute_Dist_Grab 4  //Distance from chute for robot to get package 

//******************************* PROTOTYPES ***********************************

extern void wheelspeed (unsigned char, unsigned char); //Motor function prototype
extern void delay (int); 
extern void sonar (void);
//extern void trackline(void);
extern void arm_up (void);
extern void arm_down (void);
extern void elevator_up (void);
extern void elevator_down (void);
extern void home_position (unsigned char);
extern void ATD_Init (void);     //Start the ATD

//******************************** VARIABLES ***********************************

unsigned char linedata = 0;  //Looks at only the three center line tracking sensors
unsigned int Lencode = 0;    //Output from Left Drive Motor Encoder
unsigned int Rencode = 0;    //Output from Right Drive Motor Encoder
extern float SRange;   //Range data from the Sonar Sensor
extern unsigned char IRRange;  //Range data from the IR Sensor
unsigned char Strt = 0x00;   //Value to send home_position function at start
unsigned char Finsh = 0xFF;  //Value to send home_position function at end
unsigned char init = 0;      //Used to set ATD to a digital input

//************************** WAIT_FOR_BUTTON FUNCTION **************************

void wait_for_button (void) 
{
   while((PORTK & Pushbutton) == 0)  //Signal to MCU will be active-high
   {;
      if(init == 0) //Go throught this code only the first time through the loop
	  {
	     ATD0DIEN = 0x18;  //Turn on the digital input buffer for AN 3,4
		 init = 1;          //Set init to prohibit code from executing again
	  }      
	  if((PORTAD0 & 0x08) == 0) //If button S2 is pressed
	     {elevator_up();}       //Lift the elevator
	  if((PORTAD0 & 0x10) == 0) //If button S1 is pressed
	     {elevator_down();}    //Lower the elevator       
   }  
   ATD0DIEN = 0x00; //Turn off the digital input buffers on the Analog port
   ATD_Init();      //Initialize ATD for elbow potentiometer and Sharp IR  
}

//************************* TURN_ON_BCSCANNER FUNCTION *************************

void turn_on_bcscanner (void)
{
   PORTK &= ~BarcodeSwitch;  //Active-low to power the 7414-buffered transistor
}

//************************* TURN_OFF_BCSCANNER FUNCTION ************************

void turn_off_bcscanner (void)
{
   PORTK |= BarcodeSwitch;  //Turn off the Barcode scanner
}

//***************************** DRIVE_DIR FUNCTION *****************************

void drive_dir (unsigned char dir)
{
   if(dir == Forward)
   {
      PTM &= DrvClear;  //Clear previous drive direction and turn off brake
      PTM |= Forward;
   }
   if(dir == Reverse)
   {
      PTM &= DrvClear;  //Clear previous drive direction and turn off brake
	  PTM |= Reverse;
   }
   if(dir == LeftTurn)
   {
      PTM &= DrvClear;  //Clear previous drive direction, Same as LeftTurn
   }
   if(dir == RightTurn)
   {
      PTM &= DrvClear;  //Clear previous drive direction and turn off brake
	  PTM |= RightTurn;
   }

}

//**************************** DRIVE_BRAKE FUNCTION ****************************

void drive_brake (void)
{
   PTM |= DrvBrake;
   wheelspeed(High, High);
   delay(500);
   wheelspeed(0,0);
}

//**************************** LEFT_ENCODER FUNCTION ***************************

void left_encoder (unsigned int Lclicks)
{
   TCTL4 = 0x40;  //Set Input Capture TC3 to look for rising edges only
   while(Lencode < Lclicks)
   {
      while ((TFLG1 & 0x08)== 0)  //Wait for rising edge on TC3
        {;}
      Lencode++;     //Increment the number of clicks received from left encoder
      TFLG1 = 0x08;  //Clear flag on TC3
   }
   Lencode  = 0;     //Reset the counter
}

//***************************** TRACKLINE FUNCTION *****************************

void trackline (void)
{
   drive_dir(Forward);               //Set drive motor direction
   wheelspeed(Normal, Normal);       //Set drive motor speed
   linedata = PORTA & PlaneMarker;   //Ignore the outer two sensors
   if(linedata == PlaneMarker)
      {wheelspeed(Normal, Normal);}
   if(linedata == Mid)
      {wheelspeed(Normal, Normal);}
   if(linedata == Mid_Right)
      {wheelspeed(Normal, NComp);}
   if(linedata == Mid_Left)
      {wheelspeed(NComp, Normal);}
   if(linedata == Right)
      {wheelspeed(Normal, Stop);}
   if(linedata == Left)
      {wheelspeed(Stop, Normal);}
}

//*************************** LEFT_ENCODER_LINE FUNCTION ***********************
//Same as left_encoder(), but with line-tracking capability

void left_encoder_line (unsigned int Lclicks)
{
   TCTL4 = 0x40;  //Set Input Capture TC3 to look for rising edges only
   while(Lencode < Lclicks)
   {
      while ((TFLG1 & 0x08)== 0)  //Wait for rising edge on TC3
        {trackline();}    //Update the line tracking system
      Lencode++;     //Increment the number of clicks received from left encoder
      TFLG1 = 0x08;  //Clear flag on TC3
   }
   Lencode  = 0;     //Reset the counter
}
//**************************** RIGHT_ENCODER FUNCTION **************************

void right_encoder (unsigned int Rclicks)
{
   TCTL4 = 0x10;  //Set Input Capture TC2 to look for rising edges only
   while(Rencode < Rclicks)
   {
      while ((TFLG1 & 0x04)== 0)  //Wait for rising edge on TC2
        {;}
      Rencode++;     //Increment the number of clicks received from left encoder
      TFLG1 = 0x04;  //Clear flag on TC2
   }
   Rencode  = 0;     //Reset the counter
}

//***************************** TURN_LEFT FUNCTION *****************************

void turn_left (void)
{
   drive_dir(LeftTurn);
   wheelspeed(Normal, Normal);
   delay(800);         //Give time for middle sensor to move off of white line
   while((PORTA & Mid)== 0)  //Spin until the robot lands on the middle sensor
   {;}
   drive_brake();       //Brake the motors
   delay(20);
}

//***************************** TURN_RIGHT FUNCTION ****************************

void turn_right (void)
{
   drive_dir(RightTurn);
   wheelspeed(Normal, Normal);
   delay(800);         //Give time for middle sensor to move off of white line
   while((PORTA & Mid)== 0)  //Spin until the robot lands on the middle sensor
   {;}
   drive_brake();       //Brake the motors
   delay(20);   
}

//***************************** TURN_LEFT_90 FUNCTION **************************

void turn_left_90(void)
{
   drive_dir(LeftTurn);
   wheelspeed(Normal, Normal);
   left_encoder(31);
   drive_brake();
   delay(500);
}

//***************************** TURN_RIGHT_90 FUNCTION *************************

void turn_right_90(void)
{
   drive_dir(RightTurn);
   wheelspeed(Normal, Normal);
   left_encoder(31);
   drive_brake();
   delay(500);
}

//*************************** HOME_TO_CHUTE FUNCTION ***************************

void home_to_chute (void)
{
   trackline();                     //Start tracking the white line
//   delay(600);          //Time to get out of home postion
   arm_down();      //Lower the arm in preparation to grap the first package   
   while ((PORTA & FarRight)== 0) //Driving to the chute
   {
      trackline();  //Track the white line to the first intersection 
   }
   left_encoder_line(53);  //Travel about 11 inches past the intersection
   drive_brake();   //Brake the motors 
   delay(50);            
}

//*************************** ONE_TO_CHUTE FUNCTION ****************************

void one_to_chute (void) //Returns robot to the chute from Plane 1
{
   turn_left();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   left_encoder(19);
   drive_brake();
   turn_left();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   left_encoder(19);
   drive_brake();
   turn_right();
   sonar();             //Grab a sonar reading
   while (SRange > Chute_Dist_Stop)   //Approaching to the chute
   {
      trackline();  //Track the white line
	  sonar();      //Update the distance measurement 
   }
   drive_brake();   //Brake the motors
   delay(20);
//   arm_down();      //Lower the arm to the track from home position             
}  

//*************************** TWO_TO_CHUTE FUNCTION ****************************

void two_to_chute (void) //Returns robot to the chute from Plane 2
{
   turn_left();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_left();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_right();
   sonar();             //Grab a sonar reading
   while (SRange > Chute_Dist_Stop)   //Approaching to the chute
   {
      trackline();  //Track the white line
	  sonar();      //Update the distance measurement 
   }
   drive_brake();   //Brake the motors
//   arm_down();      //Lower the arm to the track from home position             
}  

//************************** THREE_TO_CHUTE FUNCTION ***************************

void three_to_chute (void)  //Returns robot to the chute from Plane 3
{
   turn_right();
   while((PORTA & FarLeft)== 0) 
      {trackline();}    //Go to the intersection
   left_encoder_line(19);  //Go past intersection
   drive_brake();
   turn_right();
   while((PORTA & FarRight)== 0) 
      {trackline();}    //Go to the intersection
   left_encoder_line(19);  //Go past intersection
   drive_brake();
   turn_right();
   left_encoder_line(53);  //Drive up to chute
   drive_brake();   //Brake the motors
//   arm_down();      //Lower the arm to the track from home position             
}             

//*************************** CHUTE_TO_ONE FUNCTION ****************************

void chute_to_one (void)
{
   turn_right();
   home_position(Strt); //Pick arm back up
   while((PORTA & FarLeft)== 0) 
      {trackline();}    //Go to the intersection
   delay(800);  //Go through the intersection
   while((PORTA & FarLeft)== 0) 
      {trackline();}    //Go to the starting square
   left_encoder_line(29); //Use the encoder to go 6" into the starting square
   drive_brake();
   turn_left_90();
   drive_dir(Forward);  //Go forward
   wheelspeed(Normal, Normal);
   while((PORTA & Mid)== 1)  //Driving through the start box
      {;}   
//   while((PORTA & Mid)== 0)
//      {;} 
   left_encoder(33); //Use the encoder to go 7" from start box to the plane
   drive_brake();
}

//*************************** CHUTE_TO_TWO FUNCTION ****************************

void chute_to_two (void)
{
   turn_right();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_left();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_right();
   while(PORTA != PlaneMarker)
      {trackline();}    //Go to the plane marker
   delay(200);          //Go past the plane marker
   drive_brake();
   turn_left_90();      //Use wheel encoders to make precise 90 degree turn
} 

//************************** CHUTE_TO_THREE FUNCTION ***************************

void chute_to_three (void)
{
   turn_right();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_left();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_left();
   while(PORTA != PlaneMarker)
      {trackline();}    //Go to the plane marker
   delay(200);          //Go past the plane marker
   drive_brake();
   turn_right_90();      //Use wheel encoders to make precise 90 degree turn
}      

//**************************** ONE_TO_TWO FUNCTION *****************************

void one_to_two (void)
{
   turn_left();
   while((PORTA & FarRight)== 0) 
      {trackline();}    //Go to the intersection
   left_encoder(19);  //Past the intersection (for easier turning)
   drive_brake();
   turn_right();
   while((PORTA & FarRight)== 0) 
      {trackline();}    //Go to the intersection
   left_encoder_line(18);  //Past the intersection
   drive_brake();
   turn_right();
   delay(200);
   while(PORTA != PlaneMarker)
      {trackline();}    //Go to the plane marker
   left_encoder_line(43);  //Past the plane marker
   drive_brake();
   turn_left_90();      //Use wheel encoders to make precise 90 degree turn
}

//**************************** ONE_TO_THREE FUNCTION ***************************            

void one_to_three (void)
{
   turn_left();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_right();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_left();
   while(PORTA != PlaneMarker)
      {trackline();}    //Go to the plane marker
   delay(200);          //Go past the plane marker
   drive_brake();
   turn_right_90();      //Use wheel encoders to make precise 90 degree turn
}

//**************************** TWO_TO_ONE FUNCTION *****************************

void two_to_one (void)
{
   turn_left();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_left();
   while(PORTA != FarLeft) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_left();
   while(PORTA != PlaneMarker)
      {trackline();}    //Go to the plane marker
   delay(200);          //Go past the plane marker
   drive_brake();
   turn_left_90();      //Use wheel encoders to make precise 90 degree turn
}

//**************************** TWO_TO_THREE FUNCTION ***************************

void two_to_three (void)
{
   turn_left();
   while((PORTA & FarRight) == 0) 
      {trackline();}    //Go to the intersection
   delay(1000);  //Go through intersection
   while(PORTA != PlaneMarker)
      {trackline();}    //Go to the plane marker
   left_encoder_line(43);  //Go past the plane marker
   drive_brake();
   turn_right_90();      //Use wheel encoders to make precise 90 degree turn
}   

//**************************** THREE_TO_ONE FUNCTION ***************************

void three_to_one (void)
{
   turn_right();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_right();
   while(PORTA != FarLeft) 
      {trackline();}    //Go to the intersection
   delay(120);          //Small delay to allow robot to go past the intersection
   drive_brake();
   turn_left();
   while(PORTA != PlaneMarker)
      {trackline();}    //Go to the plane marker
   delay(200);          //Go past the plane marker
   drive_brake();
   turn_left_90();      //Use wheel encoders to make precise 90 degree turn
} 

//**************************** THREE_TO_TWO FUNCTION ***************************

void three_to_two (void)
{
   turn_right();
   while(PORTA != All) 
      {trackline();}    //Go to the intersection
   delay(100);          //Small delay to allow robot to go past the intersection
   while(PORTA != PlaneMarker)
      {trackline();}    //Go to the plane marker
   delay(200);          //Go past the plane marker
   drive_brake();
   turn_left_90();      //Use wheel encoders to make precise 90 degree turn
}           

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

//SONAR_TEST

void sonar_test (void)
{
   drive_dir(Forward);
   while(1)
   {
      sonar();
      if((SRange > 24)&(SRange < 36))
      {wheelspeed(100, 100);}
      if((SRange > 12)&(SRange < 24))
      {wheelspeed(50, 50);}
      if((SRange > 6)&(SRange < 12))
      {wheelspeed(20, 20);}  
   }
}

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