现在这个计算器仅有加法。出现的问题是计算结果显示有时正确有时是乱码。
/*结果有时会出现乱码*/
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
uchar code table[]={0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f};
void delay( uint m ) //延时函数
{
uint x , y ;
for( x = m ; x > 0 ; x--)
for( y = 110 ; y > 0 ; y--);
}
sbit beep = P3^1 ; //蜂鸣器
uchar firstflot = 0;
int boat = 0 ;
int second = 0 , third = 0 , m , n ;
int keyscan() //扫描键盘
{
int temp, num ;
P2=0x7f;
temp=P2;
temp=temp&0x0f; //判断第一行按键
if(temp != 0x0f )
{
delay( 10 ) ;
temp = P2 ; //重读P2口值
temp = temp & 0x0f ;
if( temp != 0x0f )
{
temp = P2 ;
switch(temp)
{
case 0x77: num=1; //1
firstflot=1 ;
break;
case 0x7b: num=2; //2
firstflot=1 ;
break;
case 0x7d: num=3; //3
firstflot=1 ;
break;
case 0x7e: num = '+' ; //+
break;
}
while(temp != 0x0f) //等待按键释放
{
temp = P2;
temp = temp & 0x0f;
}
}
}
P2 = 0xbf ; //扫描第二行键盘
temp = P2 ;
temp = temp & 0x0f;
if( temp != 0x0f )
{
delay( 10 ) ; //消抖
temp = P2 ;
temp = temp & 0x0f ;
if( temp != 0x0f )
{
temp = P2 ;
switch( temp )
{
case 0xb7: num=4; //4
firstflot=1 ;
break;
case 0xbb: num=5; //5
firstflot=1 ;
break;
case 0xbd: num=6; //6
firstflot=1 ;
break;
case 0xbe: num = '-' ; //-
break;
}
while( temp != 0x0f )
{
temp = P2 ;
temp = temp & 0x0f ;
}
}
}
P2 = 0xdf ; //扫描第三行键盘
temp = P2 ;
temp = temp & 0x0f ;
if( temp != 0x0f )
{
delay( 10 ) ; //消抖
temp = P2 ;
temp = temp & 0x0f ;
if( temp != 0x0f )
{
temp = P2 ;
switch( temp )
{
case 0xd7: num=7; //7
firstflot=1 ;
break;
case 0xdb: num=8; //8
firstflot=1 ;
break;
case 0xdd: num=9; //9
firstflot=1 ;
break;
case 0xde: num = '*' ; //*
break;
}
while( temp != 0x0f )
{
temp = P2;
temp = temp & 0x0f ;
}
}
}
P2 = 0xef ; //扫描第四行键盘
temp = P2 ;
temp = temp & 0x0f ;
if( temp != 0x0f )
{
delay( 10 ) ; //消抖
temp = P2 ;
temp = temp & 0x0f;
if( temp != 0x0f )
{
temp = P2 ;
switch( temp )
{
// case 0xe7: printf("num%s",onn) //归0
// break;
case 0xeb: num = 0 ; //0
firstflot=1 ;
break;
case 0xed: num = '=' ; //=
break;
case 0xee: num = '/' ; //除
break;
}
}
}
return num ;
}
/*分模块完成计算器程序,完成一个模块后测试能否正常执行,能则进行下一个*/
/*扫描键盘省略*/
int modern_1() //输入第一次数字
{
if(firstflot == 1 && second == 0)
{
P0 = 0x7f ;
m = keyscan() ;
P1 = table[ m ] ;
delay( 1 ) ;
return m ;
}
return m ;
}
void modern_2() //扫描功能键
{
if(keyscan() == '+')
{
P0 = 0xff ; //熄灭上位数字
delay(100) ;
firstflot = 0 ;
second = 1 ;
boat = 1 ;
}
}
int modern_3() /*再次输入数字*/
{
// int n ;
if(second == 1 && boat ==1)
{
while(1)
{
keyscan() ;
if(firstflot == 1)
{
P0 = 0x7f ;
n = keyscan() ;
P1 = table[ n ] ;
boat = 0 ;
}
return n ;
}
}
return n ;
}
int modern_4() /*计算结果*/
{
int z ;
if(keyscan() == '=')
{
z = m + n ;
third = 1 ;
return z ;
}
return z ;
}
void modern_5() /*输出结果*/
{
int c ;
if(third == 1)
{
c = modern_4() ;
P0 = 0x7f ; /*个位*/
P1 = table[c%10] ;
delay(1) ;
P0 = 0xbf ; /*十位*/
P1 = table[c/10] ;
delay(1) ;
}
}
void main() /*输出结果*/
{
P0 = 0x7f;
P1 = table[0] ;
delay(1) ;
while(1)
{
keyscan() ;
modern_1() ; modern_2() ;
modern_3() ; modern_4() ;
modern_5() ;
}
}
|