基于AT89s52单片机的计数器,单击按键使计数加一,单击另一个按键使计数减一,并用数码管显示
时间: 2024-05-08 21:16:18 浏览: 112
以下是基于AT89s52单片机的计数器,单击按键使计数加一,单击另一个按键使计数减一,并用数码管显示的代码:
```c
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit key_add=P3^0;
sbit key_sub=P3^1;
uchar code Table[]={
0xc0, //0
0xf9, //1
0xa4, //2
0xb0, //3
0x99, //4
0x92, //5
0x82, //6
0xf8, //7
0x80, //8
0x90 //9
};
uint counter=0;
void delay(uint x){
uint i,j;
for(i=x;i>0;i--)
for(j=125;j>0;j--);
}
void display(uchar dat,uchar num){
P2=0xff;
P1=Table[dat];
P2=num;
delay(1);
}
void main(){
EA=1; //开总中断
EX0=1; //开外部中断0
EX1=1; //开外部中断1
IT0=1; //外部中断0下降沿触发
IT1=1; //外部中断1下降沿触发
while(1){
display(counter%10,0xfe);
display(counter/10,0xfd);
}
}
void add() interrupt 0{
delay(5); //消抖
if(key_add==0){
if(counter<99)
counter++;
}
}
void sub() interrupt 2{
delay(5); //消抖
if(key_sub==0){
if(counter>0)
counter--;
}
}
```
其中,key_add和key_sub分别对应加一和减一的按键。Table数组存储了0~9的数码管显示值,display函数用于在数码管上显示计数器的值。计数器的值存储在counter变量中,在加一和减一的中断函数中对其进行修改。外部中断0和1用于触发加一和减一的中断函数。程序通过不断在数码管上显示计数器的值,实现了一个简单的计数器。
阅读全文
相关推荐


















