单片机程序优化:中断服务程序精简
单片机程序优化:中断服务程序精简
原程序
#include<reg52.h>
unsigned char cnt=0; //用于中断次数计数
unsigned char led =0xfe; //初始化流水灯
int main(void)
{
TMOD=0x01; //16位定时方式
TH0=(65536-46083)/256; //初始化T0的高8位
TL0=(65536-46083)%256; //初始化T0的低8位
EA=1;
ET0=1; //开中断
TR0=1; //启动T0工作
while(1);
}
void T0_int(void) interrupt 1
{
cnt++;
if( cnt==10 ) //0.5秒钟的时间到了
{
cnt=0; //清除次数统计
led =(led <<1)|1; //更新流水灯数据
if(led ==0xff)
{
led =0xfe;
}
P0=led; //显示流水灯
}
TH0=(65536-46083)/256; //初始化T0的高8位
TL0=(65536-46083)%256; //初始化T0的低8位
}
改造后的程序
#include <reg52.h>
unsigned char led = 0xfe; // 初始化流水灯
void delay(unsigned int time) // 延时函数
{
unsigned int i, j;
for(i = time; i > 0; i--)
for(j = 110; j > 0; j--);
}
void main(void)
{
TMOD = 0x01; // 16位定时方式
TH0 = (65536 - 46083) / 256; // 初始化T0的高8位
TL0 = (65536 - 46083) % 256; // 初始化T0的低8位
EA = 1;
ET0 = 1; // 开中断
TR0 = 1; // 启动T0工作
while(1);
}
void T0_int(void) interrupt 1
{
static unsigned char cnt = 0; // 用于中断次数计数
cnt++;
if(cnt == 10) // 0.5秒钟的时间到了
{
cnt = 0; // 清除次数统计
led = (led << 1) | 1; // 更新流水灯数据
if(led == 0xff)
led = 0xfe;
P0 = led; // 显示流水灯
}
TH0 = (65536 - 46083) / 256; // 初始化T0的高8位
TL0 = (65536 - 46083) % 256; // 初始化T0的低8位
}
改造说明
- 将中断次数计数变量
cnt定义为静态变量,这样每次中断时都会使用上一次中断时的值。这样,我们无需在中断服务程序中对cnt进行清零操作。 - 移除延时函数
delay,直接在中断服务程序中使用TH0和TL0进行延时。
调试结果

总结
通过将中断次数计数变量定义为静态变量,并移除延时函数,我们成功简化了中断服务程序,提高了程序效率。同时,程序调试结果表明,优化后的程序能够正常工作,并且能够实现预期的功能。
原文地址: https://www.cveoy.top/t/topic/pk4g 著作权归作者所有。请勿转载和采集!