试试看这段代码
//例13-6: 设置输出比较模块工作在PWM 模式下
// Initialize Output Compare Module
OC1CONbits.OCM = 0b000; // Disable Output Compare Module
OC1R = 100; // Write the duty cycle for the first PWM pulse
OC1RS = 200; // Write the duty cycle for the second PWM pulse
OC1CONbits.OCTSEL = 0; // Select Timer 2 as output compare time base
OC1R = 100; // Load the Compare Register Value
OC1CONbits.OCM = 0b110; // Select the Output Compare mode
// Initialize and enable Timer2
T2CONbits.TON = 0; // Disable Timer
T2CONbits.TCS = 0; // Select internal instruction cycle clock
T2CONbits.TGATE = 0; // Disable Gated Timer mode
T2CONbits.TCKPS = 0b00; // Select 1:1 Prescaler
TMR2 = 0x00; // Clear timer register
PR2 = 500; // Load the period value
IPC1bits.T2IP = 0x01; // Set Timer 2 Interrupt Priority Level
IFS0bits.T2IF = 0; // Clear Timer 2 Interrupt Flag
IEC0bits.T2IE = 1; // Enable Timer 2 interrupt
T2CONbits.TON = 1; // Start Timer
/* Example code for Timer 2 ISR*/
void __attribute__((__interrupt__, no_auto_psv)) _T2Interrupt( void )
{
/* Interrupt Service Routine code goes here */
OC1RS = 300; // Write Duty Cycle value for next PWM cycle
IFS0bits.T2IF = 0; // Clear Timer 2 interrupt flag
}
|