PWM正弦波发生器:
#include
void PWM1(void){ #define FOSC 8000000.0 //系统时间频率8M, #define DIV 1.0 //timer2预分频 //#define DIV 4.0 //timer2预分频 //#define DIV 16.0 //timer2预分频 #define FPWM 20000.0 //PWM频率 20k(spwm) #define PWM_PERIOD 1000000.0/FPWM //PWM周期 50us #define TOSC 1000000.0/(FOSC) //机器周期 0.125US //4TOSC = 0.125US*4 = 0.5us #define PR2_LOADER (PWM_PERIOD-(4*TOSC*DIV)) / (4*TOSC*DIV) RB3 = 0; TRISB3 = 0; RB5 = 0; TRISB5 = 0; CCPTMRS = 0; CCP1CON = 0x8c; CCP1CON &= ~(0x03<<4); CCPR1L=0x00; TMR2 = 0; T2CON = 0x00;//预分频1:1 PR2 = 99; PWM1CON = 0x02;//死区时间1us (FOSC/4(4 * TOSC)) TMR2IF = 0; //Timer2 与PR2 匹配中断标志位 TMR2IE = 1; // TMR2 与PR2 匹配中断允许位 T2CON |= (1<<2)|(0x02<<3); }
void main(){ for (i=0; i<255; i++); PWM1(); INTCONbits.GIE = 1; INTCONbits.PEIE = 1; TRISBbits.TRISB0 = 0; PORTBbits.RB0 = 0; while(1) { }}void interrupt isr(void){ static unsigned char index; unsigned int reference; if (TMR2IE && TMR2IF) { TMR2IF = 0; PORTBbits.RB0 = !PORTBbits.RB0; reference = pwmtab[index]; CCPR1L = (reference>>2)&0xff; //CCP1CON &= ~(0x03<<4); //CCP1CON |= ((reference&0xff)<<4); if (++index > 66*2) { index = 0; } }}
看了N天理论,不如动手一试!
呵呵, 结果!