DSP

关于dsp移相全桥dc-dc变换器实现代码

2019-07-13 10:32发布

    此代码仅供大家学习该项目使用前参考,让大家更好的学习。               //---------------------------------------------------------------------------------- // FILE: FBPS_Main.C
//
// Description:C source for DC/DC control loop using phase shifted full bridge
// driver 
//
// Version: 1.0
//
//  Target:   TMS320F280x or F2833x
//
//----------------------------------------------------------------------------------
//  Copyright Texas Instruments ?2008
//----------------------------------------------------------------------------------
//  Revision History:
//----------------------------------------------------------------------------------
//  Date  | Description / Status
//----------------------------------------------------------------------------------
// 19-Mar-08 | Release 1.0 FBPS Internal release (HRN)
//----------------------------------------------------------------------------------
//
// PLEASE READ - Useful notes about this Project


// Although this project is made up of several files, the most important ones are:
// "FBPS-Main.C"- this file
// - Application Initialization, Peripheral config,
// - Application management
// - Slower background code loops and Task scheduling
// "FBPS-DevInit_F28xxx.C
// - Device Initialization, e.g. Clock, PLL, WD, GPIO mapping
// - Peripheral clock enables
// - DevInit file will differ per each F28xxx device series, e.g. F280x, F2833x,
// "FBPS-ISR.asm
// - Assembly level library Macros and any cycle critical functions are found here
// "ProjectSettings.h"
// - Global defines (settings) project selections are found here
// - This file is referenced by both C and ASM files.


// Code is made up of sections, e.g. "FUNCTION PROTOTYPES", "VARIABLE DECLARATIONS" ,..etc
// each section has FRAMEWORK and USER areas.
//  FRAMEWORK areas provide useful ready made "infrastructure" code which for the most part
// does not need modification, e.g. Task scheduling, ISR call, GUI interface support,...etc
//  USER areas have functional example code which can be modified by USER to fit their appl.
//
// Variables or parameters used for Multiple Channels are stored in Arrays,
// the array index is the channel number, note: element zero (index=0) is not used
//
// Code can be compiled with various build options (Incremental Builds IBx), these
//  options are selected in file "ProjectSettings.h".  Note: "Rebuild All" compile
//  tool bar button must be used if this file is modified.
//----------------------------------------------------------------------------------

#include "ProjectSettings.h"
#include "PeripheralHeaderIncludes.h"
#include "DSP280x_EPWM_defines.h"
#include "dlog4ch.h"
 
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// FUNCTION PROTOTYPES
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


// -------------------------------- FRAMEWORK --------------------------------------
void DeviceInit(void);
void ISR_Init(void);
void ISR_Run(void);
void SCIA_Init();
void SerialHostComms();
void InitFlash(); 




// State Machine function prototypes
//------------------------------------
// Alpha states
void A0(void); //state A0 
void B0(void); //state B0
void C0(void); //state C0


// A branch states
void A1(void); //state A1
void A2(void); //state A2
void A3(void); //state A3
void A4(void); //state A4


// B branch states
void B1(void); //state B1
void B2(void); //state B2
void B3(void); //state B3
void B4(void); //state B4


// C branch states
void C1(void); //state C1
void C2(void); //state C2
void C3(void); //state C3
void C4(void); //state C4


// Variable declarations
void (*Alpha_State_Ptr)(void); // Base States pointer
void (*A_Task_Ptr)(void); // State pointer A branch
void (*B_Task_Ptr)(void); // State pointer B branch
void (*C_Task_Ptr)(void); // State pointer C branch




// ---------------------------------- USER -----------------------------------------
void FullBridgePS_CNF(int16 n, int16 period);
void ADC_CascSeqCNF(int ChSel[], int ACQPS, int Conv, int mode);
void ADC_DualSeqCNF(int ChSel[], int ACQPS, int Conv, int mode); 




//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// VARIABLE DECLARATIONS - GENERAL
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


// -------------------------------- FRAMEWORK --------------------------------------


int16 VTimer0[4];// Virtual Timers slaved of CPU Timer 0 (A events)
int16 VTimer1[4]; // Virtual Timers slaved of CPU Timer 1 (B events)
int16 VTimer2[4]; // Virtual Timers slaved of CPU Timer 2 (C events)
int16 SerialCommsTimer;
int16 CommsOKflg;
//int16 HRmode;from 8-ch
//int16 BlinkStatePtr, LED_TaskPtr; from 8-ch


