//
// PWM section
//
// Ability to convert/revert Port T channel from output <-> PWM
//      channel 1 - 16 bit PWM on Port T:1
//      channel 3 - 16 bit PWM on Port T:3
//      channel 5 - 16 bit PWM on Port T:5

// sets up 3x16 bit PWMs each exactly the same on 1,3,5
void PWM_Init(void){
   PWME = 0x00;        // All PWM turned OFF
   PWMPOL = 0xFF;     // PWM goes high during duty cycle
   PWMCLK = 0x00;     // set "A Clock" as input clock for PWM   - XXX check
   PWMPRCLK = 0x77;   // 0x33 is old value XXX // bus clock divide by 8 to get "A Clock"
                      // 24Mhz (bus clock) - > 333ns per "A Clock" tick
   PWMCAE = 0x00;     // PWM is left aligned for all channels
   PWMCTL = 0x70;     // Make 3x16 bit PWMs from 6x8 bit ones
}

// Enable channel to become PWM
void PWM_Enable(BYTE channel){
   PWME &= bit(channel);
}

// Releases channel from PWM
void PWM_Release(BYTE channel){
   PWME &= ~(bit(channel));
}

// Duty cycle for the PWM
void PWM_DutyCycle(BYTE channel, WORD dutyCycle){
   switch (channel) {
   case 1:
      PWMDTY01 = dutyCycle;
   case 3:
      PWMDTY23 = dutyCycle;
   case 5:
      PWMDTY45 = dutyCycle;
   }
}

//set the period of the PWM
void PWM_Period(BYTE channel, WORD period){
   switch (channel) {
   case 1:
      PWMPER01 = period;
   case 3:
      PWMPER23 = period;
   case 5:
      PWMPER45 = period;
   }
}



// modifies channel to be PWM for RC servo motors
// They expect 20ms period with 1-2ms duty cycle
// value for rotation is 0(min)-255(max)
#define RCServoPeriod 60000
#define RCServoMinDutyCycle RCServoPeriod /20
void PWM_RCServo(BYTE channel, BYTE value){
   const unsigned long RCServoDutyCycle = RCServoMinDutyCycle + (value * RCServoMinDutyCycle)/255;
   PWM_Period(channel, RCServoPeriod);
   PWM_DutyCycle(channel, RCServoDutyCycle);
}

