pwm三闭环dsp代码
时间: 2023-08-24 22:08:35 浏览: 70
以下是一个基于TMS320F28335 DSP的三闭环PWM控制器的代码示例:
```c
#include "DSP2833x_Device.h"
#include "DSP2833x_Examples.h"
#define PWM_FREQ 20000
#define PWM_PERIOD (150MHz / (2 * PWM_FREQ))
// 三闭环控制器参数
#define KP 0.5
#define KI 0.1
#define KD 0.05
// 三闭环控制器状态
float error = 0;
float integral = 0;
float derivative = 0;
float prev_error = 0;
float setpoint = 0;
float feedback = 0;
float duty_cycle = 0;
// 初始化PWM模块
void init_pwm() {
EALLOW;
SysCtrlRegs.PCLKCR0.bit.TBCLKSYNC = 0;
EDIS;
EPwm1Regs.TBCTL.bit.CTRMODE = TB_COUNT_UPDOWN;
EPwm1Regs.TBCTL.bit.PHSEN = TB_DISABLE;
EPwm1Regs.TBCTL.bit.PRDLD = TB_SHADOW;
EPwm1Regs.TBPRD = PWM_PERIOD;
EPwm1Regs.TBCTR = 0;
EPwm1Regs.CMPCTL.bit.SHDWAMODE = CC_SHADOW;
EPwm1Regs.CMPCTL.bit.SHDWBMODE = CC_SHADOW;
EPwm1Regs.CMPCTL.bit.LOADAMODE = CC_CTR_ZERO;
EPwm1Regs.CMPCTL.bit.LOADBMODE = CC_CTR_ZERO;
EPwm1Regs.AQCTLA.bit.CAU = AQ_SET;
EPwm1Regs.AQCTLA.bit.CAD = AQ_CLEAR;
EPwm1Regs.AQCTLB.bit.ZRO = AQ_SET;
EPwm1Regs.AQCTLB.bit.PRD = AQ_CLEAR;
EALLOW;
SysCtrlRegs.PCLKCR0.bit.TBCLKSYNC = 1;
EDIS;
}
// 初始化ADC模块
void init_adc() {
EALLOW;
AdcRegs.ADCCTL1.bit.ADCBGPWD = 1;
AdcRegs.ADCCTL1.bit.ADCREFSEL = 0;
AdcRegs.ADCCTL1.bit.ADCREFPWD = 1;
AdcRegs.ADCCTL1.bit.ADCPWDN = 1;
AdcRegs.ADCCTL1.bit.ADCENABLE = 1;
EDIS;
AdcRegs.ADCSOC0CTL.bit.CHSEL = 0;
AdcRegs.ADCSOC0CTL.bit.ACQPS = 6;
AdcRegs.ADCSOC0CTL.bit.TRIGSEL = 5;
}
// 读取反馈信号
float read_feedback() {
AdcRegs.ADCSOCFRC1.bit.SOC0 = 1;
while (AdcRegs.ADCINTFLG.bit.ADCINT1 == 0);
AdcRegs.ADCINTFLGCLR.bit.ADCINT1 = 1;
return AdcRegs.ADCRESULT0 * 3.3 / 4096;
}
// 计算PWM占空比
void calculate_duty_cycle() {
error = setpoint - feedback;
integral += error;
derivative = error - prev_error;
duty_cycle = KP * error + KI * integral + KD * derivative;
prev_error = error;
}
// 更新PWM输出
void update_pwm() {
if (duty_cycle < 0) {
duty_cycle = 0;
} else if (duty_cycle > 1) {
duty_cycle = 1;
}
EPwm1Regs.CMPA.half.CMPA = PWM_PERIOD * duty_cycle;
}
// 主循环
void main() {
init_pwm();
init_adc();
while (1) {
feedback = read_feedback();
calculate_duty_cycle();
update_pwm();
}
}
```
上面的代码实现了一个三闭环PWM控制器,主要包括PWM模块初始化、ADC模块初始化、读取反馈信号、计算PWM占空比和更新PWM输出等功能。其中,PID参数KP、KI和KD可以根据具体应用进行调整,setpoint表示期望输出电压,feedback表示实际输出电压,duty_cycle表示PWM占空比。在主循环中,不断读取反馈信号,计算PWM占空比,并更新PWM输出,从而实现闭环控制。
阅读全文