51单片机4×4矩阵键盘计算器的代码
时间: 2023-12-09 18:07:08 浏览: 160
以下是一个简单的51单片机4×4矩阵键盘计算器的代码,您可以根据您的需求进行修改和完善。
```c
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar keyValue, num1, num2, result;
bit flag = 0, op_flag = 0;
void init() //初始化函数
{
P1 = 0xf0;
P2 = 0x00;
TMOD = 0x01;
TH0 = 0x3c;
TL0 = 0xb0;
TR0 = 1;
ET0 = 1;
EA = 1;
}
void delay(uint i) //延时函数
{
while (i--);
}
void keyScan() interrupt 1 //键盘扫描函数
{
uchar scanCode;
P1 = 0xf0;
scanCode = P1;
scanCode &= 0xf0;
if (scanCode != 0xf0)
{
delay(1000);
scanCode = P1;
scanCode &= 0xf0;
if (scanCode != 0xf0)
{
switch (scanCode)
{
case 0x70: keyValue = 1; break;
case 0xb0: keyValue = 2; break;
case 0xd0: keyValue = 3; break;
case 0xe0: keyValue = 4; break;
case 0x30: keyValue = 5; break;
case 0x50: keyValue = 6; break;
case 0x90: keyValue = 7; break;
case 0xa0: keyValue = 8; break;
case 0x10: keyValue = 9; break;
case 0x20: keyValue = 10; break;
case 0x40: keyValue = 11; break;
case 0x80: keyValue = 12; break;
case 0x00: keyValue = 13; break;
}
flag = 1;
}
}
}
void main() //主函数
{
init();
while (1)
{
if (flag)
{
if (keyValue >= 1 && keyValue <= 9)
{
if (!op_flag)
{
num1 = num1 * 10 + keyValue;
P2 = keyValue;
}
else
{
num2 = num2 * 10 + keyValue;
P2 = keyValue;
}
}
else if (keyValue >= 10 && keyValue <= 12)
{
op_flag = 1;
switch (keyValue)
{
case 10: P2 = '+'; break;
case 11: P2 = '-'; break;
case 12: P2 = '*'; break;
}
}
else if (keyValue == 13)
{
switch (P2)
{
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
}
P2 = result;
num1 = num2 = 0;
op_flag = 0;
}
flag = 0;
}
}
}
```
注意,这只是一个简单的实现,还有很多地方可以进行优化和改进。例如,可以添加更多的操作符和功能,增加错误处理等。
阅读全文