Keil uVision5 1.4寸屏幕的简易计算器
时间: 2024-03-01 10:53:28 浏览: 93
Keil安装包.zip
以下是使用Keil uVision5编写的简易计算器代码,可以在1.4寸屏幕上显示数字和运算符,并支持加、减、乘、除四种基本运算:
```
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit RS = P2^0;
sbit RW = P2^1;
sbit EN = P2^2;
uchar num1[5] = {0};
uchar num2[5] = {0};
uchar result[5] = {0};
uchar operator = 0;
void delay(uint i)
{
while(i--);
}
void writeCmd(uchar cmd)
{
RS = 0;
RW = 0;
P0 = cmd;
EN = 1;
delay(100);
EN = 0;
}
void writeData(uchar dat)
{
RS = 1;
RW = 0;
P0 = dat;
EN = 1;
delay(100);
EN = 0;
}
void initLCD()
{
writeCmd(0x38);
writeCmd(0x0c);
writeCmd(0x06);
writeCmd(0x01);
}
void clearLCD()
{
writeCmd(0x01);
}
void writeStr(uchar x, uchar y, uchar *str)
{
uchar i;
if(y == 0)
{
writeCmd(0x80 + x);
}
else
{
writeCmd(0xc0 + x);
}
for(i = 0; str[i] != '\0'; i++)
{
writeData(str[i]);
}
}
void readNum1()
{
uchar i, j = 0;
clearLCD();
writeStr(0, 0, "Num1:");
while(1)
{
if(j > 4)
{
break;
}
if(P3 != 0xff)
{
num1[j] = P3;
j++;
delay(1000);
while(P3 != 0xff);
}
writeStr(6, 0, num1);
}
}
void readNum2()
{
uchar i, j = 0;
clearLCD();
writeStr(0, 0, "Num2:");
while(1)
{
if(j > 4)
{
break;
}
if(P3 != 0xff)
{
num2[j] = P3;
j++;
delay(1000);
while(P3 != 0xff);
}
writeStr(6, 0, num2);
}
}
void readOp()
{
clearLCD();
writeStr(0, 0, "Op:");
while(1)
{
if(P3 == 0xfd)
{
operator = '+';
break;
}
else if(P3 == 0xfb)
{
operator = '-';
break;
}
else if(P3 == 0xf7)
{
operator = '*';
break;
}
else if(P3 == 0xef)
{
operator = '/';
break;
}
else
{
continue;
}
}
writeData(operator);
}
void calculate()
{
float n1, n2, r;
n1 = atof(num1);
n2 = atof(num2);
switch(operator)
{
case '+':
r = n1 + n2;
break;
case '-':
r = n1 - n2;
break;
case '*':
r = n1 * n2;
break;
case '/':
if(n2 == 0)
{
clearLCD();
writeStr(0, 0, "Error: Div by 0");
while(1);
}
else
{
r = n1 / n2;
}
break;
default:
clearLCD();
writeStr(0, 0, "Error: Invalid Op");
while(1);
}
sprintf(result, "%.2f", r);
clearLCD();
writeStr(0, 0, "Result:");
writeStr(7, 0, result);
}
int main()
{
initLCD();
while(1)
{
readNum1();
readOp();
readNum2();
calculate();
}
return 0;
}
```
注:此代码仅供参考,实际应用中可能需要根据需求进行修改和优化。
阅读全文