
//
// Included Files
//
#include "f28x_project.h"
#include "sfo_v8.h"
#include <math.h>

typedef struct PIDinfo PIDinfo;
struct PIDinfo
{

};

//
// Defines
//

#define AUTOCONVERT       0       // 1 = Turn auto-conversion ON
                                  // 0 = Turn auto-conversion OFF

#define PWM_CH            5       // # of PWM channels + 1


#define PWM_FREQ 10000.0

#define DEVICE_GPIO_PIN_LED1    2
#define DEVICE_GPIO_PIN_LED2    3

enum polar {REVERSE, FORWARD};

#define PERIOD 3.14159f

//
// Globals
//
uint16_t status;
uint16_t DutyFine = 0x4000;
uint16_t CMPA_reg_val;
uint16_t CMPAHR_reg_val;
uint32_t temp, temp1;
bool polarity = FORWARD;
uint16_t lowFreqPin1 = 0, lowFreqPin2 = 1;

float globalTimer = 0.0f;
float deltaTime = (120.0f / PWM_FREQ) * PERIOD; // (cycles/second) * (second/interrupt) * (radians/cycle) = radians/interrupt

float previousError = 0, currentError, progTerm, diffTerm, Kp, Kd;

int MEP_ScaleFactor;

volatile struct EPWM_REGS *ePWM[PWM_CH] = {0, &EPwm1Regs, &EPwm2Regs,
                                           &EPwm3Regs, &EPwm4Regs};

//
// Function Prototypes
//
void initADC(void);
void InitEPwm1Gpio(void);
void initEPWM(void);
void initADCSOC(void);
__interrupt void adcA1ISR(void);
void error(void);

