我想弄一个SPWM的波,但是现在duty随周期在变,不知道PWM输出后还要加什么东西滤波或者怎么样,直接加个电容连接一个电阻看到的波很不理想也不是正弦波,这个是面积等效法作的50HZ的实验。PTPER中256个数是1微秒。所用调试环境MPLAB ICD2 v8.10 编译器是C30,外部有4M的晶振,再有就是PTPER时间怎么算,希望各位不吝赐教,程序如下:
#include <stdio.h> #include <p30f2020.h> #include <math.h> #define PI 3.141592
_FOSC(CSW_FSCM_OFF & HS) //HS振荡器,禁止时钟切换
_FWDT(FWDTEN_OFF); //禁止看门狗定时器 //_FBORPOR(PBOR_OFF & MCLR_EN); //禁止掉电复位,使能MCLR复位 _FGS(CODE_PROT_OFF);
int N,f=20; double Pul;
int BUFcos[98]={5,5,24,35,44,54,64,73,86,93,101,111,120,130,138,147,156,164, 172,181,188,197,204,211,219,226,232,239,245,251,257,263,268,272,278,282,287, 290,294,297,300,303,306,308,309,311,312,313,314,314,313,312,311,309,308,306, 303,300,297,294,290,287,282,278,272,268,263,257,251,245,239,232,226,219,211, 204,197,188,181,172,164,156,147,138,130,120,111,101,93,86,73,64,54,44,35,24, 5,5}, BUFcos1[64]={12,36,60,84,108,131,154,176,199,221,242,262,283,302,320,340 ,355,372,387,401,415,427,438,449,458,466,473,479,484,487,489,491 ,491,489,487,484,479,473,466,458,449,438,427,415,401,387,372,355 ,340,320,302,283,262,242,221,199,176,154,131,108,84,60,36,12};
void Delay(int x) { //延时程序 while(x--); }
void SCAN() { int i; //键盘扫描程序 // k=0; //double M=1.0,w=2*PI*f;
PORTB=0x03;
if(PORTB!=0x03) { for(i=0;i<10;i++) { Delay(25600); }
if(PORTBbits.RB0==0) //S2定义为增
{ f=f+20; if(f>=300) { f=20; }
}
else if(PORTBbits.RB1==0) //S3定义为减 { f=f-20; if(f<=20) { f=300; } } } }
void Pulse_Width(void) {
int k=0; double M=1.0,w=2*PI*f;
for(k=10;k<90;k++) { PTPER=25700;
/*~~~~~~ Load PDC1 register with initial Duty Cycle value ~~~~~~~~~~*/
//Pul=(M/w)*(cos((k-1)*PI/N)-cos(k*PI/N)); PDC1=Pul*256*1000000; //PDC1=(0.3183*BUFcos1[k]*256); Delay(25600); }
} void Pulse_Config() { TRISE=0x00; FCLCON1=0X0003; /*~~~~~~~~~~~~~~~~~~~~~~~ PWM1 Configuration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* PWM1 I/O Control Register register / IOCON1bits.PENH = 1; /* PWM1H is controlled by PWM module */ IOCON1bits.PENL = 1; /* PWM1L is co*ntrolled by PWM module */ IOCON1bits.PMOD = 0; /* Select Independent Output PWM mode */ IOCON1bits.POLH = 0;
/* Load PDTR1 and ALTDTR2 register with preset dead time value */ DTR1 = 64; /* Deadtime setting */ ALTDTR1 = 64; /* Deadtime setting */
/* PHASE1 register */ PHASE1 = 0; /* No phase shift */
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/* Configure PTPER register to produce ??kHz PWM frequency */ // PTPER = 0x4e20; /* PWM Period @30 MIPS, 2.5usec?? == 400kHz?? */
/* PWM Time Base Control Register */ PTCONbits.PTEN = 1; // Enable the PWM Module PTCONbits.EIPU = 1; //立即更新有效周期寄存器 PWMCON1bits.IUE = 1; //立即对有效的pdc寄存器进行更新
}
int main(void) {
N=100,f=50; Pul=0; T2CON=0X8000; ADPCFG=0xffff; TRISB=0x0003; PORTB=0x00; Pulse_Config();
while(1) { //SCAN(); Pulse_Width(); }
}
|
|