/** ###################################################################
**     THIS BEAN MODULE IS GENERATED BY THE TOOL. DO NOT MODIFY IT.
**     Filename  : BUZZER.C
**     Project   : PE_LL64_Demo
**     Processor : MC9S08LL64C_LQFP80
**     Beantype  : PWM
**     Version   : Bean 02.207, Driver 01.23, CPU db: 3.00.018
**     Compiler  : CodeWarrior HCS08 C Compiler
**     Date/Time : 8/14/2009, 5:48 PM
**     Abstract  :
**         This bean implements a pulse-width modulation generator
**         that generates signal with variable duty and fixed cycle. 
**     Settings  :
**         Used output pin             : 
**             ----------------------------------------------------
**                Number (on package)  |    Name
**             ----------------------------------------------------
**                       41            |  PTC2_TPM1CH0
**             ----------------------------------------------------
**
**         Timer name                  : TPM1 [16-bit]
**         Counter                     : TPM1CNT   [$0041]
**         Mode register               : TPM1SC    [$0040]
**         Run register                : TPM1SC    [$0040]
**         Prescaler                   : TPM1SC    [$0040]
**         Compare register            : TPM1C0V   [$0046]
**         Flip-flop register          : TPM1C0SC  [$0045]
**
**         Interrupt name              : Vtpm1ch0
**         Interrupt enable reg.       : TPM1C0SC  [$0045]
**         Priority                    : 
**         User handling procedure     : BUZZER_OnEnd
**         This event is called when the 1 of cycles is generated
**
**         Port name                   : PTC
**         Bit number (in port)        : 2
**         Bit mask of the port        : $0004
**         Port data register          : PTCD      [$0004]
**         Port control register       : PTCDD     [$0005]
**
**         Initialization:
**              Output level           : low
**              Timer                  : Enabled
**              Event                  : Enabled
**         High speed mode
**             Prescaler               : divide-by-1
**             Clock                   : 9961472 Hz
**           Initial value of            period     pulse width
**             Xtal ticks              : 26         26
**             microseconds            : 800        800
**             milliseconds            : 1          1
**             seconds (real)          : 0.000799982171 0.000799982171
**
**     Contents  :
**         SetRatio16 - byte BUZZER_SetRatio16(word Ratio);
**         SetDutyUS  - byte BUZZER_SetDutyUS(word Time);
**         SetDutyMS  - byte BUZZER_SetDutyMS(word Time);
**
**     Copyright : 1997 - 2009 Freescale Semiconductor, Inc. All Rights Reserved.
**     
**     http      : www.freescale.com
**     mail      : support@freescale.com
** ###################################################################*/


/* MODULE BUZZER. */

#include "Events.h"
#include "PE_Error.h"
#include "BUZZER.h"

#pragma MESSAGE DISABLE C5703          /* WARNING C5703: Parameter _ declared in function _ but not referenced */
#pragma MESSAGE DISABLE C2705          /* WARNING C2705: Possible loss of data */
#pragma MESSAGE DISABLE C5919          /* WARNING C5919: Conversion of floating to unsigned integral */
#pragma MESSAGE DISABLE C4002          /* Disable warning C4002 "Result not used" */

#pragma CODE_SEG BUZZER_CODE

static word RatioStore;                /* Ratio of L-level to H-level */

/* Internal method prototypes */

/*
** ===================================================================
**     Method      :  SetRatio (bean PWM)
**
**     Description :
**         The method stores duty value to compare register(s) and sets 
**         necessary bits or (in List mode) call SetReg method for duty 
**         value storing.
**         This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
static void SetRatio(void);

/* End of Internal methods declarations */

#define ratio_get_hi(A) ((*(TRatioValue *)(&A)).BB.Hi)
#define ratio_get_lo(A) ((*(TRatioValue *)(&A)).BB.Frac)
    
typedef union {
  uint16_t Value;
  struct {
    uint8_t Hi;
    uint8_t Frac;
  } BB;
} TRatioValue;
    
/*
** ===================================================================
**     Method      :  SetRatio (bean PWM)
**
**     Description :
**         The method stores duty value to compare register(s) and sets 
**         necessary bits or (in List mode) call SetReg method for duty 
**         value storing.
**         This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
static void SetRatio(void)
{
  if (RatioStore == 0xFFFFU) {         /* Duty = 100%? */
    TPM1C0V = 0xFFFFU;                 /* Store new value to the compare reg. */
  } else {
    TRatioValue Tmp1, Tmp2;
    uint16_t Result;
    Result = (uint16_t)(ratio_get_hi(RatioStore) * 0x1F); /* HI * HI */
    Tmp1.Value = (uint16_t)(ratio_get_hi(RatioStore) * 0x21); /* HI * LO */
    Result += Tmp1.BB.Hi;
    Tmp2.Value = (uint16_t)(ratio_get_lo(RatioStore) * 0x1F); /* LO * HI */
    Result += Tmp2.BB.Hi;
    if ((Tmp2.BB.Frac += Tmp1.BB.Frac) < Tmp1.BB.Frac) {
      ++Result;                        /* carry to result */
    }
    Tmp1.Value = (uint16_t)(ratio_get_lo(RatioStore) * 0x21); /* LO * LO */
    if ((Tmp1.BB.Hi += Tmp2.BB.Frac) < Tmp2.BB.Frac) {
      ++Result;                        /* carry to result */
    }
    if (Tmp1.BB.Hi >= 0x80) {
      ++Result;                        /* round */
    }
    TPM1C0V = Result;
  }
}

