中颖单片机 定时器2程序
时间: 2023-07-15 15:13:56 浏览: 75
以下是中颖单片机定时器2程序的示例代码:
```c
#include <reg52.h>
typedef unsigned int uint16_t;
typedef unsigned char uint8_t;
sbit LED = P1^0; // 控制LED的引脚
void Timer2Init(uint16_t ms); // 定时器2初始化函数声明
void main() {
Timer2Init(1); // 初始化定时器2,1ms中断一次
while(1) {
// 这里可以写其他的代码
}
}
void Timer2Init(uint16_t ms) {
uint16_t temp;
EA = 1; // 总中断使能
ET2 = 1; // 定时器2中断使能
temp = 11059200 / 12; // 定时器2计数器每秒钟的计数次数
temp = (uint16_t)(temp * ms / 1000); // 计算定时器2需要重载的值
RCAP2H = (uint8_t)(temp >> 8); // 定时器2重载值高字节
RCAP2L = (uint8_t)(temp & 0xFF); // 定时器2重载值低字节
T2CON = 0x04; // 定时器2工作在定时模式,使用内部时钟,计数器不清零
TR2 = 1; // 启动定时器2
}
void Timer2ISR() interrupt 5 {
static uint8_t cnt = 0;
TH2 = 0xFE; // 定时器2初始值高字节
TL2 = 0x4C; // 定时器2初始值低字节
cnt++;
if(cnt >= 500) { // 500ms
cnt = 0;
LED = ~LED; // 反转LED
}
}
```
这个程序实现了定时器2每1ms中断一次,并在中断服务程序中控制LED每500ms反转一次。你可以根据自己的需要修改定时器的中断周期和中断服务程序的具体实现。