用c语言编写一个驱动51单片机设计的简易计算器的
时间: 2023-11-26 19:06:45 浏览: 94
基于51单片机的简易计算器设计
5星 · 资源好评率100%
首先,需要连接一个4x4矩阵键盘到51单片机上,然后按照下面的步骤进行编写:
1. 定义键盘端口和显示屏端口。
```c
sbit ROW1 = P2^0;
sbit ROW2 = P2^1;
sbit ROW3 = P2^2;
sbit ROW4 = P2^3;
sbit COL1 = P2^4;
sbit COL2 = P2^5;
sbit COL3 = P2^6;
sbit COL4 = P2^7;
sbit LSA = P0^2;
sbit LSB = P0^3;
sbit LSC = P0^4;
```
2. 定义函数用于扫描键盘输入。
```c
unsigned char KeyScan()
{
unsigned char row = 0, col = 0, key = 0xFF;
ROW1 = 0; ROW2 = 1; ROW3 = 1; ROW4 = 1;
if (COL1 == 0) { col = 1; }
if (COL2 == 0) { col = 2; }
if (COL3 == 0) { col = 3; }
if (COL4 == 0) { col = 4; }
ROW1 = 1; ROW2 = 0; ROW3 = 1; ROW4 = 1;
if (COL1 == 0) { col = 1; }
if (COL2 == 0) { col = 2; }
if (COL3 == 0) { col = 3; }
if (COL4 == 0) { col = 4; }
ROW1 = 1; ROW2 = 1; ROW3 = 0; ROW4 = 1;
if (COL1 == 0) { col = 1; }
if (COL2 == 0) { col = 2; }
if (COL3 == 0) { col = 3; }
if (COL4 == 0) { col = 4; }
ROW1 = 1; ROW2 = 1; ROW3 = 1; ROW4 = 0;
if (COL1 == 0) { col = 1; }
if (COL2 == 0) { col = 2; }
if (COL3 == 0) { col = 3; }
if (COL4 == 0) { col = 4; }
if (col != 0)
{
switch (row)
{
case 0: key = col; break;
case 1: key = col + 4; break;
case 2: key = col + 8; break;
case 3: key = col + 12; break;
}
}
return key;
}
```
3. 定义函数用于显示结果。
```c
void Display(unsigned char num)
{
switch (num)
{
case 0: LSA = 0; LSB = 0; LSC = 0; break;
case 1: LSA = 1; LSB = 0; LSC = 0; break;
case 2: LSA = 0; LSB = 1; LSC = 0; break;
case 3: LSA = 1; LSB = 1; LSC = 0; break;
case 4: LSA = 0; LSB = 0; LSC = 1; break;
case 5: LSA = 1; LSB = 0; LSC = 1; break;
case 6: LSA = 0; LSB = 1; LSC = 1; break;
case 7: LSA = 1; LSB = 1; LSC = 1; break;
}
}
```
4. 在主函数中,使用一个循环来读取键盘输入并执行相应的操作。
```c
void main()
{
unsigned char key = 0xFF, num1 = 0, num2 = 0, result = 0;
while (1)
{
key = KeyScan();
if (key != 0xFF)
{
if (key >= 1 && key <= 9)
{
if (num1 == 0)
{
num1 = key;
Display(num1);
}
else if (num2 == 0)
{
num2 = key;
Display(num2);
}
}
else if (key == 10)
{
result = num1 + num2;
Display(result);
}
else if (key == 11)
{
result = num1 - num2;
Display(result);
}
else if (key == 12)
{
result = num1 * num2;
Display(result);
}
else if (key == 13)
{
result = num1 / num2;
Display(result);
}
else if (key == 14)
{
num1 = 0;
num2 = 0;
result = 0;
LSA = 1; LSB = 1; LSC = 1;
}
}
}
}
```
在这个简易计算器中,1~9为数字键,10为加法键,11为减法键,12为乘法键,13为除法键,14为清零键。当用户按下数字键时,程序会将该数字存储在num1或num2中,并在显示屏上显示出来。当用户按下运算符键时,程序会执行相应的运算并将结果显示在屏幕上。当用户按下清零键时,程序会将所有变量清零并将显示屏清空。
阅读全文