/*
** ===================================================================
**     Method      :  BUZZER_SetRatio16 (bean PWM)
**
**     Description :
**         This method sets a new duty-cycle ratio.
**     Parameters  :
**         NAME       - DESCRIPTION
**         Ratio      - Ratio is expressed as an 16-bit unsigned integer
**                      number. 0 - 0xFFFF value is proportional
**                      to ratio 0 - 100%
**         Note: Calculated duty depends on the timer possibilities
**               and on the selected period.
**     Returns     :
**         ---        - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
** ===================================================================
*/
byte BUZZER_SetRatio16(word Ratio)
{
  RatioStore = Ratio;                  /* Store new value of the ratio */
  SetRatio();                          /* Calculate and set up new appropriate values of the compare and modulo registers */
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BUZZER_SetDutyUS (bean PWM)
**
**     Description :
**         This method sets the new duty value of the output signal.
**         The duty is expressed in microseconds as a 16-bit
**         unsigned integer number.
**     Parameters  :
**         NAME            - DESCRIPTION
**         Time            - Duty to set [in microseconds]
**                      (0 to 800 us in high speed mode)
**     Returns     :
**         ---             - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
**                           ERR_MATH - Overflow during evaluation
**                           ERR_RANGE - Parameter out of range
** ===================================================================
*/
byte BUZZER_SetDutyUS(word Time)
{
  dlong rtval;                         /* Result of two 32-bit numbers multiplication */
  if (Time > 0x0320U) {                /* Is the given value out of range? */
    return ERR_RANGE;                  /* If yes then error */
  }
  PE_Timer_LngMul((dword)Time, 0x51EBFCC5LU, &rtval); /* Multiply given value and High speed CPU mode coefficient */
  if (PE_Timer_LngHi3(rtval[0], rtval[1], &RatioStore)) { /* Is the result greater or equal than 65536 ? */
    RatioStore = 0xFFFFU;              /* If yes then use maximal possible value */
  }
  SetRatio();                          /* Calculate and set up new appropriate values of the compare and modulo registers */
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BUZZER_SetDutyMS (bean PWM)
**
**     Description :
**         This method sets the new duty value of the output signal.
**         The duty is expressed in milliseconds as a 16-bit
**         unsigned integer number.
**     Parameters  :
**         NAME            - DESCRIPTION
**         Time            - Duty to set [in milliseconds]
**                      (0 to 1 ms in high speed mode)
**     Returns     :
**         ---             - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
**                           ERR_MATH - Overflow during evaluation
**                           ERR_RANGE - Parameter out of range
** ===================================================================
*/
byte BUZZER_SetDutyMS(word Time)
{
  dlong rtval;                         /* Result of two 32-bit numbers multiplication */
  if (Time > 0x01U) {                  /* Is the given value out of range? */
    return ERR_RANGE;                  /* If yes then error */
  }
  PE_Timer_LngMul((dword)Time, 0x014001D3LU, &rtval); /* Multiply given value and High speed CPU mode coefficient */
  if (PE_Timer_LngHi1(rtval[0], rtval[1], &RatioStore)) { /* Is the result greater or equal than 65536 ? */
    RatioStore = 0xFFFFU;              /* If yes then use maximal possible value */
  }
  SetRatio();                          /* Calculate and set up new appropriate values of the compare and modulo registers */
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BUZZER_Init (bean PWM)
**
**     Description :
**         Initializes the associated peripheral(s) and the beans 
**         internal variables. The method is called automatically as a 
**         part of the application initialization code.
**         This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
void BUZZER_Init(void)
{
  /* TPM1SC: TOF=0,TOIE=0,CPWMS=0,CLKSB=0,CLKSA=0,PS2=0,PS1=0,PS0=0 */
  setReg8(TPM1SC, 0x00);               /* Disable device */ 
  /* TPM1C0SC: CH0F=0,CH0IE=0,MS0B=1,MS0A=1,ELS0B=1,ELS0A=1,??=0,??=0 */
  setReg8(TPM1C0SC, 0x3C);             /* Set up PWM mode with output signal level low */ 
  RatioStore = 0xFFFFU;                /* Store initial value of the ratio */
  /* TPM1MOD: BIT15=0,BIT14=0,BIT13=0,BIT12=1,BIT11=1,BIT10=1,BIT9=1,BIT8=1,BIT7=0,BIT6=0,BIT5=1,BIT4=0,BIT3=0,BIT2=0,BIT1=0,BIT0=0 */
  setReg16(TPM1MOD, 0x1F20U);          /* Set modulo register */ 
  SetRatio();                          /* Calculate and set up new values of the compare according to the selected speed CPU mode */
  /* TPM1SC: TOF=0,TOIE=1,CPWMS=0,CLKSB=0,CLKSA=1,PS2=0,PS1=0,PS0=0 */
  setReg8(TPM1SC, 0x48);               /* Run the counter (set CLKSB:CLKSA) */ 
}

#pragma CODE_SEG __NEAR_SEG NON_BANKED

/*
** ===================================================================
**     Method      :  BUZZER_Interrupt (bean PWM)
**
**     Description :
**         The method services the interrupt of the selected peripheral(s)
**         and eventually invokes the beans event(s).
**         This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
ISR(BUZZER_Interrupt)
{
  (void)getReg8(TPM1SC);               /* Dummy read of the TPM1SC register to reset flag */
  /* TPM1SC: TOF=0 */
  clrReg8Bits(TPM1SC, 0x80);           /*  Reset interrupt request flag */ 
  BUZZER_OnEnd();                      /* Invoke user event */
}

#pragma CODE_SEG BUZZER_CODE

/* END BUZZER. */

/*
** ###################################################################
**
**     This file was created by Processor Expert 3.06 [04.26]
**     for the Freescale HCS08 series of microcontrollers.
**
** ###################################################################
*/
