51单片机LCD计算器程序
时间: 2023-12-23 15:06:30 浏览: 84
51单片机计算器程序
5星 · 资源好评率100%
以下是一个基于51单片机的LCD计算器程序,可以实现加、减、乘、除四则运算:
```
#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit RS = P2^6; //LCD1602控制引脚
sbit RW = P2^5;
sbit EN = P2^7;
sbit KEY1 = P3^0; //按键
sbit KEY2 = P3^1;
sbit KEY3 = P3^2;
sbit KEY4 = P3^3;
sbit KEY5 = P3^4;
uchar num1[5], num2[5], result[8]; //存储数字和结果的数组
uchar op; //运算符
void delay(uint t) //延时函数
{
uint i, j;
for(i=0; i<t; i++)
for(j=0; j<120; j++);
}
void write_com(uchar com) //写指令函数
{
RS = 0;
RW = 0;
P0 = com;
EN = 1;
delay(5);
EN = 0;
}
void write_data(uchar dat) //写数据函数
{
RS = 1;
RW = 0;
P0 = dat;
EN = 1;
delay(5);
EN = 0;
}
void init_LCD() //LCD初始化函数
{
write_com(0x38); //8位数据接口,2行显示,5x7点阵
write_com(0x0c); //显示开,光标关,闪烁关
write_com(0x06); //文字不动,光标自动右移
write_com(0x01); //清屏,光标回到起始位置
}
void write_string(uchar x, uchar y, uchar *str) //写字符串函数
{
uchar i=0;
if(x<16)
{
if(y==0) //第一行
write_com(0x80+x);
else //第二行
write_com(0x80+0x40+x);
while(str[i]!='\0')
{
write_data(str[i]);
i++;
}
}
}
void get_num1() //获取第一个数字
{
uchar i=0;
while(KEY5==0) //等待按键松开
{
if(KEY1==0) //数字1
{
num1[i] = '1';
i++;
write_string(i-1, 0, "1");
delay(500);
}
else if(KEY2==0) //数字2
{
num1[i] = '2';
i++;
write_string(i-1, 0, "2");
delay(500);
}
else if(KEY3==0) //数字3
{
num1[i] = '3';
i++;
write_string(i-1, 0, "3");
delay(500);
}
else if(KEY4==0) //加号
{
op = '+';
write_string(i, 0, "+");
delay(500);
break;
}
}
}
void get_num2() //获取第二个数字
{
uchar i=0;
while(KEY5==0) //等待按键松开
{
if(KEY1==0) //数字1
{
num2[i] = '1';
i++;
write_string(i, 0, "1");
delay(500);
}
else if(KEY2==0) //数字2
{
num2[i] = '2';
i++;
write_string(i, 0, "2");
delay(500);
}
else if(KEY3==0) //数字3
{
num2[i] = '3';
i++;
write_string(i, 0, "3");
delay(500);
}
else if(KEY4==0) //减号
{
op = '-';
write_string(i, 0, "-");
delay(500);
break;
}
}
}
void calculate() //计算结果
{
uint n1=0, n2=0, res=0;
n1 = (num1[0]-48)*100 + (num1[1]-48)*10 + (num1[2]-48);
n2 = (num2[0]-48)*100 + (num2[1]-48)*10 + (num2[2]-48);
switch(op)
{
case '+':
res = n1 + n2;
break;
case '-':
res = n1 - n2;
break;
case '*':
res = n1 * n2;
break;
case '/':
res = n1 / n2;
break;
}
sprintf(result, "%d", res); //将结果转换为字符串
write_string(0, 1, result);
}
void main()
{
init_LCD();
write_string(0, 0, "CALCULATOR");
while(1)
{
while(KEY5==1); //等待按键按下
if(KEY1==0) //乘号
{
op = '*';
write_string(3, 0, "*");
delay(500);
get_num1();
get_num2();
calculate();
}
else if(KEY2==0) //除号
{
op = '/';
write_string(3, 0, "/");
delay(500);
get_num1();
get_num2();
calculate();
}
}
}
```
需要注意的是,该程序只能进行三位数以内的整数运算,如果需要支持更大的数或实现浮点数运算,需要进行相应的修改。
阅读全文