51單片機(jī)100例實(shí)例之15例
//項(xiàng)目名稱:按鍵控制數(shù)碼管加減演示
//項(xiàng)目再創(chuàng)作者:科技小宅神
//完成時(shí)間:2021/01/21

#include <reg51.h>//c51頭文件
#include <intrins.h>//c51內(nèi)部移位函數(shù)
#define uchar unsigned char
#define uint? unsigned int
//段碼
uchar code DSY_CODE[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff};
//待顯示的3位緩沖
uchar Num_Buffer[]={0,0,0};
//按鍵代碼,按鍵計(jì)數(shù)
uchar Key_Code,Key_Counts=0;
//1毫秒延時(shí)子程序
void DelayMS(uint x)
{
? uchar t;
while(x--)
{
for(t=0;t<120;t++);
}
}
//刷新顯示函數(shù)
void Show_Counts_ON_DSY()
{
? uchar i,j=0x01;
Num_Buffer[2]=Key_Counts/100; //百位
? ? Num_Buffer[1]=Key_Counts/10%10; //十位
Num_Buffer[0]=Key_Counts%10; //個(gè)位
for(i=0;i<3;i++)
{
j = _cror_(j,1);//循環(huán)右移,每次移一位
P2 = j;//P2循環(huán)右移,每次移一位
P0 = DSY_CODE[Num_Buffer[i]];
DelayMS(1);
}
}
//主程序
void main()
{
? uchar i;
P0 = 0xff;
P1 = 0xff;
P2 = 0x00;
Key_Code=0xff;
while(1)
{
Show_Counts_ON_DSY();
P1 = 0xff;
Key_Code=P1;
if(Key_Code != 0xff)
{
for(i=0;i<30;i++)
{
Show_Counts_ON_DSY();
}
}
switch(Key_Code)//按鍵代碼多分支選擇結(jié)構(gòu)
{
case 0xfe: //當(dāng)P1=0xfe,即P1.0=0,即k1按下時(shí)
? ? ? ?if(Key_Counts<255) Key_Counts++;break;//如果按鍵計(jì)數(shù)小于
case 0xfd: //當(dāng)P1=0xfd,即P1.1=0,即k2按下時(shí)
? ? ? ?if(Key_Counts>0) Key_Counts--;break;
case 0xfb: //當(dāng)P1=0xfb,即P1.2=0,即k3按下時(shí)
? ? ? ?Key_Counts=0;
}
Key_Code = 0xff;
}
}