#include
#define uchar unsigned char #define uint unsigned int char b[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6, 0xa1,0x86,0x8e,0x8c,0xc1,0xce,0x91,0x89,0xc7,0xff}; // 共阴极字符码 //延时函数,用于完成程序中的时间短延时,表明延时cnt个毫秒 void delay(unsigned int cnt) { unsigned char i; while(cnt--) { for(i=220;i>0;i--) ; } } //键盘扫描程序 uchar keyboardscan(void) { uchar sccode,recode; P1=0xf0; //P1口附初值 if((P1&0xf0)!=0xf0)//假如P1口电平不等于0xf0,表明有按键按下 { delay(20); //延时20毫秒后再判别,看是否还有按键按下,次步为软件防抖 if((P1&0xf0)!=0xf0)//持续判别是否有按键按下 { sccode=0xfe; //进行逐行判别 while((sccode&0x10)!=0) { P1=sccode; if((P1&0xf0)!=0xf0) { recode=(P1&0xf0|0x0f); switch((~sccode)+(~recode)) { // 下面是键盘的编码辨认 case 0x11: return(1); break; case 0x21: return(2); break; case 0x41: return(3); break; case 0x81: return(11); break;//回来对应的键值0~15 case 0x12: return(4); break; case 0x22: return(5); break; case 0x42: return(6); break; case 0x82: return(12); break; case 0x14: return(7); break; case 0x24: return(8); break; case 0x44: return(9); break; case 0x84: return(13); break; case 0x18: return(10); break; case 0x28: return(15); break; case 0x48: return(16); break; case 0x88: return(14); break; default:break; } } else sccode = (sccode<<1)|0x01; } } } return(0xff); //假如没有按键按下,则回来0xff } void output(uchar number) { P0=b[number/10]; P2=b[number%10]; } int yunsuan(uchar a,uchar b,uchar c) { switch(c) { case 1:return(a/b);break; case 2:return(a*b);break; case 3:return(a-b);break; case 4:return(a+b);break; } } void main(void) //主函数 { unsigned char n1,n2,key,index,a; n1=n2=index=0; P0=P2=b[0]; while(1) { key = keyboardscan();//键盘扫描,看是否有按键按下 if(key != 0xff)//假如有按键按下,则key不再是0xff了,显现该按键键值 { if(key<10) { if(!index) n1=key%10; else n2=key%10; output(key%10); } else if(key==15) { n1=n2=index=0; output(0); } else if(key==16) { if(!index) output(n1); else { a=yunsuan(n1,n2,index); a=a%100; output(a); n1=a; n2=index=0; } } else { if(index==0||n2==0) index=key-10; else { a=yunsuan(n1,n2,index); a=a%100; output(a); n1=a; n2=0; index=key-10; } } } } }