Part Number: TMS320F28377D
Hi TI,
Request your assistance with an issue we encountered when implementing hysteresis current control using the CMPSS module on the TMS320F28377D.
We have configured the CMPSS module to implement hysteresis current control. The positive input of the CMPSS comparator is connected to the amplified inductor current sensing signal, while the negative input uses the internal DAC to set the current thresholds.
The upper and lower current limits are fixed at +5 A and -5 A, respectively. However, during experimental testing, the actual inductor current reaches approximately +28.4 A and -28.4 A, which significantly exceeds the configured hysteresis band.
Our experimental parameters are as follows:
- DC bus voltage: 400 V
- Inductance: 24 µH
- Upper current threshold: +5 A
- Lower current threshold: -5 A
- Actual measured inductor current: approximately ±28.4 A
We have investigated the propagation delays introduced by the downstream ePWM module and gate driver circuitry. Based on our analysis, these delays are on the nanosecond scale and appear insufficient to explain such a large current overshoot.
To further investigate this issue, we routed the upper current threshold detection event to GPIO24, which goes high when the upper threshold event is detected.
We monitored the following signals using an oscilloscope:
- CH1: CMPSS positive input voltage (amplified inductor current sensing signal)
- CH2: Actual inductor current waveform
- CH4: GPIO24 output indicating the upper current threshold detection event
From the measured waveforms, the CMPSS positive input voltage appears to follow the actual inductor current closely, without any obvious phase shift. Therefore, we believe that the propagation delay introduced by the current sensor and operational amplifier is unlikely to be the main cause of the excessive current overshoot.
However, GPIO24 appears to indicate the upper current threshold event significantly later than expected. This suggests that either the CMPSS comparator is not triggering at the intended threshold or there is an unexpected delay in the CMPSS output signal path.
With a 400 V DC bus voltage and a 24 µH inductor, the theoretical current slew rate is approximately 16.67 A/µs, assuming the full DC bus voltage is applied across the inductor.
The current overshoot from +5 A to +28.4 A corresponds to an equivalent delay of approximately 1.4 µs under this assumption.
However, according to the CMPSS specifications and other application examples, the comparator propagation delay should be on the nanosecond scale, which is significantly shorter than the delay estimated from our experimental results.
I am not sure why the CMPSS threshold detection event appears to occur so late.
Could you please advise on the following questions?
- What could cause the CMPSS comparator to generate an output event significantly later than the expected current threshold crossing?
- Could incorrect internal DAC threshold configuration, comparator polarity, or CMPSS offset characteristics cause the comparator to trigger at a different current level than intended?
- Are there any CMPSS configurations, such as asynchronous/synchronous output selection, digital filtering, or output routing through the X-BAR, that could introduce an unexpected delay on the microsecond scale?
- How can we determine whether this issue is caused by an incorrect CMPSS triggering threshold or an actual propagation delay within the CMPSS signal path?
- What would be the recommended CMPSS configuration and debugging procedure for high-speed hysteresis current control applications?
I have reviewed the CMPSS configurations and the relevant sections of the technical reference manual, but I have not been able to identify the cause of this issue.
We would appreciate your guidance on how to ensure that the CMPSS comparator triggers accurately when the inductor current reaches the configured thresholds of ±5 A.
/*
* A-phase CMPSS6 boundary monitor, raw asynchronous outputs:
* GPIO24 rises at the upper CURRENT threshold (DACL).
* GPIO26 rises at the lower CURRENT threshold (DACH).
* The mapping assumes voltage falls as inductor current rises.
* Verify CMPIN6P (ADCINC2) has that polarity and the calibrated slope.
* A-phase ADC current feedback is sampled separately on ADCINC3.
*/
/*
* F28377D CPU1: Fixed absolute inductor-current hysteresis (-5A ... +5A).
* Based on the uploaded three-phase CMPSS/ePWM delay-compensated HCC program.
*
* FIXED PHYSICAL LIMITS, ALL THREE PHASES:
* Iupper = +5.0 A, Ilower = -5.0 A (center is ALWAYS zero).
* No voltage-QPR or manual Iref can move these limits.
* With delay compensation enabled:
* comparator_upper = +5 - (Vdc - Vo) * TdRise / L
* comparator_lower = -5 + Vo * TdFall / L
* These are advance-trip thresholds, NOT changed physical targets.
* L defaults to 24 uH. Delay times and A-phase voltage advances default to zero.
* A-phase fixed advances in mV are configured below and latched at startup.
*
* Startup: measured filtered DC bus >= 400 V, manual HccRunEnable = 1,
* 250 control interrupts startup delay (~10 ms at 25 kHz).
* Running UV: 360 V; bus OV: 450 V (retain original trial limits).
* Secondary sampled-current trip: +/-30 A (25 kHz, not fast protection).
* ADC calibration, CMPSS offset codes, XBAR, deadband and hardware trips
* retain their original mapping. The 400 Hz voltage-reference generator and
* QPR state initialization remain for compatibility/observation, but there is
* NO voltage regulation in this fixed absolute-current-bound mode.
*
* The source depends on the original F28377D TI project plus
* F28x_Project.h, QPR_Control.h/.c and device support files.
* The fixed boundaries are theoretical targets; actual peaks depend on
* measured delays, ADC/CMPSS calibration, switching path, and L.
*/
#ifndef CURRENT_LOOP_ENABLE
#define CURRENT_LOOP_ENABLE 1U
#endif
#if CURRENT_LOOP_ENABLE != 1U
#error This_minimal_file_requires_CURRENT_LOOP_ENABLE_1
#endif
/* 0=temporarily disable sampled-current OC trips; 1=restore them.
* Does not bypass ADC-invalid, OV, UV, or independent hardware protection.
* A project predefined value takes precedence over this default. */
#ifndef HCC_SW_OVERCURRENT_ENABLE
#define HCC_SW_OVERCURRENT_ENABLE 1U
#endif
#if (HCC_SW_OVERCURRENT_ENABLE != 0U) && (HCC_SW_OVERCURRENT_ENABLE != 1U)
#error HCC_SW_OVERCURRENT_ENABLE_must_be_0_or_1
#endif
#include "F28x_Project.h"
#include "math.h"
#include "QPR_Control.h"
/*================ Three-phase current conversion configuration (enter actual hardware parameters first) ================*/
/* TLE4978-R040W5-O-S0010: 5 V supply, 3.0 V ADC reference, signed sensitivity -48.75 mV/A.
* If the hardware parameters change, update the following two settings; protection checks still reject zero values.
* IL_ADC_VREF_MV: measured VREFHI - VREFLO in mV, not VDDA or the sensor's 5 V supply.
* IL_SENSOR_SENS_UV_PER_A: sensor output sensitivity in uV/A, before the op-amp gain of 0.5.
* This version retains the installation polarity where voltage decreases as positive current increases; the value is (-48750L).
* Current HCC event actions only support a negative slope; changing sensor orientation also requires changing the HCC switching logic.
* The defaults below are editable; identically named project predefines take precedence.
*/
#ifndef IL_ADC_VREF_MV
#define IL_ADC_VREF_MV 3000L
#endif
#ifndef IL_SENSOR_SENS_UV_PER_A
#define IL_SENSOR_SENS_UV_PER_A (-48750L)
#endif
/* Original channel mapping: ILa uses ADCC; ILb and ILc use ADCA.
* If ADCA/ADCC references or the three sensor sensitivities differ, update their respective settings.
*/
#ifndef IL_ADCA_VREF_MV
#define IL_ADCA_VREF_MV IL_ADC_VREF_MV
#endif
#ifndef IL_ADCC_VREF_MV
#define IL_ADCC_VREF_MV IL_ADC_VREF_MV
#endif
#if (IL_ADCA_VREF_MV != 3000L) || (IL_ADCC_VREF_MV != 3000L)
#error This_ADC_3V_test_requires_ADCA_and_ADCC_reference_3000mV_check_project_predefines
#endif
#ifndef ILA_SENSOR_SENS_UV_PER_A
#define ILA_SENSOR_SENS_UV_PER_A IL_SENSOR_SENS_UV_PER_A
#endif
#ifndef ILB_SENSOR_SENS_UV_PER_A
#define ILB_SENSOR_SENS_UV_PER_A IL_SENSOR_SENS_UV_PER_A
#endif
#ifndef ILC_SENSOR_SENS_UV_PER_A
#define ILC_SENSOR_SENS_UV_PER_A IL_SENSOR_SENS_UV_PER_A
#endif
#if (IL_ADCA_VREF_MV <= 0L) || (IL_ADCC_VREF_MV <= 0L)
#error Fill in measured IL_ADC_VREF_MV or both per-module VREF macros before building.
#endif
#if (ILA_SENSOR_SENS_UV_PER_A == 0L) || (ILB_SENSOR_SENS_UV_PER_A == 0L) || (ILC_SENSOR_SENS_UV_PER_A == 0L)
#error Fill in sensor sensitivity in uV_per_A before building. No sensor sensitivity was supplied.
#endif
/* The following assumes one signal per phase, with the other input disconnected or held at 0 V, and VREFLO = AGND.
* Total gain of the two op-amp stages: (-100k/200k)*(-10k/10k) = +0.5.
* Sensor output at zero current is 2.5 V; hence the theoretical ADC-node zero level is 1.25 V.
* The actual per-phase offsets have been adjusted using the user's zero-current readings (ILa/b/c_offset), not the theoretical zero.
* If the other input still connects to a sensor whose zero-current output is 2.5 V, these equations do not apply.
*/
#define IL_ADC_COUNTS_PER_RANGE 4096.0f
#define IL_ANALOG_GAIN 0.5f
#define IL_SENSOR_ZERO_V 2.5f
#define IL_ADC_ZERO_V (IL_ANALOG_GAIN * IL_SENSOR_ZERO_V)
#define IL_ADCA_VREF_V ((float32)IL_ADCA_VREF_MV / 1000.0f)
#define IL_ADCC_VREF_V ((float32)IL_ADCC_VREF_MV / 1000.0f)
#define ILA_SENSOR_SENS_V_PER_A ((float32)ILA_SENSOR_SENS_UV_PER_A * 0.000001f)
#define ILB_SENSOR_SENS_V_PER_A ((float32)ILB_SENSOR_SENS_UV_PER_A * 0.000001f)
#define ILC_SENSOR_SENS_V_PER_A ((float32)ILC_SENSOR_SENS_UV_PER_A * 0.000001f)
/* Legacy nominal values; active CMPSS slopes use the measured ADC gains below. */
#define ILA_CONDITIONED_SLOPE_V_PER_A (IL_ANALOG_GAIN * ILA_SENSOR_SENS_V_PER_A)
#define ILB_CONDITIONED_SLOPE_V_PER_A (IL_ANALOG_GAIN * ILB_SENSOR_SENS_V_PER_A)
#define ILC_CONDITIONED_SLOPE_V_PER_A (IL_ANALOG_GAIN * ILC_SENSOR_SENS_V_PER_A)
#define ILA_THEORY_GAIN (IL_ADCC_VREF_V / (IL_ADC_COUNTS_PER_RANGE * ILA_CONDITIONED_SLOPE_V_PER_A))
#define ILB_THEORY_GAIN (IL_ADCA_VREF_V / (IL_ADC_COUNTS_PER_RANGE * ILB_CONDITIONED_SLOPE_V_PER_A))
#define ILC_THEORY_GAIN (IL_ADCA_VREF_V / (IL_ADC_COUNTS_PER_RANGE * ILC_CONDITIONED_SLOPE_V_PER_A))
/*=========================== Function declarations ===========================*/
void ConfigureADC(void);
void SetupADCEpwm(void);
void InitEPWMd(void);
void ConfigureEPWM1(void);
void ConfigureEPWM2(void);
void ConfigureEPWM3(void);
void ConfigureEPWM4(void);
void ConfigureEPWM5(void);
void ConfigureEPWM6(void);
void ConfigureEPWM12(void);
void ForceAllPWMOff(void);
void EnableAllPWM(void);
void DisableAllPWM(void);
void Gen_3PH_Sine_400Hz(void);
static void InitControllers(void);
static void InitSineTable(void);
static void UpdatePowerStageOutput(void);
static void ResetVoltageLoopStates(void);
static void ConfigureEPWMCommon(volatile struct EPWM_REGS *pwm);
static void ConfigureBuckPWMRunMode(volatile struct EPWM_REGS *pwm);
static void ConfigureBoostPWMFixedMode(volatile struct EPWM_REGS *pwm);
static void ConfigureCMPSSCurrentWindow(void);
static void ConfigureHCCEPWMXBAR(void);
static void InitCMPSS6BoundaryMonitorGPIO(void);
static void ConfigureEPWMHardwareHCCInput(volatile struct EPWM_REGS *, Uint16, Uint16);
static void UpdateVdcProtectionFilter(void);
static void UpdateVbusOvervoltageState(void);
static void HccService(void);
static void HccTrip(Uint16 code);
static void HccTripDetail(Uint16 code, Uint16 phase, Uint16 mask);
static Uint16 HccPrepareStart(void);
static Uint16 HccLatchDelayConfig(void);
static Uint16 HccUpdateDelayTerms(void);
static void HccSeed(volatile struct EPWM_REGS *, volatile struct CMPSS_REGS *);
interrupt void adca1_isr(void);
/*=========================== Clock, sampling, and PWM parameters ===========================*/
#define CPU_CLK 200000000.0f // CPU SYSCLK: 200 MHz
#define PWM_CLK 100000.0f // EPWM1..6: 100 kHz
#define ADC_SAMPLE_CLK 100000.0f // EPWM12 SOCA: 100 kHz
#define CONTROL_ISR_CLK 25000.0f // EPWM12 SOCB / ADCA1,40us period
#define TSAM (1.0f / CONTROL_ISR_CLK)
// F28377D: EPWMCLKDIV=/2, HSPCLKDIV=/1, CLKDIV=/1 => TBCLK=100 MHz.
// Center-aligned counting: PWM frequency = TBCLK/(2*TBPRD).
#define EPWM_TBCLK_HZ (CPU_CLK / 2.0f)
#define SP ((Uint16)(EPWM_TBCLK_HZ / (2.0f * PWM_CLK) + 0.5f))
#define ADC_TRIG_EPWM2_SOCA 7U // ePWM2 SOCA: early three-phase voltage sampling
#define ADC_TRIG_EPWM12_SOCA 27U // F2837xD ADC TRIGSEL: EPWM12 SOCA
#define ADC_TRIG_EPWM12_SOCB 28U // F2837xD ADC TRIGSEL: EPWM12 SOCB
#ifndef ET_CTRU_CMPB
#define ET_CTRU_CMPB 6U // CMPB match event while counting up
#endif
#define DEAD_BAND 100e-9f // Target dead time: 100 ns
// Full-cycle dead-band clock = TBCLK; 10 counts x 10 ns = 100 ns (the previous formula gave only 5 counts).
#define DIFFER ((Uint16)(EPWM_TBCLK_HZ * DEAD_BAND + 0.5f))
#define SINE_POINTS 125U // lookup-table length; advance2 per25kHz ISR
#define SINE_INDEX_STEP 2U
#define PI_F 3.1415926535f // Floating-point value of pi
#define SQRT2_F 1.41421356237f // Floating-point constant sqrt(2)
#define PHASE_120 2.0943951024f // 120-degree phase shift in radians
static float32 phase_sine_table[3][SINE_POINTS];
/*
* Target RMS value of each phase's AC component is 115 V; peak amplitude = 115 * sqrt(2).
*/
#define UREF_AMP (115.0f * SQRT2_F)
/* Nominal DC ramp remains A+25V. Compensation multiplies only the sine term.
* Actual reference minimum becomes A+25V-A*VAC_AC_COMP_x after compensation. */
#define UREF_BASE_V 25.0f
/* AC reference compensation, not ADC calibration and not QPR gain.
* Change while stopped, then rebuild/restart. Project predefines take precedence.
* A: estimated from CH1 Vmax342V/Vmin34V => AC~108.894Vrms;115/108.894~1.056.
* C: same trial starting value because screenshot amplitudes look similar;
* no numeric CH4 amplitude was supplied, so C is not independently calibrated.
* B: no measurement in this turn, so keep its original AC reference.
* No compensation coefficient/reference-peak precheck; measured voltage protection remains active. */
#ifndef VAC_AC_COMP_A
#define VAC_AC_COMP_A 1.260f
#endif
#ifndef VAC_AC_COMP_B
#define VAC_AC_COMP_B 1.260f
#endif
#ifndef VAC_AC_COMP_C
#define VAC_AC_COMP_C 1.260f
#endif
//#ifndef VAC_AC_COMP_A
//#define VAC_AC_COMP_A 1.000f
//#endif
//#ifndef VAC_AC_COMP_B
//#define VAC_AC_COMP_B 1.000f
//#endif
//#ifndef VAC_AC_COMP_C
//#define VAC_AC_COMP_C 1.000f
//#endif
/*
* 400 V DC-bus test: start threshold 400 V, running UV 360 V, OV 450 V; new divider nominal full scale 480 V.
* Reaching the bus threshold does not automatically start PWM: manual HccRunEnable = 1U is still required.
*/
#define VBUS_START_TH 400.0f
#define VBUS_OFF_TH 360.0f
/* Trial value only: set to actual allowed DC bus maximum before bench use. */
#define VBUS_OVER_TH 450.0f
/* Instantaneous phase-to-reference output limits, including the DC offset.
* Trial values only: not RMS limits. Adjust separately for actual hardware. */
#define VA_OVER_TH 370.0f
#define VB_OVER_TH 370.0f
#define VC_OVER_TH 370.0f
// Soft-start range
/*
* Step-by-step testing: change only BUCK_STAGE, then rebuild/download; no automatic stage switching.
* Compensated sine reference = A*VAC_AC_COMP_x*sin(theta) + A + UREF_BASE_V.
* Stage 5 in this version: default A/C references about 15.89 to 359.38 V; B about 25 to 350.27 V.
* At a 400 V bus, the default full-scale A/C peak-reference duty ratio is about 89.84%; retain the reserved CMP limit.
* This is not an algorithm error; first verify the actual bus voltage and high-duty-cycle capability of the driver.
*/
#define BUCK_STAGE 5U
#if BUCK_STAGE == 0U
#define BUCK_STAGE_PEAK_V 25.0f
#elif BUCK_STAGE == 1U
#define BUCK_STAGE_PEAK_V 28.0f
#elif BUCK_STAGE == 2U
#define BUCK_STAGE_PEAK_V 31.0f
#elif BUCK_STAGE == 3U
#define BUCK_STAGE_PEAK_V 34.0f
#elif BUCK_STAGE == 4U
#define BUCK_STAGE_PEAK_V 36.0f
#elif BUCK_STAGE == 5U
#define BUCK_STAGE_PEAK_V (UREF_BASE_V + 2.0f * UREF_AMP)
#else
#error "BUCK_STAGE must be 0..5"
#endif
#define UREF_START_VAL 5.0f
#define UREF_TARGET ((BUCK_STAGE_PEAK_V - UREF_BASE_V) * 0.5f)
#define UREF_STEP 0.00126f //31.5V/s, preserving the old ramp time
// Static soft-start state variable
float32 uref_current = UREF_START_VAL; // Initialize directly to the starting amplitude
/* The following ratios are retained only to estimate bus headroom during voltage-reference soft start.
* The single-voltage-loop mode enforces CMP limiting/slew-rate limiting; HCC uses these ratios only for soft-start headroom estimates.
*/
#define BUCK_DUTY_MIN 0.02f
#define BUCK_MIN_CMP ((Uint16)((float32)SP * BUCK_DUTY_MIN + 0.5f))
#define BUCK_CMP_MAX_STEP 20U
#define DC_TRIM_MAX_COUNT 75.0f
#define BUCK_DUTY_MAX 0.98f
#define BUCK_MAX_CMP ((Uint16)((float32)SP * BUCK_DUTY_MAX + 0.5f))
#define BUCK_FF_RESERVE_CMP 10U
// For slow DC-offset integration, first low-pass-filter the DC component of voltage error so the 400 Hz sine does not enter the integrator.
#define DC_ERR_FC_HZ 10.0f
#define DC_ERR_LPF_ALPHA ((2.0f * PI_F * DC_ERR_FC_HZ * TSAM) / \
(1.0f + 2.0f * PI_F * DC_ERR_FC_HZ * TSAM))
/*
* PWM start delay counter: wait for a number of ADC interrupts after power-up before clearing the TZ latch.
*At a 25 kHz control ISR rate, 250 counts correspond to about 10 ms.
*/
#define PWM_ENABLE_DELAY_CNT 250U //10ms at25kHz
/*=========================== New-hardware ADC scaling coefficients ===========================*/
#define VDC_GAIN 0.11622274186f // New voltage divider 160:1; previous calibration multiplied by 160/138; fine-tune after measurements
/* QPR limits: by current reference in HCC mode; by remaining PWM count headroom in single-voltage-loop mode. */
/*
* Some F2837xD standard headers do not define the forced-output-level macros AQ_FORCE_LOW/AQ_FORCE_HIGH.
* AQCSFRC register CSFA/CSFB bit definitions:
* 0 = disable continuous software force
* 1 = force output low
* 2 = force output high
*/
#ifndef AQ_FORCE_LOW
#define AQ_FORCE_LOW 1U
#endif
#ifndef AQ_FORCE_HIGH
#define AQ_FORCE_HIGH 2U
#endif
/*=========================== QPR instances (retained for compatibility; their outputs are unused by the fixed window) ===========================*/
QPR_Control_T Va_QPR; // A-phase quasi-proportional-resonant voltage controller
QPR_Control_T Vb_QPR; // B-phase quasi-proportional-resonant voltage controller
QPR_Control_T Vc_QPR; // C-phase quasi-proportional-resonant voltage controller
/* Tune Kp/Kr independently for each phase; rebuild/download after source changes; InitControllers loads them.
* Changing only Watch variables at runtime does not automatically recalculate the QPR internal coefficients.
* fc_inv, acFreq_inv and TSAM remain shared by the three phases. */
volatile float32 Kp_QPR_A=0.10f, Kr_QPR_A=0.20f; // A-phase, A/V
volatile float32 Kp_QPR_B=0.10f, Kr_QPR_B=0.20f; // B-phase, A/V
volatile float32 Kp_QPR_C=0.10f, Kr_QPR_C=0.20f; // C-phase, A/V
float fc_inv = 5.0f; // QPR cutoff frequency
float acFreq_inv = 400.0f; // AC output fundamental frequency: 400 Hz
// Parameters visible in CCS Watch: validate incrementally at low voltage with current limiting.
// The gains below have not been tuned to the actual LC/load frequency response and cannot guarantee stability on arbitrary power hardware.
// Adjust the DC center and 400 Hz AC modulation amplitude separately; increasing FF_gain globally also amplifies the offset.
float32 FF_DC_GAIN = 1.00f; // DC-center feedforward, initially 1.00
float32 FF_AC_GAIN = 1.00f; // Match the measured reference amplitude in this trial; first measure tracking error without additional AC feedforward gain
float32 Ki_DC_trim=0.5f; // A/(V*s)
// Only the voltage DC control target is corrected here, not voltage ADC_GAIN/offset or Va1/Vb1/Vc1 reference waveforms.
// If the measured DC center is too high, a negative CORR causes the DC integral loop to reduce the output center slowly.
// Retain the uploaded version's 0 V target correction; the full-scale reference and slow-integrator target centers are both about 187.63456 V.
// The historical debugging note about a 15 V center does not apply to this version; do not add negative offset based on that value.
float32 DC_CTRL_SHIFT_A = 0.0f;
float32 DC_CTRL_SHIFT_B = 0.0f;
float32 DC_CTRL_SHIFT_C = 0.0f;
/*=========================== ADC sampling offset corrections ===========================*/
float32 Va_offset = 0.80012984f;
float32 Vb_offset = -11.59252224f;
float32 Vc_offset = -3.75228743f;
float32 VA_GAIN = 0.11865400644f; // New divider 160:1; original A-phase calibration multiplied by 160/124
float32 VB_GAIN = 0.11611580758f; // New divider 160:1; original B-phase calibration multiplied by 160/124
float32 VC_GAIN = 0.11970312806f; // New divider 160:1; original C-phase calibration multiplied by 160/124
/* A-phase ADC calibration: use only the nine known current points from this test, with units A/count and ADC counts.
* Previous parameters: ILa_offset=1689.0, ILA_GAIN=-0.1455683678.
* Actual currents: 0,+10,+20,+30,+40,-10,-20,-30,-40 A.
* Previous displayed values: -6.394,42.5,91.91,141.33,190.82,-54.23,-103.54,-150.81,-200.86.
* Fix the offset at the 0 A point and fit a single signed gain by least squares on the other eight points:
* I_new=0.204707487762*(I_old+6.394); maximum residual for the given points is about 0.437 A.
* ILa display, HccILa and A-phase ADC overcurrent use this calibration; protection parameters are latched at startup.
* Calibrations for all three phases follow; CMPSS slopes are derived from ADC gain and the H/L comparator zero codes are retained.
* After changing ILa_offset/ILA_GAIN while stopped, restart to synchronize the latched protection parameters.
*/
#define ILA_ADC_ZERO_CAL 1732.924377916945f
#define ILA_ADC_GAIN_CAL (-0.029798934870f)
/* B-phase measured currents: 0,+10,+20,+30,+40,-10,-20,-30,-40 A.
* Previous displayed values: -5.434,44.3,95.61,147.12,198.03,-55.01,-104.67,-156.58,-205.64.
* Previous ILb_offset=1697.0, ILB_GAIN=-0.1501774643 A/count.
* I_new=0.198290412919*(I_old+5.434); zero offset fixed at 0 A, gain *** using the other eight points.
* Maximum residual is about 0.345 A; display/HccILb/sampled overcurrent share this calibration.
*/
#define ILB_ADC_ZERO_CAL 1733.183857713464f
#define ILB_ADC_GAIN_CAL (-0.029778751407f)
/* C-phase measured currents: 0,+10,+20,+30,+40,-10,-20,-30,-40 A.
* Previous displayed values: -10.79,38.49,87.34,136.46,186.72,-59.08,-108.17,-156.5,-204.36.
* Previous ILc_offset=1670.0, ILC_GAIN=-0.1453239771 A/count.
* I_new=0.204639170891*(I_old+10.79); zero offset fixed at 0 A, gain *** using the other eight points.
* Maximum residual is about 0.418 A; display/HccILc/sampled overcurrent share this calibration.
*/
#define ILC_ADC_ZERO_CAL 1744.247899178917f
#define ILC_ADC_GAIN_CAL (-0.029738978184f)
/* Signed physical V/A calibration shared by ADC and CMPSS. */
#define HCC_SLOPE_FROM_ADC(adc_vref, adc_gain) \
((adc_vref) / (IL_ADC_COUNTS_PER_RANGE * (adc_gain)))
volatile float32 ILa_offset = ILA_ADC_ZERO_CAL;
volatile float32 ILb_offset = ILB_ADC_ZERO_CAL;
volatile float32 ILc_offset = ILC_ADC_ZERO_CAL;
volatile float32 ILA_GAIN = ILA_ADC_GAIN_CAL; // A-phase nine-point calibration constrained to zero-current offset
volatile float32 ILB_GAIN = ILB_ADC_GAIN_CAL; // B-phase nine-point calibration constrained to zero-current offset
volatile float32 ILC_GAIN = ILC_ADC_GAIN_CAL; // C-phase nine-point calibration constrained to zero-current offset
/* ADC and CMPSS slope calculations share the three-phase gains latched at startup. */
static float32 hcc_ila_gain_active = ILA_ADC_GAIN_CAL;
/* B-phase ADC protection parameters are latched at startup. */
static float32 hcc_ilb_gain_active = ILB_ADC_GAIN_CAL;
/* C-phase ADC protection parameters are latched at startup. */
static float32 hcc_ilc_gain_active = ILC_ADC_GAIN_CAL;
float32 Vdc_offset = -11.43247685f; // DC-bus voltage zero-current offset from the supplied text
/*=========================== First-order low-pass filter coefficients ===========================*/
float32 alpha_v = 0.75f; //1-(1-0.50)^2, preserves old filter pole per second
float32 alpha_dc = 0.36f; //1-(1-0.20)^2
/*=========================== Low-pass filter history buffers ===========================*/
float32 Lp_last_Va = 0.0f;
float32 Lp_last_Vb = 0.0f;
float32 Lp_last_Vc = 0.0f;
float32 Lp_last_Vdc = 0.0f;
/*=========================== Raw ADC result-register values ===========================*/
Uint16 Va_ADC = 0U;
Uint16 Vb_ADC = 0U;
Uint16 Vc_ADC = 0U;
Uint16 ILa_ADC = 0U;
Uint16 ILb_ADC = 0U;
Uint16 ILc_ADC = 0U;
Uint16 Vdc_ADC = 0U;
/*=========================== Converted physical quantities ===========================*/
float32 Va = 0.0f;
float32 Vb = 0.0f;
float32 Vc = 0.0f;
float32 Vdc = 0.0f;
/* Unfiltered ADC-converted bus voltage for sampled overvoltage protection. */
volatile float32 Vdc_Protection = 0.0f;
/* Independent protection path: driven directly from raw Vdc_Protection,
* not cascaded after the existing alpha_dc control filter. */
volatile float32 Vdc_pro=0.0f;
volatile float32 alpha_pro=0.99f; //1-(1-0.90)^2
static Uint16 vdc_pro_initialized=0U;
/* Updated once per fresh ADC control sample; read-only to HccService. */
#define VBUS_OV_CONFIRM_SAMPLES 2U // nominal80us at25kHz; previously60us at50kHz
#define VBUS_OV_FAST_ADC_CODE 4094U
volatile Uint16 VbusOvCount=0U, VbusOvTrip=0U, VbusOvFast=0U;
volatile float32 Va_Protection=0.0f, Vb_Protection=0.0f, Vc_Protection=0.0f;
/*=========================== Three-phase voltage references ===========================*/
float32 Va1 = 0.0f; // A-phase 400 Hz sinusoidal voltage reference
float32 Vb1 = 0.0f; // B-phase 400 Hz sinusoidal voltage reference
float32 Vc1 = 0.0f; // C-phase 400 Hz sinusoidal voltage reference
Uint16 sine_cnt = 0U; // Sine lookup-table index counter
/*=========================== QPR debug variables retained for project compatibility ===========================*/
// In fixed-current-window mode, VaM/VbM/VcM do not participate in CMPSS threshold generation.
float32 VaM = 0.0f; // Retained for compatibility; unused for fixed-current-window control
float32 VbM = 0.0f; // Retained for compatibility; unused for fixed-current-window control
float32 VcM = 0.0f; // Retained for compatibility; unused for fixed-current-window control
// CCS Watch debug variables
float32 DcErrA = 0.0f; // Low-pass-filtered A-phase DC error
float32 DcErrB = 0.0f;
float32 DcErrC = 0.0f;
float32 DcTrimA = 0.0f; // Slow A-phase integral: PWM counts in single-voltage-loop mode, A in HCC mode
float32 DcTrimB = 0.0f;
float32 DcTrimC = 0.0f;
volatile Uint16 BuckHeadroomAlarm = 0U; // 1 = target feedforward peak for this stage exceeds reserved headroom
volatile Uint16 BuckRampHeld = 0U; // 1 = amplitude ramp paused due to current Vdc/integrator conditions
/*=========================== PWM startup state variables ===========================*/
Uint16 pwm_enable_cnt = 0U; // PWM power-up delay counter
Uint16 pwm_enabled = 0U; // PWM enable flag: 0 = off, 1 = on
/* Fixed ABSOLUTE physical inductor-current window, independent of Iref. */
#define HCC_FIXED_CURRENT_UPPER_A 5.0f
#define HCC_FIXED_CURRENT_LOWER_A (-5.0f)
#define HCC_FIXED_CURRENT_WIDTH_A (HCC_FIXED_CURRENT_UPPER_A - HCC_FIXED_CURRENT_LOWER_A)
/* Hardware CMPSS calibration values are still latched at startup. */
typedef struct {
float32 SlopeVperA,AdcZero,ActiveSlope,ActiveAdcZero,Iref;
} HCC_PHASE;
volatile HCC_PHASE HccPhase[3]={
{HCC_SLOPE_FROM_ADC(IL_ADCC_VREF_V,ILA_ADC_GAIN_CAL),ILA_ADC_ZERO_CAL,0,0,0},
{HCC_SLOPE_FROM_ADC(IL_ADCA_VREF_V,ILB_ADC_GAIN_CAL),ILB_ADC_ZERO_CAL,0,0,0},
{HCC_SLOPE_FROM_ADC(IL_ADCA_VREF_V,ILC_ADC_GAIN_CAL),ILC_ADC_ZERO_CAL,0,0,0}
};
/* Measured at zero current with the present CMPSS settings and VDDA.
* Edit only while stopped; active copies are latched at the next startup.
* H/L refer to the comparator identities, not to current upper/lower bounds. */
typedef struct {
Uint16 ZeroCodeH, ZeroCodeL;
Uint16 ActiveZeroCodeH, ActiveZeroCodeL;
} HCC_DAC_ZERO_CAL;
volatile HCC_DAC_ZERO_CAL HccDacCal[3] = {
{1541U,1537U,0U,0U},
{1519U,1515U,0U,0U},
{1521U,1525U,0U,0U}
};
volatile Uint16 HccRunEnable=0U; // Manual enable: set to 1 in CCS Watch; bus >= 400 V is also required to start
volatile Uint16 HccFault=0U, HccFaultReset=0U, HccReady=0U;
volatile float32 HccDacVref=3.3f; // CMPSS DAC reference voltage, retained from the original hardware configuration
volatile float32 HccILa=0.0f, HccILb=0.0f, HccILc=0.0f;
/* Edit while stopped and restart to latch all compensation settings.
* Shared Td terms use the effective edge delay in us. For A-phase fixed
* advance alone, leave both shared Td terms at zero. If both methods are
* used, enter only the residual A-phase error in the fixed terms.
*
* A-phase fixed advance is referred to CMPIN6P, in mV. Calibrate the
* static crossing voltages in the working crossing directions first.
* Rise: falling CMPIN6P arrives at GPIO24 late by a positive voltage
* difference (static crossing minus observed voltage). Raises DACL.
* Fall: rising CMPIN6P arrives at GPIO26 late by a positive voltage
* difference (observed voltage minus static crossing). Lowers DACH.
* Use synchronized traces and a verified negative A-phase sensor slope.
* Tune over the operating range. Large advances that consume the
* startup window are rejected as HccFault=2, HccFaultPhase=1.
*/
volatile Uint16 HccDelayEnable = 1U;
volatile float32 HccDelayTdRiseUs = 0.0f, HccDelayTdFallUs = 0.0f;
volatile float32 HccDelayInductanceUh = 24.0f;
volatile float32 HccAAdvanceRiseMv = 0.0f;
volatile float32 HccAAdvanceFallMv = 0.0f;
#define HCC_DELAY_MIN_CMD_WIDTH_A 0.30f
#define HCC_DELAY_DESIGN_BUS_V VBUS_OVER_TH
/* Active per-phase advances and prior commanded bounds. */
typedef struct {
float32 FixedRiseA, FixedFallA;
float32 DeltaRiseA, DeltaFallA, CmdUpperA, CmdLowerA;
} HCC_DELAY_PHASE;
static HCC_DELAY_PHASE HccDelayPhase[3];
static float32 hcc_delay_rise_a_per_v=0.0f,hcc_delay_fall_a_per_v=0.0f;
static float32 hcc_delay_dac_k[3]={0.0f,0.0f,0.0f};
/* Minimal latched fault identity; no per-fault waveform/snapshot copy. */
volatile Uint16 HccFaultPhase=0U,HccFaultMask=0U;
#define HCC_MASK_OC_A 0x0001U
#define HCC_MASK_OC_B 0x0002U
#define HCC_MASK_OC_C 0x0004U
#define HCC_MASK_OV_A 0x0008U
#define HCC_MASK_OV_B 0x0010U
#define HCC_MASK_OV_C 0x0020U
#define HCC_MASK_OV_DC 0x0040U
#define HCC_MASK_UV_DC 0x0080U
static float32 hcc_vref=3.3f;
/* 30A is a SECONDARY sampled-current trip with margin above +/-5A;
* the asynchronous CMPSS path performs actual hysteresis switching.
* This software check is only 25kHz and cannot guarantee peak limiting. */
#define HCC_SAMPLE_TRIP_A 30.0f
/*=========================== Main entry point ===========================*/
void main(void)
{
InitSysCtrl(); // Initialize system clock
InitGpio(); // Initialize GPIO
DINT; // Disable global interrupts
InitPieCtrl(); // Initialize PIE interrupt controller
IER = 0x0000U; // Clear CPU interrupt enable register
IFR = 0x0000U; // Clear CPU interrupt flag register
InitPieVectTable(); // Initialize interrupt vector table
EALLOW;
PieVectTable.ADCA1_INT = &adca1_isr; // Bind ADCA1 ISR
EDIS;
#ifdef _FLASH
InitFlash(); // Initialize Flash memory (Flash project build)
#endif
InitEPwm1Gpio();
InitEPwm2Gpio();
InitEPwm3Gpio();
InitEPwm4Gpio();
InitEPwm5Gpio();
InitEPwm6Gpio();
InitEPwm12Gpio(); // Configure ePWM GPIO pins
ConfigureADC(); // Basic ADC configuration
EALLOW;
CpuSysRegs.PCLKCR0.bit.TBCLKSYNC = 0U; // Disable ePWM time-base clock synchronization during individual configuration
EDIS;
ConfigureCMPSSCurrentWindow();
ConfigureHCCEPWMXBAR();
InitCMPSS6BoundaryMonitorGPIO(); // A-phase debug pins
InitEPWMd(); // HCC ePWM initialization
InitControllers(); // Initialize QPR controllers
InitSineTable(); // all trigonometric calls run before interrupts
ForceAllPWMOff(); // Latch all six power PWM outputs off before enabling TBCLKSYNC
EALLOW;
CpuSysRegs.PCLKCR0.bit.TBCLKSYNC = 1U; // Enable ePWM time-base clock synchronization
EDIS;
SetupADCEpwm(); // Configure ADC sampling triggers and channels
PieCtrlRegs.PIECTRL.bit.ENPIE = 1U; // Enable PIE interrupt controller
PieCtrlRegs.PIEIER1.bit.INTx1 = 1U; // Enable PIE group 1 interrupt 1
IER |= M_INT1; // Enable CPU interrupt group 1
EINT; // Enable global interrupts
ERTM; // Enable real-time debug interrupts
while(1)
{
// Idle main loop; all control logic executes in the ADC ISR
}
}
/*=========================== QPR controller initialization ===========================*/
static void InitControllers(void)
{
QPR_reset(&Va_QPR); // Reset A-phase QPR controller state
QPR_reset(&Vb_QPR); // Reset B-phase QPR controller state
QPR_reset(&Vc_QPR); // Reset C-phase QPR controller state
// Configure A-phase QPR controller
QPR_Control_config(&Va_QPR,
Kp_QPR_A,
Kr_QPR_A,
fc_inv,
acFreq_inv,
TSAM);
// Configure B-phase QPR controller
QPR_Control_config(&Vb_QPR,
Kp_QPR_B,
Kr_QPR_B,
fc_inv,
acFreq_inv,
TSAM);
// Configure C-phase QPR controller
QPR_Control_config(&Vc_QPR,
Kp_QPR_C,
Kr_QPR_C,
fc_inv,
acFreq_inv,
TSAM);
ResetVoltageLoopStates();
}
/* Clear all QPR and DC-offset regulation history to prevent stale states after a power-cycle restart */
static void ResetVoltageLoopStates(void)
{
QPR_reset(&Va_QPR);
QPR_reset(&Vb_QPR);
QPR_reset(&Vc_QPR);
HccPhase[0].Iref = HccPhase[1].Iref = HccPhase[2].Iref = 0.0f;
VaM = VbM = VcM = 0.0f;
DcErrA = DcErrB = DcErrC = 0.0f;
DcTrimA = DcTrimB = DcTrimC = 0.0f;
BuckHeadroomAlarm = 0U;
BuckRampHeld = 0U;
}
/*=====================25kHz control interrupt=====================*/
interrupt void adca1_isr(void)
{
Va_ADC=AdcbResultRegs.ADCRESULT1;Vb_ADC=AdcbResultRegs.ADCRESULT0;
Vc_ADC=AdcaResultRegs.ADCRESULT0;
ILa_ADC=AdccResultRegs.ADCRESULT0;ILb_ADC=AdcaResultRegs.ADCRESULT1;
ILc_ADC=AdcaResultRegs.ADCRESULT2;Vdc_ADC=AdccResultRegs.ADCRESULT1;
Va_Protection=((float32)Va_ADC-Va_offset)*VA_GAIN;
Vb_Protection=((float32)Vb_ADC-Vb_offset)*VB_GAIN;
Vc_Protection=((float32)Vc_ADC-Vc_offset)*VC_GAIN;
Vdc_Protection=((float32)Vdc_ADC-Vdc_offset)*VDC_GAIN;
Va=alpha_v*Va_Protection+(1.0f-alpha_v)*Lp_last_Va;
Vb=alpha_v*Vb_Protection+(1.0f-alpha_v)*Lp_last_Vb;
Vc=alpha_v*Vc_Protection+(1.0f-alpha_v)*Lp_last_Vc;
Vdc=alpha_dc*Vdc_Protection+(1.0f-alpha_dc)*Lp_last_Vdc;
Lp_last_Va=Va;Lp_last_Vb=Vb;Lp_last_Vc=Vc;Lp_last_Vdc=Vdc;
UpdateVdcProtectionFilter();UpdateVbusOvervoltageState();HccService();
if(HccRunEnable!=1U || HccFault!=0U ||
!(Vdc_pro>VBUS_OFF_TH && Vdc_pro<1000.0f &&
Va>-1000.0f && Va<1000.0f && Vb>-1000.0f && Vb<1000.0f &&
Vc>-1000.0f && Vc<1000.0f)) {
if(pwm_enabled!=0U || pwm_enable_cnt!=0U) ResetVoltageLoopStates();
DisableAllPWM();pwm_enable_cnt=0U;uref_current=UREF_START_VAL;sine_cnt=0U;
} else if(pwm_enabled!=0U) {
Gen_3PH_Sine_400Hz();UpdatePowerStageOutput();
} else if(Vdc_pro>=VBUS_START_TH) {
if(pwm_enable_cnt==0U) ResetVoltageLoopStates();
Gen_3PH_Sine_400Hz();
if(pwm_enable_cnt<PWM_ENABLE_DELAY_CNT) pwm_enable_cnt++;
if(pwm_enable_cnt>=PWM_ENABLE_DELAY_CNT) {
EnableAllPWM();
if(HccReady!=0U && HccFault==0U) pwm_enabled=1U;
}
}
AdcaRegs.ADCINTFLGCLR.bit.ADCINT1=1U;
if(AdcaRegs.ADCINTOVF.bit.ADCINT1!=0U) {
AdcaRegs.ADCINTOVFCLR.bit.ADCINT1=1U;
AdcaRegs.ADCINTFLGCLR.bit.ADCINT1=1U;
}
PieCtrlRegs.PIEACK.all=PIEACK_GROUP1;
}
/* Fixed hysteresis control mode:
* The QPR voltage outer loop, manual current reference and DC integrator no longer alter the inductor-current thresholds.
* Gen_3PH_Sine_400Hz() still generates a 400 Hz reference for monitoring, but does not control the current center.
*/
/* Negative sensor slope: high VOLTAGE => current too low => A ON.
* Low comparator is NOT inverted; DCB event is asserted when its output is LOW.
* In-band, neither event acts and AQ retains its previous state. */
static void ConfigureBuckPWMRunMode(volatile struct EPWM_REGS *pwm)
{
pwm->AQSFRC.bit.RLDCSF=3U;
pwm->AQCSFRC.all=0U;
pwm->AQCTLA.all=0U; pwm->AQCTLB.all=0U;
pwm->AQCTLA2.all=0U; pwm->AQCTLB2.all=0U;
pwm->AQCTLA2.bit.T1U=AQ_SET; pwm->AQCTLA2.bit.T1D=AQ_SET;
pwm->AQCTLA2.bit.T2U=AQ_CLEAR; pwm->AQCTLA2.bit.T2D=AQ_CLEAR;
pwm->DBCTL.bit.HALFCYCLE=0U;
pwm->DBCTL.bit.OUT_MODE=DB_FULL_ENABLE;
pwm->DBCTL.bit.POLSEL=DB_ACTV_HIC;
pwm->DBCTL.bit.IN_MODE=DBA_ALL;
pwm->DBRED.bit.DBRED=DIFFER; pwm->DBFED.bit.DBFED=DIFFER;
}
/*=========================== Fixed Boost-channel states for the new hardware ===========================*/
static void ConfigureBoostPWMFixedMode(volatile struct EPWM_REGS *pwm)
{
// In Buck operating mode, EPWM4/5/6 B is fixed high and A is fixed low.
// Disable dead band so independent A/B software-forced levels take effect.
pwm->AQCTLA.all = 0U;
pwm->AQCTLB.all = 0U;
pwm->DBCTL.bit.OUT_MODE = 0U;
pwm->AQSFRC.bit.RLDCSF = 3U; // Continuous AQ software force takes effect immediately
pwm->AQCSFRC.bit.CSFA = AQ_FORCE_LOW;
pwm->AQCSFRC.bit.CSFB = AQ_FORCE_HIGH;
// Downstream TZCTL TZA/TZB are both FORCE_LO, so shutdown still forces both outputs low.
}
/*=========================== Generate 400 Hz reference (monitoring only; no longer controls current bounds) ===========================*/
static void InitSineTable(void)
{
Uint16 i;float32 a;
for(i=0U;i<SINE_POINTS;i++) {
a=2.0f*PI_F*(float32)i/(float32)SINE_POINTS;
phase_sine_table[0][i]=sinf(a);
phase_sine_table[1][i]=sinf(a-PHASE_120);
phase_sine_table[2][i]=sinf(a+PHASE_120);
}
}
void Gen_3PH_Sine_400Hz(void)
{
float32 amp_used; // Nominal amplitude; also sets the unchanged DC ramp.
float32 max_ac_comp;
// The shared ramp must respect the phase with the largest AC reference.
max_ac_comp=VAC_AC_COMP_A;
if(VAC_AC_COMP_B>max_ac_comp) max_ac_comp=VAC_AC_COMP_B;
if(VAC_AC_COMP_C>max_ac_comp) max_ac_comp=VAC_AC_COMP_C;
// Soft start and high-duty-cycle feedforward headroom check
// DC reference=A+UREF_BASE_V; worst-case AC peak=A*max_ac_comp.
// Verify the maximum achievable high-side duty cycle separately on the real hardware.
{
float32 peak_ff_at_target;
float32 peak_ff_at_next;
float32 next_amp;
float32 allowed_ff,available_ff_v;
allowed_ff = (float32)BUCK_MAX_CMP -
(float32)BUCK_FF_RESERVE_CMP;
if(Vdc_pro > VBUS_OFF_TH && Vdc > 0.0f && Vdc < 1000.0f)
{
available_ff_v=allowed_ff*Vdc;
peak_ff_at_target = (float32)SP *
(FF_DC_GAIN * (UREF_TARGET + UREF_BASE_V) +
FF_AC_GAIN * UREF_TARGET * max_ac_comp);
BuckHeadroomAlarm =
(peak_ff_at_target > available_ff_v) ? 1U : 0U;
if((pwm_enable_cnt >= PWM_ENABLE_DELAY_CNT) &&
(uref_current < UREF_TARGET))
{
next_amp = uref_current + UREF_STEP;
if(next_amp > UREF_TARGET)
next_amp = UREF_TARGET;
peak_ff_at_next = (float32)SP *
(FF_DC_GAIN * (next_amp + UREF_BASE_V) +
FF_AC_GAIN * next_amp * max_ac_comp);
if(peak_ff_at_next <= available_ff_v)
{
uref_current = next_amp;
BuckRampHeld = 0U;
}
else
{
// Do not increase amplitude toward a peak with no remaining modulation headroom.
BuckRampHeld = 1U;
}
}
else
{
BuckRampHeld = 0U;
}
}
else
{
BuckHeadroomAlarm = 1U;
BuckRampHeld = 1U;
}
}
amp_used = uref_current;
// Preserve the original electrical-angle calculation logic
// Generate three-phase voltages using the ramped amplitude amp_used
// Per-phase AC scaling; all three DC centers stay amp_used+25V.
Va1 = amp_used * VAC_AC_COMP_A * phase_sine_table[0][sine_cnt] + amp_used + UREF_BASE_V;
Vb1 = amp_used * VAC_AC_COMP_B * phase_sine_table[1][sine_cnt] + amp_used + UREF_BASE_V;
Vc1 = amp_used * VAC_AC_COMP_C * phase_sine_table[2][sine_cnt] + amp_used + UREF_BASE_V;
// Preserve the original lookup-table index wrapping
sine_cnt+=SINE_INDEX_STEP;
if(sine_cnt >= SINE_POINTS)
{
sine_cnt-=SINE_POINTS; // preserve the fractional-cycle phase remainder
}
}
/*=========================== Common basic ePWM module configuration ===========================*/
static void ConfigureEPWMCommon(volatile struct EPWM_REGS *pwm)
{
EALLOW;
pwm->TZCTL.bit.TZA=TZ_FORCE_LO; pwm->TZCTL.bit.TZB=TZ_FORCE_LO;
pwm->TZFRC.bit.OST=1U;
EDIS;
pwm->TBPRD = SP; // sampling timebase, not HCC switching period
// Configure time-base clock dividers: no prescaling
pwm->TBCTL.bit.HSPCLKDIV = TB_DIV1;
pwm->TBCTL.bit.CLKDIV = TB_DIV1;
pwm->TBCTL.bit.CTRMODE = TB_COUNT_UPDOWN; // Up-down counting mode
pwm->TBCTL.bit.SYNCOSEL = TB_SYNC_DISABLE; // Disable synchronization output
pwm->TBCTL.bit.PHSEN = TB_DISABLE; // Disable phase loading
pwm->TBCTL.bit.PHSDIR = 1U;
pwm->TBPHS.bit.TBPHS = 0U; // Clear phase shift
pwm->TBCTR = 0U; // Initialize counter to zero
// CMPA/CMPB use shadow registers, loaded on counter zero and period events
pwm->CMPCTL.bit.SHDWAMODE = CC_SHADOW;
pwm->CMPCTL.bit.LOADAMODE = CC_CTR_ZERO_PRD;
pwm->CMPCTL.bit.SHDWBMODE = CC_SHADOW;
pwm->CMPCTL.bit.LOADBMODE = CC_CTR_ZERO_PRD;
pwm->CMPA.bit.CMPA = SP / 2U; // Initial 50% duty cycle
pwm->CMPB.bit.CMPB = SP / 2U;
// Clear AQ/DB first; ConfigureEPWM1..6 will set their individual operating modes.
pwm->AQCTLA.all = 0U;
pwm->AQCTLB.all = 0U;
pwm->AQCSFRC.all = 0U;
pwm->AQSFRC.bit.RLDCSF = 3U;
pwm->DBCTL.all = 0U;
pwm->DBRED.bit.DBRED = DIFFER;
pwm->DBFED.bit.DBFED = DIFFER;
EALLOW;
pwm->TZCTL.bit.TZA = TZ_FORCE_LO; // TZ fault forces channel A low
pwm->TZCTL.bit.TZB = TZ_FORCE_LO; // TZ fault forces channel B low
EDIS;
}
/**
* @brief Initialize EPWM1 (C-phase Buck)
*/
void ConfigureEPWM1(void)
{
ConfigureEPWMCommon(&EPwm1Regs);
ConfigureBuckPWMRunMode(&EPwm1Regs);
ConfigureEPWMHardwareHCCInput(&EPwm1Regs,8U,9U);
}
/**
* @brief Initialize EPWM2 (B-phase Buck)
*/
void ConfigureEPWM2(void)
{
ConfigureEPWMCommon(&EPwm2Regs);
ConfigureBuckPWMRunMode(&EPwm2Regs);
ConfigureEPWMHardwareHCCInput(&EPwm2Regs,6U,7U);
// Also use EPWM2 CMPB to trigger ADC sampling; it does not affect Buck A/B switching actions.
// Buck A is driven by CMPSS T1/T2 events; B is produced by the dead-band module.
EPwm2Regs.CMPB.bit.CMPB = SP / 4U;
EPwm2Regs.ETSEL.bit.SOCASEL = ET_CTRU_CMPB;
EPwm2Regs.ETPS.bit.SOCAPRD = ET_1ST;
EPwm2Regs.ETCLR.bit.SOCA = 1U;
EPwm2Regs.ETSEL.bit.SOCAEN = 1U;
}
/**
* @brief Initialize EPWM3 (A-phase Buck)
*/
void ConfigureEPWM3(void)
{
ConfigureEPWMCommon(&EPwm3Regs);
ConfigureBuckPWMRunMode(&EPwm3Regs);
ConfigureEPWMHardwareHCCInput(&EPwm3Regs,3U,4U);
}
/**
* @brief Initialize EPWM4 (A-phase Boost; physical B/A order)
*/
void ConfigureEPWM4(void)
{
ConfigureEPWMCommon(&EPwm4Regs);
ConfigureBoostPWMFixedMode(&EPwm4Regs);
}
/**
* @brief Initialize EPWM5 (B-phase Boost; physical B/A order)
*/
void ConfigureEPWM5(void)
{
ConfigureEPWMCommon(&EPwm5Regs);
ConfigureBoostPWMFixedMode(&EPwm5Regs);
}
/**
* @brief Initialize EPWM6 (C-phase Boost; physical B/A order)
*/
void ConfigureEPWM6(void)
{
ConfigureEPWMCommon(&EPwm6Regs);
ConfigureBoostPWMFixedMode(&EPwm6Regs);
}
/*=========================== EPWM12:100kHz SOCA,25kHz SOCB ===========================*/
void ConfigureEPWM12(void)
{
// Use the same 100 kHz time base as the six power PWMs; separate trigger events serve sampling and control.
EPwm12Regs.TBPRD = SP;
EPwm12Regs.TBCTL.bit.HSPCLKDIV = TB_DIV1;
EPwm12Regs.TBCTL.bit.CLKDIV = TB_DIV1;
EPwm12Regs.TBCTL.bit.CTRMODE = TB_COUNT_UPDOWN;
EPwm12Regs.TBCTL.bit.SYNCOSEL = TB_SYNC_DISABLE;
EPwm12Regs.TBCTL.bit.PHSEN = TB_DISABLE;
EPwm12Regs.TBCTL.bit.PHSDIR = 1U;
EPwm12Regs.TBPHS.bit.TBPHS = 0U;
EPwm12Regs.TBCTR = 0U;
EPwm12Regs.CMPA.bit.CMPA = SP / 2U; // Separate later Vdc sample
// The up-counting CMPA event in each 100 kHz period triggers analog sampling.
EPwm12Regs.ETSEL.bit.SOCAEN = 1U;
EPwm12Regs.ETSEL.bit.SOCASEL = ET_CTRU_CMPA;
/* Extended prescale selects both A/B counters:100kHz SOCA stays /1;
*100kHz PRD events produce SOCB every4th event, for25kHz control. */
EPwm12Regs.ETPS.bit.SOCPSSEL = 1U;
EPwm12Regs.ETSOCPS.bit.SOCAPRD2 = 1U;
// Every fourth100kHz PRD event triggers ADCA SOC15, producing25kHz control.
EPwm12Regs.ETSEL.bit.SOCBEN = 1U;
EPwm12Regs.ETSEL.bit.SOCBSEL = ET_CTR_PRD;
EPwm12Regs.ETSOCPS.bit.SOCBPRD2 = 4U;
EPwm12Regs.ETCLR.bit.SOCA = 1U;
EPwm12Regs.ETCLR.bit.SOCB = 1U;
}
/*=========================== All ePWM clock and initialization entry point ===========================*/
void InitEPWMd(void)
{
EALLOW;
// Explicitly set EPWMCLK = SYSCLK/2 to match TBPRD and the 100 ns dead-time calculation.
ClkCfgRegs.PERCLKDIVSEL.bit.EPWMCLKDIV = 1U;
// Enable ePWM peripheral clocks for channels 1/2/3/4/5/6/12
CpuSysRegs.PCLKCR2.bit.EPWM1 = 1U;
CpuSysRegs.PCLKCR2.bit.EPWM2 = 1U;
CpuSysRegs.PCLKCR2.bit.EPWM3 = 1U;
CpuSysRegs.PCLKCR2.bit.EPWM4 = 1U;
CpuSysRegs.PCLKCR2.bit.EPWM5 = 1U;
CpuSysRegs.PCLKCR2.bit.EPWM6 = 1U;
CpuSysRegs.PCLKCR2.bit.EPWM12 = 1U;
EDIS;
// Configure each ePWM register set
ConfigureEPWM1();
ConfigureEPWM2();
ConfigureEPWM3();
ConfigureEPWM4();
ConfigureEPWM5();
ConfigureEPWM6();
ConfigureEPWM12();
}
/*=========================== Basic ADC hardware configuration ===========================*/
void ConfigureADC(void)
{
EALLOW;
// Configure ADC clock divider
AdcaRegs.ADCCTL2.bit.PRESCALE = 6U;
AdcbRegs.ADCCTL2.bit.PRESCALE = 6U;
AdccRegs.ADCCTL2.bit.PRESCALE = 6U;
// Configure 12-bit single-ended ADC mode
AdcSetMode(ADC_ADCA, ADC_RESOLUTION_12BIT, ADC_SIGNALMODE_SINGLE);
AdcSetMode(ADC_ADCB, ADC_RESOLUTION_12BIT, ADC_SIGNALMODE_SINGLE);
AdcSetMode(ADC_ADCC, ADC_RESOLUTION_12BIT, ADC_SIGNALMODE_SINGLE);
// Generate interrupt pulses after sample conversion completes
AdcaRegs.ADCCTL1.bit.INTPULSEPOS = 1U;
AdcbRegs.ADCCTL1.bit.INTPULSEPOS = 1U;
AdccRegs.ADCCTL1.bit.INTPULSEPOS = 1U;
// Enable ADC power
AdcaRegs.ADCCTL1.bit.ADCPWDNZ = 1U;
AdcbRegs.ADCCTL1.bit.ADCPWDNZ = 1U;
AdccRegs.ADCCTL1.bit.ADCPWDNZ = 1U;
DELAY_US(1000); // Wait for ADC stabilization
EDIS;
}
/*=========================== New-board ADC channels and EPWM12 triggers ===========================*/
void SetupADCEpwm(void)
{
Uint16 acqps = 39U; // 12-bit single-ended acquisition window from the reference program
EALLOW;
// A0 (Vc) uses early EPWM2 sampling; A3 (ILc)/A5 (ILb) retain EPWM12; Vdc uses separate later EPWM12 sampling.
AdcaRegs.ADCSOC0CTL.bit.CHSEL = 0U;
AdcaRegs.ADCSOC0CTL.bit.ACQPS = acqps;
AdcaRegs.ADCSOC0CTL.bit.TRIGSEL = ADC_TRIG_EPWM2_SOCA; // Vc
AdcaRegs.ADCSOC1CTL.bit.CHSEL = 5U;
AdcaRegs.ADCSOC1CTL.bit.ACQPS = acqps;
AdcaRegs.ADCSOC1CTL.bit.TRIGSEL = ADC_TRIG_EPWM12_SOCA;
AdcaRegs.ADCSOC2CTL.bit.CHSEL = 3U;
AdcaRegs.ADCSOC2CTL.bit.ACQPS = acqps;
AdcaRegs.ADCSOC2CTL.bit.TRIGSEL = ADC_TRIG_EPWM12_SOCA;
// EPWM12 SOCA at 100 kHz: ADCB = B0 (Vb), B1 (Va).
AdcbRegs.ADCSOC0CTL.bit.CHSEL = 0U;
AdcbRegs.ADCSOC0CTL.bit.ACQPS = acqps;
AdcbRegs.ADCSOC0CTL.bit.TRIGSEL = ADC_TRIG_EPWM2_SOCA; // Vb
AdcbRegs.ADCSOC1CTL.bit.CHSEL = 1U;
AdcbRegs.ADCSOC1CTL.bit.ACQPS = acqps;
AdcbRegs.ADCSOC1CTL.bit.TRIGSEL = ADC_TRIG_EPWM2_SOCA; // Va
// EPWM12 SOCA at 100 kHz: ADCC = C3 (ILa), C4 (Vdc).
AdccRegs.ADCSOC0CTL.bit.CHSEL = 3U;
AdccRegs.ADCSOC0CTL.bit.ACQPS = acqps;
AdccRegs.ADCSOC0CTL.bit.TRIGSEL = ADC_TRIG_EPWM12_SOCA;
AdccRegs.ADCSOC1CTL.bit.CHSEL = 4U;
AdccRegs.ADCSOC1CTL.bit.ACQPS = 79U; // Separate 400 ns Vdc acquisition window (SYSCLK = 200 MHz)
AdccRegs.ADCSOC1CTL.bit.TRIGSEL = ADC_TRIG_EPWM12_SOCA;
// Add a second sample of ADCINC4 to diagnose channel crosstalk from SOC0 current to SOC1 voltage.
// SOC2 is diagnostic only; it does not change the Vdc algorithm input or the existing TZ undervoltage protection.
AdccRegs.ADCSOC2CTL.bit.CHSEL = 4U;
AdccRegs.ADCSOC2CTL.bit.ACQPS = 79U;
AdccRegs.ADCSOC2CTL.bit.TRIGSEL = ADC_TRIG_EPWM12_SOCA;
// EPWM12 SOCB25kHz: SOC15 provides ADCA1 timing; RESULT15 is not feedback.
AdcaRegs.ADCSOC15CTL.bit.CHSEL = 0U;
AdcaRegs.ADCSOC15CTL.bit.ACQPS = acqps;
AdcaRegs.ADCSOC15CTL.bit.TRIGSEL = ADC_TRIG_EPWM12_SOCB;
AdcaRegs.ADCINTSEL1N2.bit.INT1SEL = 15U; // EOC15 -> ADCA1
AdcaRegs.ADCINTSEL1N2.bit.INT1E = 1U;
AdcaRegs.ADCINTFLGCLR.bit.ADCINT1 = 1U;
AdcaRegs.ADCINTOVFCLR.bit.ADCINT1 = 1U;
EDIS;
}
/*=========================== Low-level PWM switching control functions ===========================*/
/**
* @brief Force one PWM channel A low before configuring the fault latch
* @param pwm: pointer to ePWM registers
*/
/**
* @brief Disable all six PWMs and trigger one-shot TZ fault latches
*/
void ForceAllPWMOff(void)
{
EALLOW;
// Set the OST one-shot fault latches to block PWM outputs
EPwm1Regs.TZFRC.bit.OST = 1U;
EPwm2Regs.TZFRC.bit.OST = 1U;
EPwm3Regs.TZFRC.bit.OST = 1U;
EPwm4Regs.TZFRC.bit.OST = 1U;
EPwm5Regs.TZFRC.bit.OST = 1U;
EPwm6Regs.TZFRC.bit.OST = 1U;
EDIS;
}
/**
* @brief Clear the fault latches for all six PWMs and restore normal gate-drive outputs
*/
void EnableAllPWM(void)
{
if(HccRunEnable != 1U || HccFault != 0U) return;
HccService();
if(HccFault != 0U) return;
if(HccPrepareStart() == 0U) return;
ConfigureBoostPWMFixedMode(&EPwm4Regs);
ConfigureBoostPWMFixedMode(&EPwm5Regs);
ConfigureBoostPWMFixedMode(&EPwm6Regs);
HccSeed(&EPwm3Regs,&Cmpss6Regs);
HccSeed(&EPwm2Regs,&Cmpss2Regs);
HccSeed(&EPwm1Regs,&Cmpss1Regs);
EALLOW;
EPwm1Regs.TZCLR.bit.OST=1U; EPwm2Regs.TZCLR.bit.OST=1U;
EPwm3Regs.TZCLR.bit.OST=1U; EPwm4Regs.TZCLR.bit.OST=1U;
EPwm5Regs.TZCLR.bit.OST=1U; EPwm6Regs.TZCLR.bit.OST=1U;
EDIS;
HccReady=1U;
}
/**
* @brief Emergency shutdown of all PWMs: latch TZ faults and clear the enable flag
*/
void DisableAllPWM(void)
{
EALLOW;
EPwm1Regs.TZFRC.bit.OST = 1U;
EPwm2Regs.TZFRC.bit.OST = 1U;
EPwm3Regs.TZFRC.bit.OST = 1U;
EPwm4Regs.TZFRC.bit.OST = 1U;
EPwm5Regs.TZFRC.bit.OST = 1U;
EPwm6Regs.TZFRC.bit.OST = 1U;
EDIS;
pwm_enabled = 0U;
HccReady=0U;
}
/*==================== Fixed-band hardware current loop ====================*/
/*
* A-phase asynchronous CMPSS6 boundary monitor (no ISR/ADC latency).
* Negative-slope sensing:
* upper crossed -> CTRIPOUTL = 0 -> GPIO24 = 1 (inverted X-BAR)
* lower crossed -> CTRIPOUTH = 1 -> GPIO26 = 1 (normal X-BAR)
* inside window -> GPIO24 = 0, GPIO26 = 0.
* These pins are NOT event latches: return to zero inside the window.
*/
static void InitCMPSS6BoundaryMonitorGPIO(void)
{
EALLOW;
/* Drive both pins low as GPIO while preparing the X-BAR. */
GpioCtrlRegs.GPAGMUX2.bit.GPIO24 = 0U;
GpioCtrlRegs.GPAMUX2.bit.GPIO24 = 0U;
GpioCtrlRegs.GPAGMUX2.bit.GPIO26 = 0U;
GpioCtrlRegs.GPAMUX2.bit.GPIO26 = 0U;
GpioCtrlRegs.GPAPUD.bit.GPIO24 = 1U;
GpioCtrlRegs.GPAPUD.bit.GPIO26 = 1U;
GpioDataRegs.GPACLEAR.bit.GPIO24 = 1U;
GpioDataRegs.GPACLEAR.bit.GPIO26 = 1U;
GpioCtrlRegs.GPADIR.bit.GPIO24 = 1U;
GpioCtrlRegs.GPADIR.bit.GPIO26 = 1U;
/* Change only Output X-BAR output1/output3, not the power ePWM X-BAR. */
OutputXbarRegs.OUTPUT1MUXENABLE.all = 0UL;
OutputXbarRegs.OUTPUT3MUXENABLE.all = 0UL;
OutputXbarRegs.OUTPUT1MUX0TO15CFG.all = 0UL;
OutputXbarRegs.OUTPUT1MUX16TO31CFG.all = 0UL;
OutputXbarRegs.OUTPUT3MUX0TO15CFG.all = 0UL;
OutputXbarRegs.OUTPUT3MUX16TO31CFG.all = 0UL;
/* CMPSS6 CTRIPOUTL (MUX11.0) -> inverted OUTPUT1 -> GPIO24 */
OutputXbarRegs.OUTPUT1MUX0TO15CFG.bit.MUX11 = 0U;
OutputXbarRegs.OUTPUT1MUXENABLE.bit.MUX11 = 1U;
OutputXbarRegs.OUTPUTINV.bit.OUTPUT1 = 1U;
/* CMPSS6 CTRIPOUTH (MUX10.0) -> OUTPUT3 -> GPIO26 */
OutputXbarRegs.OUTPUT3MUX0TO15CFG.bit.MUX10 = 0U;
OutputXbarRegs.OUTPUT3MUXENABLE.bit.MUX10 = 1U;
OutputXbarRegs.OUTPUTINV.bit.OUTPUT3 = 0U;
/* Do not latch signals at the output X-BAR. */
OutputXbarRegs.OUTPUTLATCHENABLE.bit.OUTPUT1 = 0U;
OutputXbarRegs.OUTPUTLATCHENABLE.bit.OUTPUT3 = 0U;
OutputXbarRegs.OUTPUTLATCHCLR.bit.OUTPUT1 = 1U;
OutputXbarRegs.OUTPUTLATCHCLR.bit.OUTPUT3 = 1U;
/* GPIO mux function 1 = OUTPUTXBAR1 for GPIO24, OUTPUTXBAR3 for GPIO26 */
GpioCtrlRegs.GPAGMUX2.bit.GPIO24 = 0U;
GpioCtrlRegs.GPAMUX2.bit.GPIO24 = 1U;
GpioCtrlRegs.GPAGMUX2.bit.GPIO26 = 0U;
GpioCtrlRegs.GPAMUX2.bit.GPIO26 = 1U;
EDIS;
}
static void ConfigureHCCEPWMXBAR(void)
{
EALLOW;
/* Clear and reconfigure ePWM X-BAR routes for TRIP4/5/7/8/9/10. */
EPwmXbarRegs.TRIP4MUX0TO15CFG.all = 0U;
EPwmXbarRegs.TRIP4MUX16TO31CFG.all = 0U;
EPwmXbarRegs.TRIP4MUXENABLE.all = 0U;
EPwmXbarRegs.TRIP5MUX0TO15CFG.all = 0U;
EPwmXbarRegs.TRIP5MUX16TO31CFG.all = 0U;
EPwmXbarRegs.TRIP5MUXENABLE.all = 0U;
EPwmXbarRegs.TRIP7MUX0TO15CFG.all = 0U;
EPwmXbarRegs.TRIP7MUX16TO31CFG.all = 0U;
EPwmXbarRegs.TRIP7MUXENABLE.all = 0U;
EPwmXbarRegs.TRIP8MUX0TO15CFG.all = 0U;
EPwmXbarRegs.TRIP8MUX16TO31CFG.all = 0U;
EPwmXbarRegs.TRIP8MUXENABLE.all = 0U;
EPwmXbarRegs.TRIP9MUX0TO15CFG.all = 0U;
EPwmXbarRegs.TRIP9MUX16TO31CFG.all = 0U;
EPwmXbarRegs.TRIP9MUXENABLE.all = 0U;
EPwmXbarRegs.TRIP10MUX0TO15CFG.all = 0U;
EPwmXbarRegs.TRIP10MUX16TO31CFG.all = 0U;
EPwmXbarRegs.TRIP10MUXENABLE.all = 0U;
/* A-phase: CMPSS6 CTRIPH/CTRIPL -> TRIP4/TRIP5 (MUX10/MUX11). */
EPwmXbarRegs.TRIP4MUX0TO15CFG.bit.MUX10 = 0U;
EPwmXbarRegs.TRIP4MUXENABLE.bit.MUX10 = 1U;
EPwmXbarRegs.TRIP5MUX0TO15CFG.bit.MUX11 = 0U;
EPwmXbarRegs.TRIP5MUXENABLE.bit.MUX11 = 1U;
/* B-phase: CMPSS2 CTRIPH/CTRIPL -> TRIP7/TRIP8 (MUX2/MUX3). */
EPwmXbarRegs.TRIP7MUX0TO15CFG.bit.MUX2 = 0U;
EPwmXbarRegs.TRIP7MUXENABLE.bit.MUX2 = 1U;
EPwmXbarRegs.TRIP8MUX0TO15CFG.bit.MUX3 = 0U;
EPwmXbarRegs.TRIP8MUXENABLE.bit.MUX3 = 1U;
/* C-phase: CMPSS1 CTRIPH/CTRIPL -> TRIP9/TRIP10 (MUX0/MUX1). */
EPwmXbarRegs.TRIP9MUX0TO15CFG.bit.MUX0 = 0U;
EPwmXbarRegs.TRIP9MUXENABLE.bit.MUX0 = 1U;
EPwmXbarRegs.TRIP10MUX0TO15CFG.bit.MUX1 = 0U;
EPwmXbarRegs.TRIP10MUXENABLE.bit.MUX1 = 1U;
EPwmXbarRegs.TRIPOUTINV.all = 0U;
EDIS;
}
static void ConfigureEPWMHardwareHCCInput(volatile struct EPWM_REGS *pwm,
Uint16 high_trip_sel,
Uint16 low_trip_sel)
{
EALLOW;
/* Route the selected high/low Trip signals into DCA/DCB and generate T1/T2 digital-compare events for AQ. */
pwm->DCTRIPSEL.bit.DCAHCOMPSEL = high_trip_sel;
pwm->DCTRIPSEL.bit.DCBHCOMPSEL = low_trip_sel;
pwm->TZDCSEL.bit.DCAEVT2 = TZ_DCAH_HI;
pwm->TZDCSEL.bit.DCBEVT2 = TZ_DCBH_LOW;
pwm->DCACTL.bit.EVT2SRCSEL = DC_EVT2;
pwm->DCACTL.bit.EVT2FRCSYNCSEL = DC_EVT_ASYNC;
pwm->DCBCTL.bit.EVT2SRCSEL = DC_EVT2;
pwm->DCBCTL.bit.EVT2FRCSYNCSEL = DC_EVT_ASYNC;
/* Select DCAEVT2 for AQ T1 and DCBEVT2 for T2. */
pwm->AQTSRCSEL.bit.T1SEL = 1U;
pwm->AQTSRCSEL.bit.T2SEL = 3U;
/* Periodic HCC AQ transitions do not use Trip-Zone; TZ remains reserved for protective OST shutdown. */
pwm->TZSEL.bit.DCAEVT2 = 0U;
pwm->TZSEL.bit.DCBEVT2 = 0U;
pwm->TZCTL.bit.DCAEVT2 = TZ_NO_CHANGE;
pwm->TZCTL.bit.DCBEVT2 = TZ_NO_CHANGE;
pwm->TZCLR.bit.DCAEVT2 = 1U;
pwm->TZCLR.bit.DCBEVT2 = 1U;
EDIS;
}
static void ConfigureOneCMPSS(volatile struct CMPSS_REGS *cmpss)
{
cmpss->COMPCTL.all = 0U;
cmpss->COMPDACCTL.all = 0U;
/* Configure CMPSS comparators and internal DACs. */
cmpss->COMPDACCTL.bit.DACSOURCE = 0U;
cmpss->COMPDACCTL.bit.SELREF = 0U;
cmpss->COMPDACCTL.bit.RAMPSOURCE = 11U;
cmpss->COMPDACCTL.bit.SWLOADSEL = 0U;
cmpss->COMPCTL.bit.COMPHSOURCE = 0U;
cmpss->COMPCTL.bit.COMPLSOURCE = 0U;
/* Neither comparator is inverted; detect out-of-range low voltage using a LOW event in the DC stage. */
cmpss->COMPCTL.bit.COMPHINV = 0U;
cmpss->COMPCTL.bit.COMPLINV = 0U;
/* CTRIP/CTRIPOUT select the raw asynchronous comparator outputs.
* The filter remains available for the startup-only COMPSTS read. */
cmpss->COMPCTL.bit.CTRIPHSEL = 0U;
cmpss->COMPCTL.bit.CTRIPOUTHSEL = 0U;
cmpss->COMPCTL.bit.CTRIPLSEL = 0U;
cmpss->COMPCTL.bit.CTRIPOUTLSEL = 0U;
cmpss->COMPCTL.bit.ASYNCHEN = 1U;
cmpss->COMPCTL.bit.ASYNCLEN = 1U;
cmpss->COMPHYSCTL.bit.COMPHYS = 0U;
cmpss->DACHVALS.bit.DACVAL = 4095U;
cmpss->DACLVALS.bit.DACVAL = 0U;
cmpss->COMPSTSCLR.bit.HLATCHCLR = 1U;
cmpss->COMPSTSCLR.bit.LLATCHCLR = 1U;
cmpss->COMPCTL.bit.COMPDACE = 1U;
/* COMPSTS reflects the FILTER output, not the raw asynchronous output.
* Initialize a one-sample monitor for reliable static status/seed reads.
* SAMPWIN and THRESH encode actual counts minus one. CTRIP*SEL stays 0.
*/
cmpss->CTRIPHFILCLKCTL.bit.CLKPRESCALE = 0U;
cmpss->CTRIPLFILCLKCTL.bit.CLKPRESCALE = 0U;
cmpss->CTRIPHFILCTL.all = 0U;
cmpss->CTRIPLFILCTL.all = 0U;
cmpss->CTRIPHFILCTL.bit.SAMPWIN = 0U;
cmpss->CTRIPHFILCTL.bit.THRESH = 0U;
cmpss->CTRIPLFILCTL.bit.SAMPWIN = 0U;
cmpss->CTRIPLFILCTL.bit.THRESH = 0U;
cmpss->CTRIPHFILCTL.bit.FILINIT = 1U;
cmpss->CTRIPLFILCTL.bit.FILINIT = 1U;
}
static void ConfigureCMPSSCurrentWindow(void)
{
EALLOW;
CpuSysRegs.PCLKCR14.bit.CMPSS6=1U;
CpuSysRegs.PCLKCR14.bit.CMPSS2=1U;
CpuSysRegs.PCLKCR14.bit.CMPSS1=1U;
EDIS;
DELAY_US(1);
EALLOW;
ConfigureOneCMPSS(&Cmpss6Regs);
ConfigureOneCMPSS(&Cmpss2Regs);
ConfigureOneCMPSS(&Cmpss1Regs);
EDIS;
DELAY_US(20);
}
/* Independent measured comparator zero codes include each DAC/comparator
* offset. The current displacement uses the physical slope derived from ADC calibration.
* Raw high-low code ordering is NOT a physical-window validity criterion. */
static Uint16 HccBuildDelayWindow(float32 upper,float32 lower,float32 k,
Uint16 zeroH,Uint16 zeroL,Uint16 *high,Uint16 *low)
{
float32 vh,vl,span;
Uint16 hi,lo;
if(!(upper>lower && upper<HCC_SAMPLE_TRIP_A && lower>-HCC_SAMPLE_TRIP_A &&
k<-0.01f && k>-1000.0f && zeroH>=1U && zeroH<=4094U &&
zeroL>=1U && zeroL<=4094U)) return 0U;
vh=(float32)zeroH+k*lower;
vl=(float32)zeroL+k*upper;
if(!(vh>=1.0f && vh<=4094.0f && vl>=1.0f && vl<=4094.0f)) return 0U;
/* Negative sensor slope: floor DACH and ceil DACL round inward in current. */
hi=(Uint16)vh;lo=(Uint16)vl;
if((float32)lo<vl) lo++;
span=((float32)hi-(float32)zeroH)-((float32)lo-(float32)zeroL);
if(!(span>=4.0f)) return 0U;
*high=hi;*low=lo;return 1U;
}
static void HccWriteWindow(volatile struct CMPSS_REGS *cmp,Uint16 high,Uint16 low,
Uint16 upper_first)
{
EALLOW;
if(upper_first!=0U) {
cmp->DACLVALS.bit.DACVAL=low;cmp->DACHVALS.bit.DACVAL=high;
} else {
cmp->DACHVALS.bit.DACVAL=high;cmp->DACLVALS.bit.DACVAL=low;
}
EDIS;
}
static void HccTripDetail(Uint16 code,Uint16 phase,Uint16 mask)
{
DisableAllPWM();
if(HccFault==0U) {
HccFaultPhase=phase;HccFaultMask=mask;HccFault=code;
}
}
static void HccTrip(Uint16 code)
{
HccTripDetail(code,0U,0U);
}
static void UpdateVdcProtectionFilter(void)
{
/* Invalid input must not poison the persistent LPF state. HccService
* still checks raw/control bus and alpha and faults on invalid values. */
if(!(alpha_pro>0.0f && alpha_pro<=1.0f)) return;
if(!(Vdc_Protection>=0.0f && Vdc_Protection<1000.0f)) return;
if(vdc_pro_initialized==0U) {
Vdc_pro=Vdc_Protection;
vdc_pro_initialized=1U;
} else {
Vdc_pro += alpha_pro*(Vdc_Protection-Vdc_pro);
}
}
static void UpdateVbusOvervoltageState(void)
{
if(Vdc_pro >= VBUS_OVER_TH) {
if(VbusOvCount < VBUS_OV_CONFIRM_SAMPLES) VbusOvCount++;
} else {
VbusOvCount=0U;
}
VbusOvFast=(Vdc_ADC >= VBUS_OV_FAST_ADC_CODE)?1U:0U;
VbusOvTrip=((VbusOvCount >= VBUS_OV_CONFIRM_SAMPLES) ||
(VbusOvFast != 0U))?1U:0U;
}
static void HccService(void)
{
float32 values[3],volts[3],limits[3];
Uint16 raw[3],i,mask,invalid_phase;
if(HccReady!=0U) {
values[0]=((float32)ILa_ADC-HccPhase[0].ActiveAdcZero)*hcc_ila_gain_active;
values[1]=((float32)ILb_ADC-HccPhase[1].ActiveAdcZero)*hcc_ilb_gain_active;
values[2]=((float32)ILc_ADC-HccPhase[2].ActiveAdcZero)*hcc_ilc_gain_active;
} else {
values[0]=((float32)ILa_ADC-ILa_offset)*ILA_GAIN;
values[1]=((float32)ILb_ADC-ILb_offset)*ILB_GAIN;
values[2]=((float32)ILc_ADC-ILc_offset)*ILC_GAIN;
}
HccILa=values[0];HccILb=values[1];HccILc=values[2];
if(HccFaultReset != 0U) {
HccFaultReset=0U;
if(HccRunEnable == 0U && pwm_enabled == 0U) {HccFault=0U;HccFaultPhase=0U;HccFaultMask=0U;}
}
if(HccFault != 0U) return; /* keep the first fault and its snapshot */
if(!(alpha_pro>0.0f && alpha_pro<=1.0f &&
VBUS_OVER_TH > VBUS_START_TH && VBUS_START_TH > VBUS_OFF_TH &&
VA_OVER_TH>0.0f && VA_OVER_TH<1000.0f &&
VB_OVER_TH>0.0f && VB_OVER_TH<1000.0f &&
VC_OVER_TH>0.0f && VC_OVER_TH<1000.0f)) { HccTrip(1U); return; }
if(!(Vdc_Protection >= 0.0f && Vdc_Protection < 1000.0f &&
Vdc >= 0.0f && Vdc < 1000.0f &&
Vdc_pro >= 0.0f && Vdc_pro < 1000.0f)) { HccTrip(3U); return; }
mask=0U; invalid_phase=0U;
volts[0]=Va_Protection; volts[1]=Vb_Protection; volts[2]=Vc_Protection;
limits[0]=VA_OVER_TH; limits[1]=VB_OVER_TH; limits[2]=VC_OVER_TH;
for(i=0U;i<3U;i++) {
if(!(volts[i]>-1000.0f && volts[i]<1000.0f)) {
HccTripDetail(3U,(Uint16)(i+1U),0U); return;
}
if(volts[i]>=limits[i] || volts[i]<=-limits[i])
mask |= (Uint16)(HCC_MASK_OV_A << i);
}
if(VbusOvTrip != 0U) mask |= HCC_MASK_OV_DC;
if(pwm_enabled != 0U && Vdc_pro <= VBUS_OFF_TH) mask |= HCC_MASK_UV_DC;
/* Current coefficients are latched on start. Compute ALL three phases
* before selecting a primary fault, so the snapshot is never one ISR old. */
if(HccReady != 0U) {
raw[0]=ILa_ADC; raw[1]=ILb_ADC; raw[2]=ILc_ADC;
for(i=0U;i<3U;i++) {
if(raw[i]==0U || raw[i]>=4095U ||
!(values[i]>-1000.0f && values[i]<1000.0f)) {
if(invalid_phase==0U) invalid_phase=(Uint16)(i+1U);
} else if((HCC_SW_OVERCURRENT_ENABLE != 0U) &&
(values[i]>HCC_SAMPLE_TRIP_A || values[i]<-HCC_SAMPLE_TRIP_A)) {
mask |= (Uint16)(HCC_MASK_OC_A << i);
}
}
}
/* All physical conditions from this scan are preserved in Mask. */
if((mask & HCC_MASK_OV_DC)!=0U) { HccTripDetail(9U,0U,mask); return; }
for(i=0U;i<3U;i++) {
if((mask & (HCC_MASK_OC_A << i))!=0U) {
HccTripDetail((Uint16)(11U+i),(Uint16)(i+1U),mask); return;
}
}
for(i=0U;i<3U;i++) {
if((mask & (HCC_MASK_OV_A << i))!=0U) {
HccTripDetail((Uint16)(21U+i),(Uint16)(i+1U),mask); return;
}
}
if((mask & HCC_MASK_UV_DC)!=0U) { HccTripDetail(10U,0U,mask); return; }
if(invalid_phase!=0U) { HccTripDetail(3U,invalid_phase,0U); return; }
}
static void UpdatePowerStageOutput(void)
{
Uint16 i, high[3], low[3], upper_first[3];
float32 upper[3], lower[3];
if(HccFault != 0U || HccReady == 0U) return;
if(HccUpdateDelayTerms() == 0U) return;
/* Absolute bounds never depend on HccPhase[i].Iref, QPR or manual commands.
* With delay compensation, CMPSS thresholds move inward so the intended
* physical turn-around remains +5A/-5A after effective propagation delay.
*/
for(i=0U; i<3U; i++) {
upper[i] = HCC_FIXED_CURRENT_UPPER_A - HccDelayPhase[i].DeltaRiseA;
lower[i] = HCC_FIXED_CURRENT_LOWER_A + HccDelayPhase[i].DeltaFallA;
if(!HccBuildDelayWindow(upper[i], lower[i], hcc_delay_dac_k[i],
HccDacCal[i].ActiveZeroCodeH,
HccDacCal[i].ActiveZeroCodeL,
&high[i], &low[i])) {
HccTripDetail(2U, (Uint16)(i+1U), 0U);
return;
}
upper_first[i] = (upper[i] > HccDelayPhase[i].CmdUpperA) ? 1U : 0U;
}
for(i=0U; i<3U; i++) {
HccDelayPhase[i].CmdUpperA = upper[i];
HccDelayPhase[i].CmdLowerA = lower[i];
}
HccWriteWindow(&Cmpss6Regs, high[0], low[0], upper_first[0]);
HccWriteWindow(&Cmpss2Regs, high[1], low[1], upper_first[1]);
HccWriteWindow(&Cmpss1Regs, high[2], low[2], upper_first[2]);
}
/* Latch measured A-phase ADC calibration for this fixed-window control mode.
* Comparator voltage slope and high/low DAC zero codes remain independent. */
static Uint16 HccLatchIlaAdcCalibration(void)
{
if(!(ILa_offset>1.0f && ILa_offset<4094.0f &&
ILA_GAIN>-0.5f && ILA_GAIN<-0.0001f)) {
HccTripDetail(1U,1U,0U);
return 0U;
}
HccPhase[0].AdcZero=ILa_offset;
hcc_ila_gain_active=ILA_GAIN;
return 1U;
}
/* B-phase measured ADC calibration; independent of CMPSS/DAC conversion. */
static Uint16 HccLatchIlbAdcCalibration(void)
{
if(!(ILb_offset>1.0f && ILb_offset<4094.0f &&
ILB_GAIN>-0.5f && ILB_GAIN<-0.0001f)) {
HccTripDetail(1U,2U,0U);
return 0U;
}
HccPhase[1].AdcZero=ILb_offset;
hcc_ilb_gain_active=ILB_GAIN;
return 1U;
}
/* C-phase measured ADC calibration; independent of CMPSS/DAC conversion. */
static Uint16 HccLatchIlcAdcCalibration(void)
{
if(!(ILc_offset>1.0f && ILc_offset<4094.0f &&
ILC_GAIN>-0.5f && ILC_GAIN<-0.0001f)) {
HccTripDetail(1U,3U,0U);
return 0U;
}
HccPhase[2].AdcZero=ILc_offset;
hcc_ilc_gain_active=ILC_GAIN;
return 1U;
}
/* Derive CMPSS voltage slopes from the same latched ADC gains.
* HccBuildWindow multiplies by4096/Vdac; H/L zero codes remain independent. */
static void HccUpdateCmpSlopesFromAdc(void)
{
HccPhase[0].SlopeVperA=HCC_SLOPE_FROM_ADC(IL_ADCC_VREF_V,hcc_ila_gain_active);
HccPhase[1].SlopeVperA=HCC_SLOPE_FROM_ADC(IL_ADCA_VREF_V,hcc_ilb_gain_active);
HccPhase[2].SlopeVperA=HCC_SLOPE_FROM_ADC(IL_ADCA_VREF_V,hcc_ilc_gain_active);
}
static Uint16 HccLatchDelayConfig(void)
{
float32 rise, fall, max_factor, min_width, start_margin, codes_per_amp;
float32 fixed_rise_mv, fixed_fall_mv, slope_magnitude;
HCC_DELAY_PHASE *phase;
Uint16 i;
fixed_rise_mv = HccAAdvanceRiseMv;
fixed_fall_mv = HccAAdvanceFallMv;
if(HccDelayEnable > 1U ||
!(HccDelayInductanceUh > 1.0f && HccDelayInductanceUh < 10000.0f &&
HccDelayTdRiseUs >= 0.0f && HccDelayTdRiseUs <= 5.0f &&
HccDelayTdFallUs >= 0.0f && HccDelayTdFallUs <= 5.0f &&
hcc_vref > 2.5f && hcc_vref < 3.6f &&
HCC_DELAY_DESIGN_BUS_V > 0.0f && HCC_DELAY_DESIGN_BUS_V < 1000.0f)) {
HccTrip(1U);
return 0U;
}
if(!(fixed_rise_mv >= 0.0f && fixed_rise_mv <= 1000.0f &&
fixed_fall_mv >= 0.0f && fixed_fall_mv <= 1000.0f)) {
HccTripDetail(1U, 1U, 0U);
return 0U;
}
rise = 0.0f;
fall = 0.0f;
if(HccDelayEnable != 0U) {
rise = HccDelayTdRiseUs / HccDelayInductanceUh;
fall = HccDelayTdFallUs / HccDelayInductanceUh;
} else {
fixed_rise_mv = 0.0f;
fixed_fall_mv = 0.0f;
}
hcc_delay_rise_a_per_v = rise;
hcc_delay_fall_a_per_v = fall;
max_factor = (rise > fall) ? rise : fall;
for(i = 0U; i < 3U; i++) {
phase = &HccDelayPhase[i];
slope_magnitude = -HccPhase[i].ActiveSlope;
if(!(slope_magnitude > 0.0001f && slope_magnitude < 0.5f)) {
HccTripDetail(2U, (Uint16)(i + 1U), 0U);
return 0U;
}
phase->FixedRiseA = 0.0f;
phase->FixedFallA = 0.0f;
if(i == 0U) {
phase->FixedRiseA = fixed_rise_mv * 0.001f / slope_magnitude;
phase->FixedFallA = fixed_fall_mv * 0.001f / slope_magnitude;
}
hcc_delay_dac_k[i] = -4096.0f * slope_magnitude / hcc_vref;
codes_per_amp = -hcc_delay_dac_k[i];
start_margin = 2.0f / codes_per_amp;
/* At the design bus voltage, check the narrowest command window
* and retain at least two DAC codes of margin from zero on each side. */
min_width = HCC_FIXED_CURRENT_WIDTH_A - HCC_DELAY_DESIGN_BUS_V * max_factor
- phase->FixedRiseA - phase->FixedFallA;
if(!(min_width >= HCC_DELAY_MIN_CMD_WIDTH_A &&
HCC_FIXED_CURRENT_UPPER_A - HCC_DELAY_DESIGN_BUS_V * rise
- phase->FixedRiseA > start_margin &&
-HCC_FIXED_CURRENT_LOWER_A - HCC_DELAY_DESIGN_BUS_V * fall
- phase->FixedFallA > start_margin &&
HCC_FIXED_CURRENT_UPPER_A < HCC_SAMPLE_TRIP_A &&
HCC_FIXED_CURRENT_LOWER_A > -HCC_SAMPLE_TRIP_A)) {
HccTripDetail(2U, (Uint16)(i + 1U), 0U);
return 0U;
}
}
return 1U;
}
static Uint16 HccUpdateDelayTerms(void)
{
float32 bus,vo[3],v,delta,width;
Uint16 i;
bus=Vdc_Protection;
vo[0]=Va_Protection;vo[1]=Vb_Protection;vo[2]=Vc_Protection;
if(!(bus>0.0f && bus<1000.0f)) {HccTrip(3U);return 0U;}
for(i=0U;i<3U;i++) {
v=vo[i];
if(!(v>-1000.0f && v<1000.0f)) {
HccTripDetail(3U,(Uint16)(i+1U),0U);return 0U;
}
if(v<0.0f) {v=0.0f;}
if(v>bus) {v=bus;}
HccDelayPhase[i].DeltaRiseA = (bus-v)*hcc_delay_rise_a_per_v
+ HccDelayPhase[i].FixedRiseA;
HccDelayPhase[i].DeltaFallA = v*hcc_delay_fall_a_per_v
+ HccDelayPhase[i].FixedFallA;
delta=HccDelayPhase[i].DeltaRiseA+HccDelayPhase[i].DeltaFallA;
width=HCC_FIXED_CURRENT_WIDTH_A-delta;
if(!(width>=HCC_DELAY_MIN_CMD_WIDTH_A)) {
HccTripDetail(2U,(Uint16)(i+1U),0U);return 0U;
}
}
return 1U;
}
static Uint16 HccPrepareStart(void)
{
Uint16 i, hi, lo;
/* Do not allow the power stage to start before the measured bus reaches
* 400V. Manual HccRunEnable remains an independent safety interlock.
*/
if(!(Vdc_pro>=VBUS_START_TH && Vdc_pro<VBUS_OVER_TH)) return 0U;
if(HccLatchIlaAdcCalibration()==0U ||
HccLatchIlbAdcCalibration()==0U ||
HccLatchIlcAdcCalibration()==0U) return 0U;
HccUpdateCmpSlopesFromAdc();
hcc_vref=HccDacVref;
for(i=0U; i<3U; i++) {
HccDacCal[i].ActiveZeroCodeH=HccDacCal[i].ZeroCodeH;
HccDacCal[i].ActiveZeroCodeL=HccDacCal[i].ZeroCodeL;
HccPhase[i].ActiveSlope=HccPhase[i].SlopeVperA;
HccPhase[i].ActiveAdcZero=HccPhase[i].AdcZero;
HccPhase[i].Iref=0.0f; /* diagnostic compatibility only */
}
if(HccLatchDelayConfig()==0U) return 0U;
/* Only the absolute +/-5A window needs DAC range verification.
* There are no +/-20A Iref extrema in this fixed-window program.
*/
for(i=0U; i<3U; i++) {
if(!HccBuildDelayWindow(HCC_FIXED_CURRENT_UPPER_A,
HCC_FIXED_CURRENT_LOWER_A,
hcc_delay_dac_k[i],
HccDacCal[i].ActiveZeroCodeH,
HccDacCal[i].ActiveZeroCodeL,
&hi, &lo)) {
HccTripDetail(2U,(Uint16)(i+1U),0U);
return 0U;
}
}
HccReady=1U;
HccService();
if(HccFault!=0U) return 0U;
UpdatePowerStageOutput();
if(HccFault!=0U) return 0U;
DELAY_US(2);
return (HccFault==0U && HccReady!=0U)?1U:0U;
}
static void HccSeed(volatile struct EPWM_REGS *pwm, volatile struct CMPSS_REGS *cmp)
{
Uint16 action;
/* Negative sensor slope, unchanged from the running HCC mapping:
* COMPLSTS is the explicitly initialized one-sample monitor; DAC values
* have settled for 2us before this startup-only read. The running loop
* and GPIO markers continue using the independent RAW ASYNC path.
* COMPLSTS=0 -> i >= Upper -> seed A low (falling-current state).
* COMPLSTS=1 -> in band or below Lower -> seed A high to establish current.
* In particular i=0 MUST start A high; waiting for a threshold with A low
* and an unenergized inductor can leave the hardware loop stalled forever.
* A high/B low assumes the uploaded power-stage polarity (A raises i).
* B remains derived from A by DB; never force complementary gates high.
*/
action=(cmp->COMPSTS.bit.COMPLSTS==0U)?AQ_CLEAR:AQ_SET;
pwm->AQSFRC.bit.RLDCSF=3U;
pwm->AQCSFRC.bit.CSFA=0U;
pwm->AQCSFRC.bit.CSFB=0U;
pwm->AQSFRC.bit.ACTSFA=action;
pwm->AQSFRC.bit.OTSFA=1U;
}
Below are our experimental waveforms and relevant CMPSS configurations.