//
// Main
//
void main(void)
{

    //
    // Initialize device clock and peripherals
    //
    InitSysCtrl();

    //
    // Initialize GPIO
    //
    InitGpio();
    GPIO_SetupPinMux(DEVICE_GPIO_PIN_LED1, GPIO_MUX_CPU1, 0);
    GPIO_SetupPinOptions(DEVICE_GPIO_PIN_LED1, GPIO_OUTPUT, GPIO_PUSHPULL);

    GPIO_SetupPinMux(DEVICE_GPIO_PIN_LED2, GPIO_MUX_CPU1, 0);
    GPIO_SetupPinOptions(DEVICE_GPIO_PIN_LED2, GPIO_OUTPUT, GPIO_PUSHPULL);

    InitEPwm1Gpio();

    //
    // Disable CPU interrupts
    //
    DINT;

    //
    // Initialize the PIE control registers to their default state.
    // The default state is all PIE interrupts disabled and flags
    // are cleared.
    //
    InitPieCtrl();

    //
    // Disable CPU interrupts and clear all CPU interrupt flags:
    //
    IER = 0x0000;
    IFR = 0x0000;

    //
    // Initialize the PIE vector table with pointers to the shell Interrupt
    // Service Routines (ISR).
    //
    InitPieVectTable();

    // Enable global Interrupts and higher priority real-time debug events:
    //
    EINT;   // Enable Global interrupt INTM
    ERTM;   // Enable Global realtime interrupt DBGM

    status = SFO_INCOMPLETE;

    // Calling SFO() updates the HRMSTEP register with calibrated
    // MEP_ScaleFactor. HRMSTEP must be populated with a scale factor
    // value prior to enabling high resolution period control.
    //
    while(status == SFO_INCOMPLETE)
    {
        status = SFO();
        if(status == SFO_ERROR)
        {
            error();   // SFO function returns 2 if an error occurs & # of MEP
        }              // steps/coarse step exceeds maximum of 255.
    }

    //
    // Map ISR functions
    //
    EALLOW;
    PieVectTable.ADCA1_INT = &adcA1ISR;     // Function for ADCA interrupt 1
    EDIS;

    //
    // Configure the ADC and power it up
    //
    initADC();

    //
    // Configure the ePWM
    //
    initEPWM();

    //
    // Setup the ADC for ePWM triggered conversions on channel 1
    //
    initADCSOC();

    //
    // Enable global Interrupts and higher priority real-time debug events:
    //
    IER |= M_INT1;  // Enable group 1 interrupts

    EINT;           // Enable Global interrupt INTM
    ERTM;           // Enable Global realtime interrupt DBGM

    //


    //
    // Enable PIE interrupt
    //
    PieCtrlRegs.PIEIER1.bit.INTx1 = 1;

    //
    // Sync ePWM
    //
    EALLOW;
    CpuSysRegs.PCLKCR0.bit.TBCLKSYNC = 1;


    //
    // Start ePWM
    //
    EPwm1Regs.ETSEL.bit.SOCBEN = 1;    // Enable SOCB for ePWM1
    EPwm1Regs.ETSEL.bit.SOCAEN = 1;    // Enable SOCA for ePWM1
    EPwm1Regs.TBCTL.bit.CTRMODE = 0;   // Unfreeze, and enter up count mode

    //
    // Take conversions indefinitely in loop
    //
    while(1)
    {

        CMPA_reg_val = ((long)DutyFine * (EPwm1Regs.TBPRD + 1)) >> 15;
        temp = ((long)DutyFine * (EPwm1Regs.TBPRD + 1)) ;
        temp = temp - ((long)CMPA_reg_val << 15);


       #if(AUTOCONVERT)
        CMPAHR_reg_val = temp << 1; // convert to Q16
       #else
        CMPAHR_reg_val = ((temp * MEP_ScaleFactor) +
                          (0x0080 << 7)) >> 15;
        CMPAHR_reg_val = CMPAHR_reg_val << 8;

       #endif

       //
       // Example for a 32 bit write to CMPA:CMPAHR
       //
        EPwm1Regs.CMPA.all = ((long)CMPA_reg_val) << 16 |
                              CMPAHR_reg_val; // loses lower 8-bits

        EPwm1Regs.CMPB.all = ((long)CMPA_reg_val) << 16 |
                              CMPAHR_reg_val; // loses lower 8-bits

    //
    // Call the scale factor optimizer lib function SFO()
    // periodically to track for any change due to temp/voltage.
    // This function generates MEP_ScaleFactor by running the
    // MEP calibration module in the HRPWM logic. This scale
    // factor can be used for all HRPWM channels. The SFO()
    // function also updates the HRMSTEP register with the
    // scale factor value.
    //
    status = SFO(); // in background, MEP calibration module
                // continuously updates MEP_ScaleFactor

    if(status == SFO_ERROR)
    {
    error();   // SFO function returns 2 if an error occurs & #
               // of MEP steps/coarse step
    }              // exceeds maximum of 255.

        //
        // Software breakpoint. At this point, conversion results are stored in
        // adcAResults.
        //
        // Hit run again to get updated conversions.
        //
       // ESTOP0;
    }
}

//
// initADC - Function to configure and power up ADCA.
//
void initADC(void)
{
    //
    // Setup VREF as internal
    //
    SetVREF(ADC_ADCA, ADC_INTERNAL, ADC_VREF3P3);

    EALLOW;

    //
    // Set ADCCLK divider to /4
    //
    AdcaRegs.ADCCTL2.bit.PRESCALE = 6;

    //
    // Set pulse positions to late
    //
    AdcaRegs.ADCCTL1.bit.INTPULSEPOS = 1;

    //
    // Power up the ADC and then delay for 1 ms
    //
    AdcaRegs.ADCCTL1.bit.ADCPWDNZ = 1;
    EDIS;

    DELAY_US(1000);
}