// Used to indirectly access all EPWM modules, very useful!
volatile struct EPWM_REGS *ePWM[] = 
   { &EPwm1Regs,// intentional (ePWM[0] not used)
&EPwm1Regs,  
&EPwm2Regs,
&EPwm3Regs,
&EPwm4Regs,
&EPwm5Regs,
&EPwm6Regs,
#ifdef DSP2804x_DEVICE_H
&EPwm7Regs,
&EPwm8Regs
#endif
 }; 


// Used for running BackGround in flash, and ISR in RAM
extern Uint16 *RamfuncsLoadStart, *RamfuncsLoadEnd, *RamfuncsRunStart;




// ---------------------------------- USER -----------------------------------------


int16 AdcNetBus[NumChannels+1];  // used as consecutive addresses for ADC_Rslts


// Control block Coeficients
long Coef2P2Z_1[7], Coef2P2Z_2[7];


// Variable Declaration


long DataLogTrigger;
int ChSel[16];


int phase,dbLeft,dbRight; // FB Phase command and Dead band
// adjust for the right and left legs
int Vref = 0; // FB Set Voltage
int Iref = 0; // FB Current Loop Command


int16   fbps_slew_temp = 0; // Temp variable: used only if implementing 
// slew rate control in the slower state machine


int16   fbpsSetSlewed = 0; // Slewed set point for the FB voltage loop
int16   fbpsSlewRate = 0; // FB Slew rate adjustment  


// Datalog Module
DLOG_4CH dlog = DLOG_4CH_DEFAULTS;


long Pgain, Igain, Dgain, Dmax;  //for Voltage loop
long Pgain_I, Igain_I, Dgain_I, Dmax_I;  //for Current loop


int calc_flag = 0; // Setting this flag re-calculates control loop coefficients


// ASM Module Terminal pointers and variables
extern int16 *ADC_Rslt;
extern int16 *CNTL_2P2Z_Ref1, *CNTL_2P2Z_Out1, *CNTL_2P2Z_Fdbk1;
extern int16 *CNTL_2P2Z_Ref2, *CNTL_2P2Z_Out2, *CNTL_2P2Z_Fdbk2;
extern long *CNTL_2P2Z_Coef1, *CNTL_2P2Z_Coef2; 


// FBPS_DRV
extern int16 *FBPS_phase1, *FBPS_dbLeft1, *FBPS_dbRight1;
extern int16 *FBPS_phase2, *FBPS_dbLeft2, *FBPS_dbRight2;
extern int16 *FBPS_phase3, *FBPS_dbLeft3, *FBPS_dbRight3;


// SLEW_LIMIT
extern int16 *SLEW_LIMIT_In1, *SLEW_LIMIT_Incr1, *SLEW_LIMIT_Out1;
extern int16 *SLEW_LIMIT_In2, *SLEW_LIMIT_Incr2, *SLEW_LIMIT_Out2; 


// HR_FBPS_DRV -- Not Used
extern int16 *FBPS_phase, *FBPS_dbLeft, *FBPS_dbRight;
extern int16 SFFBPS; 




//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// VARIABLE DECLARATIONS - CCS WatchWindow / GUI support
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


// -------------------------------- FRAMEWORK --------------------------------------


//GUI support variables - No GUI for FBPS Only project
// sets a limit on the amount of external GUI controls - increase as necessary
int16 *varSetTxtList[64];//64 textbox controlled variables
int16 *varSetBtnList[16];//16 button controlled variables
int16 *varSetSldrList[16];//16 slider controlled variables
int16 *varGetList[16];//16 variables sendable to GUI
int16 *arrayGetList[16];//16 arrays sendable to GUI


// ---------------------------------- USER -----------------------------------------


// Monitor ("Get") // Display as:
int16 Gui_Vfbin;// Q8
int16 Gui_Ifb;// Q12
int16 Gui_Vfbout;// Q10


/*int16 Pgain;// "counts" (Q0) 
int16 Igain; // "counts" (Q0) 
int16 Dgain; // "counts" (Q0) 
*/


int16 Gui_VfbSet = 0;// Q10 
int16 Gui_IfbSet = 0;// Q12 -- Build 3 Only 


//Scaling Constants (values found via spreadsheet)
int16 K_Vfbin;// Q15
int16 K_Ifb; // Q15
int16 K_Vfbout;// Q15 


int16 iK_Ifb; // Q14
int16 iK_Vfbout;// Q14 


// Variables for background support only (no need to access)
int16 i; // common use incrementer
int16 HistPtr, temp_Scratch;
int16 temp_ChNum, temp_Iout;


int16 Vset[NumChannels+1];// Per Unit (Q15) 
int16 Vmargin[NumChannels+1];// Per Unit (Q15) 


