#ifndef PWM_H
#define PWM_H

#include "Motor.h"

enum PwmMod {ForceLow = 0, ForceHi = 1, ActiveHi = 2, ActiveLow = 3};
// <<< Use Configuration Wizard in Context Menu >>>
// <o> Set MPWM SWAP <0x00=> MDRF05/MDRF40 <0x70=> MDRFA0/MDRFD0
#define SWAP 0x70

// <h> Set MPWMDATA 
// <i> The frequency of MPWMDATA is 48MHz
// <o> Set PWM Frequency (unit : Hz) <12000-40000 : 10>
// <i> unit : Hz
// </h>
#define PWM_FREQ 27000
#define MPWMDATA_REGS (unsigned short) ((48000000/PWM_FREQ)/2)

// <h> Set MPWMINV 
// <o.0> U INV <0=> Non-Inverse <1=> Inverse
// <o.1> X INV <0=> Non-Inverse <1=> Inverse
// <o.2> V INV <0=> Non-Inverse <1=> Inverse
// <o.3> Y INV <0=> Non-Inverse <1=> Inverse
// <o.4> W INV <0=> Non-Inverse <1=> Inverse
// <o.5> Z INV <0=> Non-Inverse <1=> Inverse
// </h>
 #define MPWMINV_REGS 0x00
 
// <h> Set MPWMDB
// <i> The frequency of MPWMDB is 48MHz
// <o> Deadband Time 
// <0x30=> Deadband Time 1us
// <0x48=> Deadband Time 1.5us
// <0x60=> Deadband Time 2us
// <0x90=> Deadband Time 3us
// <0xC0=> Deadband Time 4us
// <0xF0=> Deadband Time 5us
// <i> 0x30 : 48MHz * 48 = 1us
// </h>
#define MPWMDB_REGS 0x60 

#define PWM_Frequency PWM_FREQ
#define PWM_Counter MPWMDATA_REGS
// 1rps (rad/sec) = 1/60 rpm, w = 2Pi = 1rps
// 0 ~ 24512 is Electrical Degree 0~360 deg
// AngleBase formula : AngleBase = 24512 * (1/PWM_Frequency) * (1/60) * 32767
//#define AngleBase (long) ((float) (24512 * (1/PWM_Frequency) * (1/60)) * 32767)
//#define AngleBase (long) ((float) 13386411/PWM_Frequency)

// <o> BASE_RPM (unit : rpm)
// <i> Base_Rpm : (32767 / POLE_PAIRS)
#define BASE_RPM 32767
#define AngleBase (long) ((float) BASE_RPM * POLE/120 * 24512/PWM_Frequency)

//#define AngleBase (long) ((float) BASE_RPM * POLE_PAIRS * 24512 / PWM_Frequency / 60)
// ex. AngleBase (long) ((float) 100 * 24512 / PWM_Frequency)
//     3000(rpm) * (Pole/2) * 24512 / 60 / AngleBaseShift
// 24512 = 16KHz = 16Hz = 32767 (PLL_OUT)
// 24512 = 20KHz = 20Hz = 32767 (PLL_OUT)

// <<< end of configuration section >>>

extern void PWM_SetBreakForce (void);
extern void PWM_SetBreak (void);
extern void PWM_SetAllOff (void);
extern void PWM_SetActive (void);
extern void PWM_Init (void);
extern void PWM_Duty (unsigned short PwmDuty);
#endif