|
不知道你用的什么MCU和外圍電路,只能按51給你寫了程序,端口定義根據(jù)實(shí)際電路自行修改。
#include <AT89X52.H>
#define uchar unsigned char
#define uint unsigned int
sbit OUT=P1^0; //輸出
sbit key1=P3^4; //鍵1
sbit key2=P3^5; //鍵2
sbit dula=P2^6; //段選
sbit wela=P2^7; //位選
uchar code table[]={ //共陰數(shù)碼管0~f
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71};
uchar Cnt50ms=0,Cnt1s=0;
uchar Time=0;
bit flag=0;
void Timer0Init();
void keycan();
void display();
void Countdown();
void main()
{
Timer0Init(); //初始化定時(shí)器
while(1)
{
keycan(); //按鍵掃描
display(); //顯示
Countdown();//倒計(jì)時(shí)
}
}
void Timer0Init() //50毫秒@12.000MHz
{
TMOD= 0x01; //設(shè)置定時(shí)器模式
TL0 = 0xB0; //設(shè)置定時(shí)初值
TH0 = 0x3C; //設(shè)置定時(shí)初值
// TF0 = 0; //清除TF0標(biāo)志
// TR0 = 1; //定時(shí)器0開始計(jì)時(shí)
EA=1; //開總中斷
ET0=1; //開T0中斷
}
void keycan()
{
static bit key1_sign=0,key2_sign=0; //按鍵自鎖標(biāo)志
static uchar count1=0,count2=0; //消抖計(jì)數(shù)變量
if(!key1) //檢測(cè)按鍵1如果按下為0
{
if((key1_sign==0)&&(flag==0)) //按鍵自鎖標(biāo)志為0
{
count1++; //消抖計(jì)數(shù)
if(count1>=250) //消抖延時(shí)
{
key1_sign=1; //按鍵自鎖標(biāo)志置1
Cnt50ms=0;
Time++; //定時(shí)時(shí)間變量+1
if(Time>=10)
Time=0;
}
}
}
else
{
key1_sign=0; //按鍵自鎖標(biāo)志清0
count1=0; //消抖計(jì)數(shù)清0
}
if(!key2) //檢測(cè)按鍵2如果按下為0
{
if(key2_sign==0) //按鍵自鎖標(biāo)志為0
{
count2++; //消抖計(jì)數(shù)
if(count2>=250) //消抖延時(shí)
{
key2_sign=1; //按鍵自鎖標(biāo)志置1
Cnt1s=Time; //傳遞定時(shí)時(shí)間
if(Cnt1s>0)
{
OUT = 0; //低電平輸出
flag= 1; //禁止key1操作
TR0 = 1; //開啟定時(shí)器
}
}
}
}
else
{
key2_sign=0; //按鍵自鎖標(biāo)志清0
count2=0; //消抖計(jì)數(shù)清0
}
}
void display()
{
if(flag==0)
P0=table[Time]; //顯示定時(shí)時(shí)間
else
P0=table[Cnt1s]|0x80;//加點(diǎn)表示倒計(jì)時(shí)工作中
dula=1;
dula=0;
P0=0x7e; //6位數(shù)碼管只使用第1位
wela=1;
wela=0;
}
void Countdown() //倒計(jì)時(shí)
{
if(flag==1)
{
if(Cnt1s==0)
{
TR0 = 0; //關(guān)閉定時(shí)器
OUT = 1; //停止輸出
flag= 0; //允許key1操作
}
}
}
void Timer0() interrupt 1
{
TL0 = 0xB0; //設(shè)置定時(shí)重裝值
TH0 = 0x3C; //設(shè)置定時(shí)重裝值
Cnt50ms++;
if(Cnt50ms>=20)//1秒
{
Cnt50ms=0;
Cnt1s--;
}
} |
|