// History arrays are used for Running Average calculation (boxcar filter)
// Used for CCS display and GUI only, not part of control loop processing
int16 Hist_Vfbin[HistorySize];
int16 Hist_Ifb[HistorySize];
int16 Hist_Vfbout[HistorySize];




void main(void)
{
//=================================================================================
// INITIALISATION - General
//=================================================================================


//-------------------------------- FRAMEWORK --------------------------------------


DeviceInit(); // Device Life support & GPIO
// SCIA_Init();  // Initalize the Serial Comms A peripheral


// Only used if running from FLASH
#ifdef FLASH
// Copy time critical code and Flash setup code to RAM
// The  RamfuncsLoadStart, RamfuncsLoadEnd, and RamfuncsRunStart
// symbols are created by the linker. Refer to the linker files. 
MemCopy(&RamfuncsLoadStart, &RamfuncsLoadEnd, &RamfuncsRunStart);


// Call Flash Initialization to setup flash waitstates
// This function must reside in RAM
InitFlash(); // Call the flash wrapper init function
#endif //(FLASH)


// Timing sync for background loops
// Timer period definitions found in PeripheralHeaderIncludes.h
CpuTimer0Regs.PRD.all =  mSec1;// A tasks
CpuTimer1Regs.PRD.all =  mSec5;// B tasks
CpuTimer2Regs.PRD.all =  mSec0_5;// C tasks


// Tasks State-machine init
Alpha_State_Ptr = &A0;
A_Task_Ptr = &A1;
B_Task_Ptr = &B1;
C_Task_Ptr = &C1;


VTimer0[0] = 0;
VTimer1[0] = 0;VTimer1[1] = 0;
VTimer2[0] = 0;
CommsOKflg = 0;


HistPtr = 0;

// ---------------------------------- USER -----------------------------------------


//Configure Scaling Constants
K_Vfbin = 18432;// 0.5625 in Q15 (see excel spreadsheet)


K_Ifb = 21670;// 0.6600 in Q15 (see excel spreadsheet)


K_Vfbout = 24578;// 0.7501 in Q15 (see excel spreadsheet)


iK_Ifb = 24775;// 1.5152 in Q14 (see excel spreadsheet)


iK_Vfbout = 21844;// 1.3332 in Q14 (see excel spreadsheet)




//==================================================================================
// INCREMENTAL BUILD OPTIONS - NOTE: select via ProjectSettings.h
//==================================================================================
// ---------------------------------- USER -----------------------------------------
//==============================================================================
#if (INCR_BUILD == 1) // Open loop FBPS drive to excite power stage
//=============================================================
#define prd 500 // Period count = 200 KHz @ 100 MHz


FullBridgePS_CNF(2, prd); // ePWM2 and ePWM3, Period=prd
ISR_Init(); // ASM ISR init


// Lib Module connection to "nets" 
//----------------------------------------
// Connect the FBPS PWM generator block:  
FBPS_phase2   = &phase;// Point to the phase net
FBPS_dbLeft2  = &dbLeft;// Point to the left leg dead band adjust
FBPS_dbRight2 = &dbRight;// Point to the right leg dead band adjust


phase    = 0;
dbLeft   = 20;
dbRight  = 18; 


GpioDataRegs.GPASET.bit.GPIO16 = 1;// Disable PFC FET driver


#endif //  (INCR_BUILD == 1) Open loop FBPS drive to excite power stage


//=============================================================
#if (INCR_BUILD == 2) // Open loop FBPS drive + ADC feedback
//=============================================================
#define prd 500 // Period count = 200 KHz @ 100 MHz


// "Raw" (R) ADC measurement name defines
#define IfbR AdcMirror.ADCRESULT0 //
#define Vfb_outRAdcMirror.ADCRESULT1 //
#define Vfb_inRAdcMirror.ADCRESULT2//


// Channel Selection for Cascaded Sequencer
ChSel[0] =  1;// A1 - FBPS Transformer Primary Current
ChSel[1] =  0;// A0 - FBPS O/P Voltage
ChSel[2] = 11;// B3 - FBPS I/P Voltage


FullBridgePS_CNF(2, prd); // ePWM2 and ePWM3, Period=prd


ADC_CascSeqCNF(ChSel, 2, 3, 0);// ACQPS=2, #Conv=3, Mode= Start/Stop (0)


// Configure the Start of Conversion for the ADC.
// At TBCNT3 = (TBPRD3 + TBPHS3)/2 SOCA is triggered
EPwm3Regs.ETSEL.bit.SOCAEN  =  1;
EPwm3Regs.ETSEL.bit.SOCASEL =  ET_CTRU_CMPB; // Use CBU event as trigger 
    EPwm3Regs.ETPS.bit.SOCAPRD = 1;         // Generate pulse on 1st event 


EPwm3Regs.CMPB = (EPwm3Regs.TBPRD)/2;// Intialize CMPB3


ISR_Init(); // ASM ISR init


// Lib Module connection to "nets" 
//----------------------------------------
// ADC feedback connections
ADC_Rslt = &AdcNetBus[1];// point to 1st element, i.e. AdcCh0 
// Connect the FBPS PWM generator block:  
FBPS_phase2   = &phase;// Point to the phase net
FBPS_dbLeft2  = &dbLeft;// Point to the left leg dead band adjust
FBPS_dbRight2 = &dbRight;// Point to the right leg dead band adjust


phase    = 0;
dbLeft   = 20;
dbRight  = 18;  


GpioDataRegs.GPASET.bit.GPIO16 = 1;// Disable PFC FET driver


#endif // (INCR_BUILD == 2) Open loop FBPS drive + ADC feedback


//=============================================================================
#if (INCR_BUILD == 3)// Closed current loop check with constant I command
//=============================================================================
#define prd 500 // Period count = 200 KHz @ 100 MHz


// "Raw" (R) ADC measurement name defines
#define IfbR AdcMirror.ADCRESULT0 //
#define Vfb_outRAdcMirror.ADCRESULT1 //
#define Vfb_inRAdcMirror.ADCRESULT2//


// Channel Selection for Cascaded Sequencer
ChSel[0] =  1;// A1 - FBPS Transformer Primary Current
ChSel[1] =  0;// A0 - FBPS O/P Voltage
ChSel[2] = 11;// B3 - FBPS I/P Voltage


FullBridgePS_CNF(2, prd); // ePWM2 and ePWM3, Period=prd


ADC_CascSeqCNF(ChSel, 2, 3, 0);// ACQPS=2, #Conv=3, Mode= Start/Stop (0)


// Configure the Start of Conversion for the ADC.
// At TBCNT3 = (TBPRD3 + TBPHS3)/2 SOCA is triggered
EPwm3Regs.ETSEL.bit.SOCAEN  =  1;
EPwm3Regs.ETSEL.bit.SOCASEL =  ET_CTRU_CMPB;// Use CBU event as trigger 
    EPwm3Regs.ETPS.bit.SOCAPRD = 1;        // Generate pulse on 1st event 


EPwm3Regs.CMPB = (EPwm3Regs.TBPRD)/2;// Intialize CMPB3


ISR_Init(); // ASM ISR init


// Lib Module connection to "nets" 
//----------------------------------------
// ADC feedback connections
ADC_Rslt = &AdcNetBus[1];// point to 1st element, i.e. AdcCh0  


// Connect the FBPS PWM generator block:  
FBPS_phase2   = &phase;// Point to the phase net
FBPS_dbLeft2  = &dbLeft;// Point to the left leg dead band adjust
FBPS_dbRight2 = &dbRight;// Point to the right leg dead band adjust




// CNTL_2P2Z(2) connections - Current loop
CNTL_2P2Z_Ref2 = &Iref;// Current loop command
CNTL_2P2Z_Out2 = &phase;// Output controls phase
CNTL_2P2Z_Fdbk2 = &AdcNetBus[1];// FB transformer primary current
CNTL_2P2Z_Coef2 = &Coef2P2Z_2[0];// point to first coeff.


Iref = 0;
dbLeft   = 20;
dbRight  = 18;  


// ---------------------------------- USER -----------------------------------------


// PID coefficients & Clamping - Current loop (Q26)
Dmax_I  = 0x03F00000; /* 0.984375 */
Pgain_I = 0x00000000; 
Igain_I = 0x00400000; /* 0.0625 */
Dgain_I = 0x00000000;


// Coefficient init --- Coeeficient values in Q26
Coef2P2Z_2[0] = Dgain_I;// B2
Coef2P2Z_2[1] = (Igain_I - Pgain_I - Dgain_I - Dgain_I);// B1
Coef2P2Z_2[2] = (Pgain_I + Igain_I + Dgain_I);// B0
Coef2P2Z_2[3] = 0x00000000;// A2
Coef2P2Z_2[4] = 0x04000000;// A1=1
Coef2P2Z_2[5] = Dmax_I;// Clamp Hi limit (Q26)
Coef2P2Z_2[6] = 0x00000000;// Clamp Lo


GpioDataRegs.GPASET.bit.GPIO16 = 1;// Disable PFC FET driver


#endif // (INCR_BUILD == 3) Closed current loop check with constant I command


//=============================================================================
#if (INCR_BUILD == 4) // Closed Current & Voltage loop check
//=============================================================================
#define prd 500 // Period count = 200 KHz @ 100 MHz


// "Raw" (R) ADC measurement name defines
#define IfbR AdcMirror.ADCRESULT0 //
#define Vfb_outRAdcMirror.ADCRESULT1 //
#define Vfb_inRAdcMirror.ADCRESULT2//


// Channel Selection for Cascaded Sequencer
ChSel[0] =  1;// A1 - FBPS Transformer Primary Current
ChSel[1] =  0;// A0 - FBPS O/P Voltage
ChSel[2] = 11;// B3 - FBPS I/P Voltage


FullBridgePS_CNF(2, prd);// ePWM2 and ePWM3, Period=prd


ADC_CascSeqCNF(ChSel, 2, 3, 0);// ACQPS=2, #Conv=3, Mode= Start/Stop (0)


// Configure the Start of Conversion for the ADC.
// At TBCNT3 = (TBPRD3 + TBPHS3)/2 SOCA is triggered
EPwm3Regs.ETSEL.bit.SOCAEN  =  1;
EPwm3Regs.ETSEL.bit.SOCASEL =  ET_CTRU_CMPB; // Use CBU event as trigger 
    EPwm3Regs.ETPS.bit.SOCAPRD = 1;         // Generate pulse on 1st event 


EPwm3Regs.CMPB = (EPwm3Regs.TBPRD)/2;// Intialize CMPB3


ISR_Init(); // ASM ISR init


// Lib Module connection to "nets" 
//----------------------------------------
// ADC feedback connections
ADC_Rslt = &AdcNetBus[1];// point to 1st element, i.e. AdcCh0  


// Connect the FBPS PWM generator block:  
FBPS_phase2   = &phase;// Point to the phase net
FBPS_dbLeft2  = &dbLeft;// Point to the left leg dead band adjust
FBPS_dbRight2 = &dbRight;// Point to the right leg dead band adjust


// CNTL_2P2Z(2) connections - Current loop
CNTL_2P2Z_Ref2 = &Iref;// Current Command Calculated by voltage loop
CNTL_2P2Z_Out2 = &phase;// Output controls phase
CNTL_2P2Z_Fdbk2 = &AdcNetBus[1];// FB transformer primary current
CNTL_2P2Z_Coef2 = &Coef2P2Z_2[0];// point to first coeff.


// PID coefficients & Clamping - Current loop  (Q26)
Dmax_I  = 0x03F00000; /* 0.984375 */
Pgain_I = 0x02000000; /* 0.5 */
Igain_I = 0x00000500; /* 0.000019 */
Dgain_I = 0x00000000;


// Coefficient init --- Coeeficient values in Q26
Coef2P2Z_2[0] = Dgain_I;// B2
Coef2P2Z_2[1] = (Igain_I - Pgain_I - Dgain_I - Dgain_I);// B1
Coef2P2Z_2[2] = (Pgain_I + Igain_I + Dgain_I);// B0
Coef2P2Z_2[3] = 0x00000000;// A2
Coef2P2Z_2[4] = 0x04000000;// A1 Corresponds to 1 in Q26
Coef2P2Z_2[5] = Dmax_I;// Clamp Hi limit (Q26)
Coef2P2Z_2[6] = 0x00000000;// Clamp Lo


// CNTL_2P2Z(1) connections - Voltage loop
CNTL_2P2Z_Ref1 = &fbpsSetSlewed;// Slewed Voltage command
CNTL_2P2Z_Out1 = &Iref;// Reference command to the current loop
CNTL_2P2Z_Fdbk1 = &AdcNetBus[2];// FB O/P Voltage feedback
CNTL_2P2Z_Coef1 = &Coef2P2Z_1[0];// point to first coeff.


// PID coefficients & Clamping - Voltage loop (Q26)
Dmax  = 0x03F00000; /* 0.984375 */
Pgain = 0x00020000; /* 0.00195 */
Igain = 0x00200000;/* 0.03125 */
Dgain = 0x00000000;


// Coefficient init --- Coeeficient values in Q26
Coef2P2Z_1[0] = Dgain;// B2
Coef2P2Z_1[1] = (Igain - Pgain - Dgain - Dgain);// B1
Coef2P2Z_1[2] = (Pgain + Igain + Dgain);// B0
Coef2P2Z_1[3] = 0x00000000;// A2
Coef2P2Z_1[4] = 0x04000000;// A1=1
Coef2P2Z_1[5] = Dmax;// Clamp Hi limit (Q26)
Coef2P2Z_1[6] = 0x00000000;// Clamp Lo


fbpsSlewRate = 1;


Vref = 0;
dbLeft   = 20;
dbRight  = 18;   


GpioDataRegs.GPASET.bit.GPIO16 = 1;// Disable PFC FET driver


#endif // (INCR_BUILD == 4) Closed Current & Voltage loop check




//==============================================================================
// Items common to all builds
//==============================================================================


//Configuring GPIO8 (ePWM5A) for SR drive and to generate secondary 12V bias
EPwm4Regs.TBCTL.bit.SYNCOSEL = TB_SYNC_IN;// Pass the Sync signal through to ePWM5


EPwm5Regs.TBCTL.bit.PRDLD = TB_IMMEDIATE;// Set Immediate load
EPwm5Regs.TBPRD = 500;// 200 kHz
EPwm5Regs.CMPA.half.CMPA = 250;// Fix duty at 50%
EPwm5Regs.TBPHS.half.TBPHS = 0;
EPwm5Regs.TBCTR = 0;


EPwm5Regs.TBCTL.bit.CTRMODE = TB_COUNT_UP;
EPwm5Regs.TBCTL.bit.PHSEN = TB_ENABLE;// Enabled for SR
EPwm5Regs.TBCTL.bit.HSPCLKDIV = TB_DIV1;
EPwm5Regs.TBCTL.bit.CLKDIV = TB_DIV1;


EPwm5Regs.AQCTLA.bit.ZRO = AQ_CLEAR;
EPwm5Regs.AQCTLA.bit.CAU = AQ_SET; 




EPwm2Regs.TZCLR.bit.OST = 1;// Clear any spurious trips
EPwm3Regs.TZCLR.bit.OST = 1;// Clear any spurious trips 


//All enabled ePWM module clocks are started with the first rising edge of 
//TBCLK aligned   
EALLOW;
SysCtrlRegs.PCLKCR0.bit.TBCLKSYNC = 1; 
EDIS;




//=================================================================================
// INTERRUPT & ISR INITIALISATION (best to run this section after other initialisation)
//=================================================================================
EALLOW;
PieVectTable.EPWM3_INT = &ISR_Run;// Map Interrupt
EDIS;
PieCtrlRegs.PIEIER3.bit.INTx3 = 1;// PIE level enable, Grp3 / Int3
EPwm3Regs.ETSEL.bit.INTSEL = ET_CTRU_CMPB;// INT on CMPB3 event
EPwm3Regs.ETSEL.bit.INTEN = 1;// Enable INT
EPwm3Regs.ETPS.bit.INTPRD = ET_1ST;// Generate INT every event (200 KHz) 


// Enable Peripheral, global Ints and higher priority real-time debug events:
IER |= M_INT3; 
EINT;   // Enable Global interrupt INTM
ERTM;   // Enable Global realtime interrupt DBGM 


// Initialize DATALOG module      
    dlog.iptr1 = &AdcNetBus[1]; //FB Current
    dlog.iptr2 = &AdcNetBus[2]; //FB O/P Voltage
    dlog.iptr3 = &phase;
    dlog.iptr4 = &Iref;
    dlog.trig_value = 0x10;
    dlog.size = 0x400;
    dlog.prescalar = 1;
    dlog.init(&dlog);


//=================================================================================
// BACKGROUND (BG) LOOP
//=================================================================================


//--------------------------------- FRAMEWORK -------------------------------------
for(;;)
{
// State machine entry & exit point
//===========================================================
(*Alpha_State_Ptr)();// jump to an Alpha state (A0,B0,...)
//===========================================================
}
} //END MAIN CODE 




