| 本帖最后由 740071911 于 2021-7-4 09:25 编辑 
 实现pwm呼吸灯效果
 1、pwm功能添加,打开mcc,根据如下配置,设置pwm输出到RC1引脚。
 
 
 
 2、代码编写。
 
 因为pwm为12bit,所以每1ms增加1,到0~4095时间太长,观察效果不好,
 改为1ms ,PWM占空比增加2,这样往复循环,4s左右的呼吸灯。
 
 pwm函数介绍
 
 PWM1_16BIT_SetSlice1Output1DutyCycleRegister();//设置占空比
 定时器中断函数
 void TMR0_DefaultInterruptHandler(void){
    // add your TMR0 interrupt custom code
    // or set custom function using TMR0_SetInterruptHandler()
   
    static unsigned short int tmr_cnt = 0;
    static unsigned short int pwm_duty = 0;
    static unsigned char dir = 0;
   
    // clear the TMR0 interrupt flag
    PIR3bits.TMR0IF = 0;
    // Write to the Timer0 register
    TMR0H = timer0ReloadVal16bit >> 8;
    TMR0L = (uint8_t) timer0ReloadVal16bit;
   
    if (dir == 0)  //increase duty
    {
        pwm_duty+=2;
        if (pwm_duty >= 4095)
        {
             pwm_duty =4095;
             dir = 1;
        }
    }
    else          //decrease duty
    {
        pwm_duty -=2;
        if (pwm_duty > 60000)
        {
            pwm_duty = 0;
            dir = 0;
        }
     }
     PWM1_16BIT_SetSlice1Output1DutyCycleRegister(pwm_duty);
     PWM1_16BIT_LoadBufferRegisters();//使能占空比修改
     if(++tmr_cnt >= 1000)
     {
          tmr_cnt = 0;
          flag_1s = 1;
          //IO_RC1_Toggle();
     }
}
 3、完整代码
 
 
 
 |