//
// initEPWM - Function to configure ePWM1 to generate the SOC.
//
void initEPWM(void)
{
    EALLOW;

    EPwm1Regs.ETSEL.bit.SOCBEN = 0;     // Disable SOC on A group
    EPwm1Regs.ETSEL.bit.SOCBSEL = 4;    // Select SOC on up-count
    EPwm1Regs.ETPS.bit.SOCBPRD = 1;     // Generate pulse on 1st event

    EPwm1Regs.ETSEL.bit.SOCAEN = 0;     // Disable SOC on A group
    EPwm1Regs.ETSEL.bit.SOCASEL = 4;    // Select SOC on up-count
    EPwm1Regs.ETPS.bit.SOCAPRD = 1;     // Generate pulse on 1st event

    EPwm1Regs.TBCTL.bit.PRDLD = TB_SHADOW;
    EPwm1Regs.CMPA.bit.CMPA = (60000000 / PWM_FREQ);   // Set compare A value to 2048 counts
    EPwm1Regs.CMPB.bit.CMPB = (60000000 / PWM_FREQ);   // Set compare B value to 2048 counts
    EPwm1Regs.TBPRD = (120000000 / PWM_FREQ) - 1;           // Set period to 4096 counts
    EPwm1Regs.CMPA.bit.CMPAHR = (1 << 8);   // initialize HRPWM extension
    EPwm1Regs.CMPB.bit.CMPBHR = (1 << 8);   // initialize HRPWM extension
    EPwm1Regs.TBPHS.all = 0;
    EPwm1Regs.TBCTR = 0;

    EPwm1Regs.TBCTL.bit.CTRMODE = TB_COUNT_UP;
    EPwm1Regs.TBCTL.bit.PHSEN = TB_DISABLE;
    EPwm1Regs.EPWMSYNCINSEL.all = SYNC_IN_SRC_DISABLE_ALL;
    EPwm1Regs.EPWMSYNCOUTEN.all = SYNC_OUT_SRC_DISABLE_ALL;
    EPwm1Regs.TBCTL.bit.HSPCLKDIV = TB_DIV1;
    EPwm1Regs.TBCTL.bit.CLKDIV = TB_DIV1;
    EPwm1Regs.TBCTL.bit.FREE_SOFT = 11;

    EPwm1Regs.CMPCTL.bit.LOADAMODE = CC_CTR_ZERO;
    EPwm1Regs.CMPCTL.bit.LOADBMODE = CC_CTR_ZERO;
    EPwm1Regs.CMPCTL.bit.SHDWAMODE = CC_SHADOW;
    EPwm1Regs.CMPCTL.bit.SHDWBMODE = CC_SHADOW;

  //  EPwm1Regs.TBCTL.bit.CTRMODE = 3;    // Freeze counter

    GpioCtrlRegs.GPADIR.bit.GPIO0 = 1;
    GpioCtrlRegs.GPADIR.bit.GPIO1 = 1;
    EPwm1Regs.AQCTLA.bit.ZRO = AQ_SET;      // PWM toggle high/low
    EPwm1Regs.AQCTLA.bit.CAU = AQ_CLEAR;
    EPwm1Regs.AQCTLB.bit.ZRO = AQ_CLEAR;
    EPwm1Regs.AQCTLB.bit.CBU = AQ_SET;


    EALLOW;
    EPwm1Regs.HRCNFG.all = 0x0;
    EPwm1Regs.HRCNFG.bit.EDGMODE = HR_FEP;  // MEP control on falling edge
    EPwm1Regs.HRCNFG.bit.CTLMODE = HR_CMP;
    EPwm1Regs.HRCNFG.bit.HRLOAD  = HR_CTR_ZERO;
    EPwm1Regs.HRCNFG.bit.EDGMODEB = HR_FEP; // MEP control on falling edge
    EPwm1Regs.HRCNFG.bit.CTLMODEB = HR_CMP;
    EPwm1Regs.HRCNFG.bit.HRLOADB  = HR_CTR_ZERO;
    #if(AUTOCONVERT)
    EPwm1Regs.HRCNFG.bit.AUTOCONV = 1;      // Enable auto-conversion
                                             // logic
    #endif
    EPwm1Regs.HRPCTL.bit.HRPE = 0; // Turn off high-resolution period
                                    // control.
    EDIS;
}

