|
#include <REG51.H>
#include "key.h"
#include "lcd1602.h"
#include "math.h"
#define uchar unsigned char
#define uint unsigned int
uchar code num[15]="0123456789+-*/=";
uchar code free[16]=" ";
uchar calculate[16]="0";
uchar result[16]="0";
//对式子进行运算
void count(){
uchar i=0,k=0,c=0,j=0;
uint sum1=0,sum2=0,sum=0;
//检测第一项的数值
while(calculate[c]>=0x30 && calculate[c]<=0x39)
{
c++;
}
k=c;
for(i=0;i<c;i++)
{
sum1=sum1+(calculate[i]-0x30)*(int)(pow(10.0,c-i-1)+0.1);
}
//检测第二项数值
i=c+1;
c++;
while(calculate[c]>=0x30 && calculate[c]<=0x39)
{
c++;
}
//i++;
for(;i<c;i++)
{
sum2=sum2+(calculate[i]-0x30)*(int)(pow(10.0,c-i-1)+0.1);
}
//进行运算
if (calculate[k]==0x2B) sum=sum1+sum2;
else if (calculate[k]==0x2D) sum=sum1-sum2;
else if (calculate[k]==0x2A) sum=sum1*sum2;
else if (calculate[k]==0x2F) sum=sum1/sum2;
i=0;
k=15;
//显示结果
while (sum>0)
{
result[i]=num[sum%10];
//检测result数值是否正确
LcdWriteCmd(0x80+0x40+k);
LcdWriteDat(result[i]);
sum=sum/10;
i++;k--;
}
}
void key_on(key)
{
uchar i=0;
static uint site=0;
switch(key)
{
case 1:case 2:case 3:case 4:
case 5:case 6:case 7:case 8:
case 9:case 10:case 11:case 12:
case 13:case 14:
LcdWriteCmd(0x80+site);
LcdWriteDat(num[key-1]);
calculate[site]=num[key-1];
site++;
delayms(300);
break;
case 15:
LcdWriteCmd(0x80+site);
LcdWriteDat(num[key-1]);
calculate[site]=num[key-1];
site++;
count(); //运算
delayms(300);
break;
case 16:
site=0;
LcdWriteCmd(0x80+site);
for (i=0;i<16;i++)
{
LcdWriteDat(free[i]);
}
LcdWriteCmd(0x80+0x40+site);
for (i=0;i<16;i++)
{
LcdWriteDat(free[i]);
}
break;
}
}
void main()
{
uchar key=0;
InitLcd1602();
P1=0x0F;
while(1){
key=KEY_Scan();
key_on(key);
}
}
部分程序
|
|