51单片机简易计算器cx
时间: 2023-07-24 16:35:02 浏览: 167
好的,以下是一个基于Keil C的简易计算器示例代码:
```c
#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
// 按键输入的IO口
sbit KEY_ADD = P2^0;
sbit KEY_SUB = P2^1;
sbit KEY_MUL = P2^2;
sbit KEY_DIV = P2^3;
sbit KEY_EQ = P2^4;
sbit KEY_CLR = P2^5;
sbit KEY_7 = P2^6;
sbit KEY_8 = P2^7;
// 数码管IO口
sbit DIG_1 = P1^0;
sbit DIG_2 = P1^1;
sbit DIG_3 = P1^2;
sbit DIG_4 = P1^3;
sbit SEG_A = P1^4;
sbit SEG_B = P1^5;
sbit SEG_C = P1^6;
sbit SEG_D = P1^7;
uchar code DIG_TABLE[] = { // 数码管显示表
0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f
};
// 数码管显示函数
void display(uint num) {
uchar i;
uchar dig[4];
for (i = 0; i < 4; i++) {
dig[i] = num % 10;
num /= 10;
}
for (i = 0; i < 100; i++) { // 防止闪烁
DIG_1 = 0; SEG_A = (dig[3] == 0 && i < 50);
DIG_2 = 0; SEG_B = (dig[2] == 0 && i < 50);
DIG_3 = 0; SEG_C = (dig[1] == 0 && i < 50);
DIG_4 = 0; SEG_D = (dig[0] == 0 && i < 50);
_nop_(); _nop_(); _nop_();
DIG_1 = 1; SEG_A = DIG_TABLE[dig[3]];
DIG_2 = 1; SEG_B = DIG_TABLE[dig[2]];
DIG_3 = 1; SEG_C = DIG_TABLE[dig[1]];
DIG_4 = 1; SEG_D = DIG_TABLE[dig[0]];
_nop_(); _nop_(); _nop_();
}
}
// 读取按键输入函数
uchar read_key() {
if (!KEY_7) return 7;
if (!KEY_8) return 8;
if (!KEY_ADD) return '+';
if (!KEY_SUB) return '-';
if (!KEY_MUL) return '*';
if (!KEY_DIV) return '/';
if (!KEY_EQ) return '=';
if (!KEY_CLR) return 'C';
return 0;
}
void main() {
uint num1, num2, result;
uchar op, key;
while (1) {
num1 = num2 = result = op = 0;
while (1) {
key = read_key();
if (key >= '0' && key <= '9') { // 数字
num2 = num2 * 10 + key - '0';
display(num2);
} else if (key == '+' || key == '-' || key == '*' || key == '/') { // 运算符
if (op != 0) { // 已有运算符,先计算上一次结果
switch (op) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
}
num1 = result;
num2 = 0;
display(result);
}
op = key;
} else if (key == '=') { // 等于号,计算结果
switch (op) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
}
num1 = result;
num2 = 0;
op = 0;
display(result);
} else if (key == 'C') { // 清空,重置状态
num1 = num2 = result = op = 0;
display(0);
while (read_key() == 'C') {} // 等待按键释放
}
}
}
}
```
这个代码实现了基本的加减乘除运算和清空功能。需要根据具体的硬件连接和需求进行修改和优化。
阅读全文