/*
Matt Hobson
ELEN 599
Spring 2006
File Name: PWM.c
File Purpose: Initialize the registers related to PWM for operation with the 
              DC motors aboard the IEEE 2006 Robot.  Also, contains all the 
			  PWM-related code.
			  
			  PortP: 
			         0 = Left drive motor
					 1 = Right drive motor
					 2 = Arm motor
					 3 = Chute motor
					 4 = Gripper motor
			   
			   All motors will use the same frequency PWM signal 
			  
*/

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

#include <mc9s12dp256.h>

//********************************** DEFINE ************************************

#define PERIOD 254  //Clock A count required to yield 42.3us period (23.6kHz)
#define PWMOFF 0  //Minimum duty cycle for the PWM signal

//**************************** PWM_INIT FUNCTION *******************************

void PWM_Init (void)
{
  PWMCLK = 0x00;    //Select clock A (for 0,1,and 4), and clock B (for 2 and 3)
  PWMPRCLK = 0x22;  //Set prescale to (bus frequency) / 4 for clocks A and B 
  PWMCTL = 0x00;    //No concatenation
  PWMPOL = 0xFF;    //Set all PWM channel polarity as high (normal PWM operation)
  PWMCAE = 0x00;    //Operate in left-aligned mode
  PWMPER0 = PERIOD; //Set the period register to generate a 23.5kHz signal
  PWMDTY0 = PWMOFF; //Set duty cycle to off: Left Drive Motor
  PWMPER1 = PERIOD; //Set the period register to generate a 23.5kHz signal
  PWMDTY1 = PWMOFF; //Set duty cycle to off: Right Drive Motor
  PWMPER2 = PERIOD; //Set the period register to generate a 23.5kHz signal
  PWMDTY2 = PWMOFF; //Set duty cycle to off: Arm Motor
  PWMPER3 = PERIOD; //Set the period register to generate a 23.5kHz signal
  PWMDTY3 = PWMOFF; //Set duty cycle to off: Elevator Motor
  PWMPER4 = PERIOD; //Set the period register to generate a 23.5kHz signal
  PWMDTY4 = PWMOFF; //Set duty cycle to off: Gripper Motor
  PWME = 0x01F;      //Enable the PWM channels 0, 1, 2, 3, and 4
}

//**************************** WHEELSPEED FUNCTION *****************************

void wheelspeed (unsigned char speedL, unsigned char speedR)  
{
   PWMDTY0 = speedL;  //Controls the speed of the two sets of drive motors
   PWMDTY1 = speedR;
}

//**************************** ARM_SPEED FUNCTION ******************************

void arm_speed (unsigned char Aspeed)
{
   PWMDTY2 = Aspeed;  //Control the speed of the arm motor
}

//************************** ELEVATOR_SPEED FUNCTION ***************************

void elevator_speed (unsigned char Espeed)
{
   PWMDTY3 = Espeed;  //Control the speed of the elevator motor
}

//************************** GRIPPER_SPEED FUNCTION ****************************

void gripper_speed (unsigned char Gspeed)
{
   PWMDTY4 = Gspeed;  //Control the speed of the gripper motor
}

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