//=================================================================================
// STATE-MACHINE SEQUENCING AND SYNCRONIZATION
//=================================================================================


//--------------------------------- FRAMEWORK -------------------------------------
void A0(void)
{
// loop rate synchronizer for A-tasks
if(CpuTimer0Regs.TCR.bit.TIF == 1)
{
CpuTimer0Regs.TCR.bit.TIF = 1;// clear flag


//-----------------------------------------------------------
(*A_Task_Ptr)();// jump to an A Task (A1,A2,A3,...)
//-----------------------------------------------------------


VTimer0[0]++; // virtual timer 0, instance 0 (spare)
}


Alpha_State_Ptr = &B0;// Comment out to allow only A tasks
}


void B0(void)
{
// loop rate synchronizer for B-tasks
if(CpuTimer1Regs.TCR.bit.TIF == 1)
{
CpuTimer1Regs.TCR.bit.TIF = 1;// clear flag


//-----------------------------------------------------------
(*B_Task_Ptr)();// jump to a B Task (B1,B2,B3,...)
//-----------------------------------------------------------
VTimer1[0]++; // virtual timer 1, instance 0 
VTimer1[1]++; // virtual timer 1, instance 1 (used by DSP280xx_SciCommsGui.c)
}


Alpha_State_Ptr = &C0;// Allow C state tasks
}


