今天我们来试下PIC16F15244的PWM功能,我们把PWM输出引脚关联到板载的LED上,让它来控制LED灯光强弱的变化。
好了,我们新建工程,打开MCC,配置PWM,我们使用TIMER2的PWM3:
我们这里配置PWM的频率为1KHz,占空比开始为0,然后10%递加,到达100%后,再10%的递减,到达0后,在次循环。
点击生成代码,
代码上初始的测试时50%的占空比的,我们用示波器看下PA2即LED的输出引脚,看下波形输出:
波形完全正常。
我们需要做的就是main函数的while循环里,每隔一段时间改变一下PWM的占空比duty值:
- void main(void)
- {
- volatile uint16_t pwmduty=0;//占空比
- volatile uint8_t pwmdir=0; //方向
- // initialize the device
- SYSTEM_Initialize();
- // When using interrupts, you need to set the Global and Peripheral Interrupt Enable bits
- // Use the following macros to:
- // Enable the Global Interrupts
- INTERRUPT_GlobalInterruptEnable();
- // Enable the Peripheral Interrupts
- INTERRUPT_PeripheralInterruptEnable();
- // Disable the Global Interrupts
- //INTERRUPT_GlobalInterruptDisable();
- // Disable the Peripheral Interrupts
- //INTERRUPT_PeripheralInterruptDisable();
-
-
- while (1)
- {
- // Add your application code
- //LED_Toggle();
- //printf("Hello world!\r\n");
- //delay_ms(500);
-
- //LED_Toggle();
-
- PWM3_LoadDutyValue(pwmduty);
- printf("now pwm duty is %d!\r\n",pwmduty);
- // __delay_ms(500);
- delay_ms(1000);
-
- if(pwmdir==0)
- {
- pwmduty=pwmduty+100;
- if(pwmduty>=1000)
- {
- pwmdir=1;//切换方向
- pwmduty=500;
- }
- }
- else
- {
- pwmduty=pwmduty-100;
- if(pwmduty<=10)
- {
- pwmdir=0;//切换方向
- pwmduty=0;
- }
- }
-
- }
- }
代码还是比较简单的,用MCC配置,真的省了不少事情啊~
看下LED的波形和亮度变化图片:
除此之外还开了TIMER0 500ms的中断,和TIMER2 300MS的中断,完全能够正常运行:
好了,PWM就到这~
|