使用TMS320F2812的捕获单元测量外部输入方波的频率的代码
时间: 2024-02-21 19:01:07 浏览: 133
下面是使用TMS320F2812的捕获单元测量外部输入方波的频率的代码示例:
```c
#include "DSP281x_Device.h"
#include "DSP281x_Examples.h"
#define EPWM_TIMER_TBPRD 7500 // EPWM 周期
void InitEPwm(void);
void InitECap(void);
interrupt void ecap1_isr(void);
Uint32 cap1 = 0;
Uint32 cap2 = 0;
Uint32 cap3 = 0;
Uint32 freq = 0;
void main(void)
{
InitSysCtrl();
DINT;
InitPieCtrl();
IER = 0x0000;
IFR = 0x0000;
InitPieVectTable();
EALLOW;
PieVectTable.ECAP1_INT = &ecap1_isr;
EDIS;
InitEPwm();
InitECap();
IER |= M_INT3;
PieCtrlRegs.PIEIER3.bit.INTx1 = 1;
EINT;
ERTM;
while(1)
{
freq = 75000000 / (cap2 - cap1);
}
}
void InitEPwm(void)
{
EPwm1Regs.TBCTL.bit.CTRMODE = TB_FREEZE;
EPwm1Regs.TBPRD = EPWM_TIMER_TBPRD;
EPwm1Regs.TBCTL.bit.CTRMODE = TB_COUNT_UP;
}
void InitECap(void)
{
ECap1Regs.ECEINT.all = 0x0000;
ECap1Regs.ECCTL1.bit.CAPLDEN = 1;
ECap1Regs.ECCTL2.bit.TSCTRSTOP = 0;
ECap1Regs.ECCTL2.bit.CONT_ONESHT = 0;
ECap1Regs.ECCTL1.bit.CAP1POL = 1;
ECap1Regs.ECCTL1.bit.CAP2POL = 1;
ECap1Regs.ECCTL1.bit.CAP3POL = 1;
ECap1Regs.ECCTL1.bit.CAP4POL = 1;
ECap1Regs.ECCTL1.bit.CTRRST1 = 1;
ECap1Regs.ECCTL1.bit.CTRRST2 = 1;
ECap1Regs.ECCTL1.bit.CTRRST3 = 1;
ECap1Regs.ECCTL1.bit.CTRRST4 = 1;
ECap1Regs.ECCTL2.bit.SYNCI_EN = 1;
ECap1Regs.ECCTL2.bit.SYNCO_SEL = 0;
ECap1Regs.ECCTL2.bit.SYNCO_EN = 0;
ECap1Regs.ECCTL2.bit.TSCTRSTOP = 0;
}
interrupt void ecap1_isr(void)
{
if (ECap1Regs.ECFLG.bit.CEVT1)
{
cap1 = ECap1Regs.CAP1;
ECap1Regs.ECCLR.bit.CEVT1 = 1;
}
if (ECap1Regs.ECFLG.bit.CEVT2)
{
cap2 = ECap1Regs.CAP2;
ECap1Regs.ECCLR.bit.CEVT2 = 1;
}
if (ECap1Regs.ECFLG.bit.CEVT3)
{
cap3 = ECap1Regs.CAP3;
ECap1Regs.ECCLR.bit.CEVT3 = 1;
}
PieCtrlRegs.PIEACK.all = PIEACK_GROUP3;
}
```
在这个代码示例中,我们使用TMS320F2812的EPwm1模块来生成一个周期为7500的方波,使用ECap1模块来测量外部输入方波的频率。在初始化ECap1模块时,我们将ECap1Regs.ECEINT.all设置为0,即不开启任何中断;将ECap1Regs.ECCTL1和ECap1Regs.ECCTL2中的寄存器位设置为相应的值以便正确地测量输入方波的频率。在捕获到每个上升沿时,我们通过判断ECap1Regs.ECFLG.bit.CEVT1、ECap1Regs.ECFLG.bit.CEVT2和ECap1Regs.ECFLG.bit.CEVT3是否被置位来分别获取每个上升沿的计数值,然后将相应的寄存器位清零,以便下一次捕获。最后,在ecap1_isr中使用PieCtrlRegs.PIEACK.all = PIEACK_GROUP3来清除中断标志。在while循环中,我们计算输入方波的频率,并将结果存储在变量freq中。
阅读全文