void C0(void)
{
// loop rate synchronizer for C-tasks
if(CpuTimer2Regs.TCR.bit.TIF == 1)
{
CpuTimer2Regs.TCR.bit.TIF = 1;// clear flag


//-----------------------------------------------------------
(*C_Task_Ptr)();// jump to a C Task (C1,C2,C3,...)
//-----------------------------------------------------------
VTimer2[0]++; //virtual timer 2, instance 0 (spare)
}


Alpha_State_Ptr = &A0;// Back to State A0
}




//=================================================================================
// A - TASKS
//=================================================================================
//--------------------------------------------------------
void A1(void) // Control Coefficient re-calculations
//=====================================================================
{
if (calc_flag == 1)// Debug - Current loop coefficient update
{
Coef2P2Z_2[0] = Dgain_I;// B2
Coef2P2Z_2[1] = (Igain_I - Pgain_I - Dgain_I - Dgain_I);// B1
Coef2P2Z_2[2] = (Pgain_I + Igain_I + Dgain_I);// B0
Coef2P2Z_2[3] = 0x00000000;// A2
Coef2P2Z_2[4] = 0x04000000;// A1 Corresponds to 1 in Q26
Coef2P2Z_2[5] = Dmax_I;// Clamp Hi limit (Q26)
Coef2P2Z_2[6] = 0x00000000;

calc_flag = 0;
// Debug - Voltage loop coefficient update
Coef2P2Z_1[0] = Dgain;// B2
Coef2P2Z_1[1] = (Igain - Pgain - Dgain - Dgain);// B1
Coef2P2Z_1[2] = (Pgain + Igain + Dgain);// B0
Coef2P2Z_1[3] = 0x00000000;// A2
Coef2P2Z_1[4] = 0x04000000;// A1 Corresponds to 1 in Q26
Coef2P2Z_1[5] = Dmax;// Clamp Hi limit (Q26)
Coef2P2Z_1[6] = 0x00000000;
}
//-------------------
A_Task_Ptr = &A2;
//-------------------
}


