中断比我们之前写的(不断查询)要好的多。
可以实行并行工作
中断源
默认中断级别
EA 总中断允许位
ET 定时器
EX 外部中断
ES 串口中断
练习
- 使用定时器中断
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
uint count;
void init()
{
TMOD = 0x01; //定时器0工作模式1
ET0 = 1;
TH0 = 0x4b;
TL0 = 0xfd;
EA = 1;
TR0 = 1;
}
int main()
{
init();
while(1)
{
}
return 0;
}
void T0_time() interrupt 1
{ TH0 = 0x4b;
TL0 = 0xfd;
count++;
if(count==20)
{
P1 = ~P1;
count=0;
}
}
-
练习二
#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit we = P2^7;
sbit du = P2^6;
uchar count0=0,count1;//全局变量 存储定时器加一计数器溢出次数
uchar temp0,temp1 = 0x7f; //temp0负责数码管的值,temp1负责流水灯的值
uchar code leddata[]={
0x3F, //"0"
0x06, //"1"
0x5B, //"2"
0x4F, //"3"
0x66, //"4"
0x6D, //"5"
0x7D, //"6"
0x07, //"7"
0x7F, //"8"
0x6F, //"9"
0x77, //"A"
0x7C, //"B"
0x39, //"C"
0x5E, //"D"
0x79, //"E"
0x71, //"F"
0x76, //"H"
0x38, //"L"
0x37, //"n"
0x3E, //"u"
0x73, //"P"
0x5C, //"o"
0x40, //"-"
0x00, //熄灭
0x00 //自定义
};
void delay(uint z) //1MS延时
{
uint x,y;
for(x = z; x > 0; x--)
for(y = 114; y > 0 ; y--);
}
void display(uchar i) //数码管显示函数
{
uchar shi,ge;
shi = i / 10; //求模
ge = i % 10; //求余
P0 = 0xff; //清除段码
we = 1;
P0 = 0xfe; //点亮第一位数码管
we = 0;
du = 1;
P0 = leddata[shi];
du = 0;
delay(1);
P0 = 0xff; //清除段码
we = 1;
P0 = 0xfd; //点亮第二位数码管
we = 0;
du = 1;
P0 = leddata[ge];
du = 0;
delay(1);
}
/*中断服务特殊功能寄存器配置*/
void init()
{
TMOD = 0x11; //定时器T1/T0 16为计数工作模式
TH1 = TH0 = 0x4b;
TL1 = TL0 = 0xfd; //T1/T0 定时50ms
ET1 = ET0 = 1; //开T1/T0中断
TR1 = TR0 = 1; //启动T1/T0
EX0 = 1; //开外部中断0
IT0 = 0; //外部中断0为低电平触发
EA = 1; //开总中断
}
void main()
{
init(); //调用配置函数
while(1)
{
display(temp0);//数码管显示
}
}
void int0() interrupt 0 //外部中断0,中断服务程序
{
TR0 = 0; //关闭定时器0
}
/*定时器0中断服务程序*/
void timer0() interrupt 1 //T0内部查询顺序1
{
TH0 = 0x4b;
TL0 = 0xfd; //定时器0再次放初值 50ms
count0++;
if (count0 == 20)
{
count0 = 0;
temp0++;
if (temp0 > 60)
{
temp0 = 0;
}
}
}
/*定时器1中断服务程序*/
void timer1() interrupt 3 //T1内部查询顺序3
{
TH1 = 0x4b;
TL1 = 0xfd; //定时器1再次放初值 50ms
count1++;
if (count1 == 10)
{
count1 = 0;
P1 = temp1;
temp1 = _cror_(temp1,1);//循环右移一次
}
}