//
// initADCSOC - Function to configure ADCA's SOC0 to be triggered by ePWM1.
//
void initADCSOC(void)
{
    //
    // Select the channels to convert and the end of conversion flag
    //
    EALLOW;

    AdcaRegs.ADCSOC0CTL.bit.CHSEL = 1;     // SOC0 will convert pin A1
                                           // 0:A0  1:A1  2:A2  3:A3
                                           // 4:A4   5:A5   6:A6   7:A7
                                           // 8:A8   9:A9   A:A10  B:A11
                                           // C:A12  D:A13  E:A14  F:A15
    AdcaRegs.ADCSOC0CTL.bit.ACQPS = 80;     // Sample window is 10 SYSCLK cycles
    AdcaRegs.ADCSOC0CTL.bit.TRIGSEL = 5;   // Trigger on ePWM1 SOCA

    AdcaRegs.ADCINTSEL1N2.bit.INT1SEL = 0; // End of SOC0 will set INT1 flag
    AdcaRegs.ADCINTSEL1N2.bit.INT1E = 1;   // Enable INT1 flag
    AdcaRegs.ADCINTFLGCLR.bit.ADCINT1 = 1; // Make sure INT1 flag is cleared

    EDIS;
}

//
// adcA1ISR - ADC A Interrupt 1 ISR
//
__interrupt void adcA1ISR(void)
{
    //
    // Add the latest result to the buffer
    // ADCRESULT0 is the result register of SOC0
   // adcResult = AdcaResultRegs.ADCRESULT0;


    globalTimer += deltaTime;

    if (polarity == FORWARD)
        currentError = (0.5f + (sin(globalTimer) / 2.0f)) - (AdcaResultRegs.ADCRESULT0 / 3500.0f);
    else
        currentError = (AdcaResultRegs.ADCRESULT0 / 3500.0f) - (0.5f - (sin(globalTimer) / 2.0f));


    progTerm = currentError * 2.0f;

    diffTerm = currentError - previousError;

    DutyFine = 0x7FDF * progTerm;

    if ((PERIOD - globalTimer) < 0.005)
    {
        globalTimer = 0.0f;

        polarity = !polarity;

        if (polarity == FORWARD)
        {
            EALLOW;
            EPwm1Regs.AQCTLA.bit.ZRO = AQ_SET;      // PWM toggle high/low
            EPwm1Regs.AQCTLA.bit.CAU = AQ_CLEAR;
            EPwm1Regs.AQCTLB.bit.ZRO = AQ_CLEAR;
            EPwm1Regs.AQCTLB.bit.CBU = AQ_SET;
            EDIS;

            GPIO_WritePin(DEVICE_GPIO_PIN_LED1, 0);
            GPIO_WritePin(DEVICE_GPIO_PIN_LED2, 1);
        }
        else
        {
            EALLOW;
            EPwm1Regs.AQCTLA.bit.ZRO = AQ_CLEAR;      // PWM toggle high/low
            EPwm1Regs.AQCTLA.bit.CAU = AQ_SET;
            EPwm1Regs.AQCTLB.bit.ZRO = AQ_SET;
            EPwm1Regs.AQCTLB.bit.CBU = AQ_CLEAR;
            EDIS;

            GPIO_WritePin(DEVICE_GPIO_PIN_LED1, 1);
            GPIO_WritePin(DEVICE_GPIO_PIN_LED2, 0);
        }

    }


    if (DutyFine < 0x21)
        DutyFine = 0x21;
    else if (DutyFine > 0x7FDF)
        DutyFine = 0x7FDF;

    previousError = currentError;


    //
    // Clear the interrupt flag
    //
    AdcaRegs.ADCINTFLGCLR.bit.ADCINT1 = 1;

    //
    // Check if overflow has occurred
    //
    if(1 == AdcaRegs.ADCINTOVF.bit.ADCINT1)
    {
        AdcaRegs.ADCINTOVFCLR.bit.ADCINT1 = 1; //clear INT1 overflow flag
        AdcaRegs.ADCINTFLGCLR.bit.ADCINT1 = 1; //clear INT1 flag
    }

    //
    // Acknowledge the interrupt
    //
    PieCtrlRegs.PIEACK.all = PIEACK_GROUP1;
}

// error - Halt debugger when called
//
void error (void)
{
    ESTOP0;         // Stop here and handle error
}

//
// End of File
//
