重写该代码用定时器2实现
时间: 2024-02-18 11:01:08 浏览: 30
好的,下面是使用定时器2实现的代码:
```
#include <reg52.h>
#define FREQ_SYS 11059200UL
sbit LED = P1^0;
int duty_cycle = 10;
void timer2_init(){
T2CON = 0x00; //设置定时器2为模式0,不使用预分频器
RCAP2H = 0xFF; //设置重载值为65535
RCAP2L = 0xFF;
ET2 = 1; //启用定时器2中断
EA = 1; //启用全局中断
TR2 = 1; //启动定时器2
}
void pwm_init(){
PWMCFG = 0x00; // PWM时钟源SYSCLK
PWMCON = 0x3F; // 使能PWM输出到对应IO口
PWMDTYA = 0x02; // PWM占空比10%,对应PWM0
PWMPRD = 0xFF; // PWM周期65536
PWMCON |= 0x80; // 启动PWM模块
}
void timer2_handler() interrupt 5{
TF2 = 0; //清除中断标志位
if(duty_cycle <= 10 || duty_cycle >= 100) // 达到上限或下限反向渐变
duty_cycle += (duty_cycle >= 100) ? -1 : 1;
else
duty_cycle += 10; // 渐变增加
PWMDTY0 = (unsigned int)(255 - 255 * duty_cycle / 100); // 更新PWM占空比
}
void main(){
timer2_init(); // 初始化计时器2
pwm_init(); // 初始化PWM模块
while(1){
// do nothing
}
}
```
在使用定时器2实现时,需要注意以下几点:
1. 定时器2的中断向量号为5,需要使用`interrupt 5`来声明中断处理函数。
2. 定时器2的重载值需要设置为65535,否则无法达到与定时器0相同的计时时间。
3. 在中断处理函数中,需要清除中断标志位`TF2`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)