外部中断
下降沿触发
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
#define segN 4
uchar code segD[] = {
0x3f,0x06,0x5b,0x4f,0x66,
0x6d,0x7d,0x07,0x7f,0x6f,
0x00,0xf3};
uchar code segW[] = {
0xf7,0xfb,0xfd,0xfe
};
uchar num[segN];
uint a=807;
void delay(uint timer)
{
uchar j = 124;
while(timer--)
{
while(j--);
}
}
void display(uint k)
{
uchar i;
for(i=0; i<segN; i++)
{
int result=1;
num[segN-i-1]=k/result%10;
result*=10;
k/=10;
P2 = segW[i];
P0 = segD[num[segN-i-1]];
delay(1);
}
}
void exit_init()
{
EA=1;
IT0=1;//下降沿触发
IT1=1;
EX0=1;
EX1=1;
}
void main()
{
exit_init();
while(1)
{
display(a);
}
}
void int0_inter() interrupt 0
{
a++;
}
void int1_inter() interrupt 2
{
a=0;
}
低电平触发
void exit_init()
{
EA=1;
IT0=0;//低电平触发
IT1=1;
EX0=1;
EX1=1;
}
定时器
工作方式0
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit led = P2^0;
uchar num;
void int0_inter() interrupt 0
{
num=0;
TL0=0x18;
TH0=0X63;
TR0=1;
}
void int1_inter() interrupt 2
{
TR0=0;
}
void timer0_inter() interrupt 1
{
num++;
TL0=0x18;
TH0=0x63;
}
void exit_init()
{
IT0=1;
IT1=1;
EX0=1;
EX1=1;
TMOD=0;
TL0=0x18;
TH0=0X63;
ET0=1;
EA=1;
}
void main()
{
exit_init();
num=0;
P2=0xff;
while(1)
{
if(num>=200)
{
num=0;
led=~led;
}
}
}
工作方式1
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit out_pin = P2^0;
void timer0_inter() interrupt 1
{
out_pin = ~ out_pin;
TL0=0X78;
TH0=0XEC;
}
void exit_init()
{
TMOD=1;
TL0=0x78;
TH0=0XEC;
ET0=1;
EA=1;
TR0=1;
}
void main()
{
exit_init();
P2=0xff;
while(1)
{
;
}
}
工作方式2
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit out_pin = P2^0;
void timer0_inter() interrupt 1
{
out_pin = ~ out_pin;
}
void exit_init()
{
TMOD=2;
TL0=0x06;
TH0=0X06;
ET0=1;
EA=1;
TR0=1;
}
void main()
{
exit_init();
P2=0xff;
while(1)
{
;
}
}
工作方式3
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit out_A = P2^0;
sbit out_B = P2^1;
void timerTL0_inter() interrupt 1
{
out_A = ~ out_A;
TL0 =0;
}
void timerTH0_inter() interrupt 3
{
out_B = ~ out_B;
TH0=128;
}
void exit_init()
{
TMOD=3;
TL0=0;
TH0=128;
EA=1;
ET0=1;
ET1=1;
TR0=1;
TR1=1;
}
void main()
{
exit_init();
P2=0xff;
while(1)
{
;
}
}
计数器
计数功能是对外部脉冲进行计数,捕捉输入脉冲的下降沿,从T0(P3.4)和T1(P3.5)两个引脚输入。
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
#define segN 4
uchar code segD[] = {
0x3f,0x06,0x5b,0x4f,0x66,
0x6d,0x7d,0x07,0x7f,0x6f,
0x00,0xf3};
void delay(uint timer)
{
uchar j = 124;
while(timer--)
{
while(j--);
}
}
void display(uint k)
{
uchar a = k%10;
uchar b = k/10%10;
P2 = 0xfe;
P0 = segD[b];
delay(5);
P2 = 0xfd;
P0 = segD[a];
delay(5);
}
void int0_inter() interrupt 0
{
TL1 =0;
}
void timer_inter() interrupt 3
{
TL1=0;
}
void exit_init()
{
IT0=1;
EX0=1;
TMOD=0x60;
TL1=0;
TH1=0;
EA=1;
ET1=1;
TR1=1;
}
void main()
{
uchar num;
exit_init();
P2=0xff;
while(1)
{
num = TL1;
display(num);
}
}