//=====================================================================
void A2(void)  // Slew Rate,  SCI GUI
//-----------------------------------------------------------------
{
// This is an example code for implementing the slew rate control in
// a slower state machine instead of implementing it in the ISR. 
// fbpsSlewRate has to be a positive value
fbps_slew_temp = Vref - fbpsSetSlewed;


if (fbps_slew_temp >= fbpsSlewRate) // Positive Command
{
fbpsSetSlewed = fbpsSetSlewed + fbpsSlewRate;
}
else
{
if ((-1)*(fbps_slew_temp) >= fbpsSlewRate) // Negative Command
{
fbpsSetSlewed = fbpsSetSlewed - fbpsSlewRate;
}
}


// SerialHostComms();
//-------------------
A_Task_Ptr = &A1;// To make task A3 active, change &A1 to &A3
//-------------------
}


//=======================================================================
void A3(void) // SPARE (not active)
//=======================================================================
{


//-----------------
A_Task_Ptr = &A1;// To make task A4 active, change &A1 to &A4
//-----------------
}


//=====================================================================
void A4(void) //  SPARE (not active)
//=====================================================================
{


//-----------------
A_Task_Ptr = &A1;// After Task A4, start over with task A1
//-----------------
}




//%%%%%%%%%%%%%%%    B-Tasks:   %%%%%%%%%%%%%%%%%%%%%%%%%
//=====================================================================
void B1(void) // Voltage and Current Dashboard measurements (Only for Builds 2 and above)
//=====================================================================
{
#if (INCR_BUILD > 1) // ADC Measurements


// Voltage measurement calculated by:
// Gui_Vfbin = VfbinAvg * K_Vfbin, where VfbinAvg = sum of 8 Vfb_inR samples
// Gui_Vfbout = VfboutAvg * K_Vfbout, where VfboutAvg = sum of 8 Vfb_outR samples
 
HistPtr++;
if (HistPtr >= 8)HistPtr = 0;


// BoxCar Averages - Input Raw samples into History arrays
//----------------------------------------------------------------
Hist_Vfbin[HistPtr] = Vfb_inR; // Raw ADC result (Q12)


temp_Scratch=0;
for(i=0; i Gui_Vfbin = ( (long) temp_Scratch * (long) K_Vfbin ) >> 15; // (Q15 * Q15)>>15 = Q15


// BoxCar Averages - Input Raw samples into History arrays
//----------------------------------------------------------------   
Hist_Vfbout[HistPtr] = Vfb_outR; // Raw ADC result (Q12)


temp_Scratch=0;
for(i=0; i Gui_Vfbout = ( (long) temp_Scratch * (long) K_Vfbout ) >> 15; // (Q15 * Q15)>>15 = Q15


// Voltage Meas
//----------------------------------------------------------------
// view following variables in Watch Window as:
// Gui_Vfbin = Q8 
// Gui_Vfbout = Q10


// Current measurement calculated by:
// Gui_Ifb = IfbAvg * K_Ifb, where IfbAvg = sum of 8 IfbR samples
//BoxCar Averages - Input Raw samples into History arrays 


Hist_Ifb[HistPtr] = IfbR; // Raw ADC result (Q12)


temp_Scratch=0;
for(i=0; i Gui_Ifb = ( (long) temp_Scratch * (long) K_Ifb ) >> 15; // (Q15 * Q15)>>15 = Q15


// Current Meas
//----------------------------------------------------------------
// view following variables in Watch Window as:
// Gui_Ifb = Q12


// Voltage setting calculated by:
// Vref = Gui_VfbSet * iK_Vfbout, where iK_Vfbout = 1/K_Vfbout (i.e. inverse K_Vfbout)
// view and set following variable in Watch Window as:
// Gui_VfbSet = Q10 (Used as Q15 below) 
if (Gui_VfbSet > 250) // If command is greater than a certain minimum
Vref = ( (long) Gui_VfbSet * (long) iK_Vfbout ) >> 14; // (Q15 * Q14) >> 14 = Q15
else // If FB is disabled, start from a small value
Vref = 250; // Re-initialise to a small command


#if (INCR_BUILD == 3) 
// Current setting calculated by:
// Iref = Gui_IfbSet * iK_Ifb, where iK_Ifb = 1/K_Ifb (i.e. inverse K_Ifb)
// view and set following variable in Watch Window as:
// Gui_IfbSet = Q12 (Used as Q15 below)
Iref = ( (long) Gui_IfbSet * (long) iK_Ifb ) >> 14; // (Q15 * Q14) >> 14 = Q15
#endif 


#endif //INCR_BUILD > 1 
B_Task_Ptr = &B2;
//-----------------
}


//=====================================================================
void B2(void) // SPARE
//=====================================================================
{
//-----------------
B_Task_Ptr = &B1;
//-----------------
}


//=====================================================================
void B3(void) // SPARE (not active)
//=====================================================================
{
//-----------------
B_Task_Ptr = &B1;
//-----------------
}


//=====================================================================
void B4(void) //  SPARE (not active)
//=====================================================================
{


//-----------------
B_Task_Ptr = &B1;
//-----------------
}






//%%%%%%%%%%%%%%%    C-Tasks:   %%%%%%%%%%%%%%%%%%%%%%%%%
//=====================================================================
void C1(void) // FB Shut Down when command is v.small (Only Build 4)
//=====================================================================
{
// When the I/P FB command is v.small [<250 (0.18 V)]  and the output has reached a low value
// (Gui_Vfbout = 250 (i.e. around 0.18 V), turn-off FB by making Phase command 0 
#if (INCR_BUILD == 4) 
if (Gui_Vfbout < 250 && Gui_VfbSet < 250)
{
CNTL_2P2Z_Out2 = &Iref;// This will prevent the current loop O/P from driving the FB PWM driver
phase = 0; // If Output has gone below this small level, turn-off FB
}
else CNTL_2P2Z_Out2 = &phase;// Connect Current loop O/P to FB PWM driver
#endif
//-----------------
C_Task_Ptr = &C2;
//-----------------
}


//=====================================================================
void C2(void) //  SPARE
//=====================================================================
{
//-----------------
C_Task_Ptr = &C1;
//-----------------
}


//=====================================================================
void C3(void) //  SPARE (not active)
//=====================================================================
{

//-----------------
C_Task_Ptr = &C1;
//-----------------
}


//=====================================================================
void C4(void) //  SPARE (not active)
//=====================================================================
{
//-----------------
C_Task_Ptr = &C1;
//----------------- }