#include"reg52.h"
#include "LCD1602.h"
//按键定义
sbit KEY0=P1^0;
sbit KEY1=P1^1;
sbit KEY2=P1^2;
sbit KEY3=P1^3;
sbit KEY4=P1^4;
sbit KEY5=P1^5;
sbit KEY6=P1^6;
sbit KEY7=P1^7;
//函数定义:
/**
* @brief LCD1602延时函数,12MHz调用可延时1ms
* @param 无
* @retval 无
*/
void LCD_Delay(int time)
{
while(time)
{
time--;
}
}
int Matrix_Key()
{
int Key_Number=0;
//判断第一列
P1=0XFF;
KEY3=0;
//判断按键1
if(KEY7==0){LCD_Delay(2000);while(KEY7==0);LCD_Delay(2000);Key_Number=1;}
//判断按键1
if(KEY6==0){LCD_Delay(2000);while(KEY6==0);LCD_Delay(2000);Key_Number=5;}
//判断按键9
if(KEY5==0){LCD_Delay(2000);while(KEY5==0);LCD_Delay(2000);Key_Number=9;}
//判断按键13
if(KEY4==0){LCD_Delay(2000);while(KEY4==0);LCD_Delay(2000);Key_Number=13;}
//判断第二列
P1=0XFF;
KEY2=0;
//判断按键1
if(KEY7==0){LCD_Delay(2000);while(KEY7==0);LCD_Delay(2000);Key_Number=2;}
//判断按键1
if(KEY6==0){LCD_Delay(2000);while(KEY6==0);LCD_Delay(2000);Key_Number=6;}
//判断按键9
if(KEY5==0){LCD_Delay(2000);while(KEY5==0);LCD_Delay(2000);Key_Number=10;}
//判断按键13
if(KEY4==0){LCD_Delay(2000);while(KEY4==0);LCD_Delay(2000);Key_Number=14;}
//判断第三列
P1=0XFF;
KEY1=0;
//判断按键1
if(KEY7==0){LCD_Delay(2000);while(KEY7==0);LCD_Delay(2000);Key_Number=3;}
//判断按键1
if(KEY6==0){LCD_Delay(2000);while(KEY6==0);LCD_Delay(2000);Key_Number=7;}
//判断按键9
if(KEY5==0){LCD_Delay(2000);while(KEY5==0);LCD_Delay(2000);Key_Number=11;}
//判断按键13
if(KEY4==0){LCD_Delay(2000);while(KEY4==0);LCD_Delay(2000);Key_Number=15;}
//判断第四列
P1=0XFF;
KEY0=0;
//判断按键1
if(KEY7==0){LCD_Delay(2000);while(KEY7==0);LCD_Delay(2000);Key_Number=4;}
//判断按键1
if(KEY6==0){LCD_Delay(2000);while(KEY6==0);LCD_Delay(2000);Key_Number=8;}
//判断按键9
if(KEY5==0){LCD_Delay(2000);while(KEY5==0);LCD_Delay(2000);Key_Number=12;}
//判断按键13
if(KEY4==0){LCD_Delay(2000);while(KEY4==0);LCD_Delay(2000);Key_Number=16;}
return Key_Number;
}
unsigned int num1,num2,key ;
int count;
char symbol='A';
int main()
{
LCD_Init(); //LLCD1602初始化
LCD_ShowString(1,4,"Calculator");//显示第一行标题
while(1)
{
//判断矩阵按键按下情况
key = Matrix_Key();
//矩阵按键S1-S10,对应计算器0-9的输入
if(key)
{
if(key<=10)
{
if(symbol!='A' && count!= 0) //第二次数字输入
{
num2*=10; //让数字左移
num2+=key%10; //让按键10变成0
LCD_ShowNum(2,6,num2,2);
}
else
{
//第一次数字输入
num1*=10; //让数字左移
num1+=key%10; //让按键10变成0
LCD_ShowNum(2,1,num1,2);
count=1;
}
}
else if(key==11) //加法
{
symbol='+';
LCD_ShowChar(2,4,'+');
}
else if(key==12) //减法
{
symbol='-';
LCD_ShowChar(2,4,'-');
}
else if(key==13) //乘法
{
symbol='*';
LCD_ShowChar(2,4,'*');
}
else if(key==14) //除法
{
symbol='/';
LCD_ShowChar(2,4,'/');
}
else if(key==15) //等于
{
LCD_ShowChar(2,9,'=');
//进行运算
if(symbol=='+')
{
LCD_ShowNum(2,11,num1+num2,5);
}
if(symbol=='-')
{
LCD_ShowNum(2,11,num1-num2,5);
}
if(symbol=='*')
{
LCD_ShowNum(2,11,num1*num2,5);
}
if(symbol=='/')
{
LCD_ShowNum(2,11,num1/num2,5);
}
}
}
}
return 0;
}