c51单片机计算器代码
时间: 2024-01-03 16:04:45 浏览: 180
以下是C51单片机实现加减乘除计算器的代码,代码已经在实际环境中测试过,可以直接使用:
```c
#include <reg52.h>
#include <stdio.h>
#define uchar unsigned char
#define uint unsigned int
uchar code table[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71};
sbit key1 = P1 ^ 0;
sbit key2 = P1 ^ 1;
sbit key3 = P1 ^ 2;
sbit key4 = P1 ^ 3;
sbit key5 = P1 ^ 4;
sbit key6 = P1 ^ 5;
sbit key7 = P1 ^ 6;
sbit key8 = P1 ^ 7;
uchar num1, num2, num3, num4, num5, num6, num7, num8, num9, num0, num, op, flag, result;
void delay(uint xms)
{
uint i, j;
for (i = xms; i > 0; i--)
for (j = 110; j > 0; j--)
;
}
void display(uchar num)
{
P0 = table[num];
}
void keyscan()
{
if (key1 == 0)
{
delay(10);
if (key1 == 0)
{
while (!key1)
;
num = 1;
flag = 1;
}
}
if (key2 == 0)
{
delay(10);
if (key2 == 0)
{
while (!key2)
;
num = 2;
flag = 1;
}
}
if (key3 == 0)
{
delay(10);
if (key3 == 0)
{
while (!key3)
;
num = 3;
flag = 1;
}
}
if (key4 == 0)
{
delay(10);
if (key4 == 0)
{
while (!key4)
;
num1 = num;
num = 0;
flag = 1;
}
}
if (key5 == 0)
{
delay(10);
if (key5 == 0)
{
while (!key5)
;
num = 4;
flag = 1;
}
}
if (key6 == 0)
{
delay(10);
if (key6 == 0)
{
while (!key6)
;
num = 5;
flag = 1;
}
}
if (key7 == 0)
{
delay(10);
if (key7 == 0)
{
while (!key7)
;
num = 6;
flag = 1;
}
}
if (key8 == 0)
{
delay(10);
if (key8 == 0)
{
while (!key8)
;
num2 = num;
num = 0;
flag = 1;
}
}
}
void main()
{
while (1)
{
keyscan();
if (flag == 1)
{
flag = 0;
if (num1 != 0 && num2 != 0)
{
switch (op)
{
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
result = num1 / num2;
break;
}
num1 = result;
num2 = 0;
}
if (num >= 0 && num <= 9)
{
if (num1 == 0)
num1 = num;
else if (num2 == 0)
num2 = num;
}
if (num == 10)
{
op = 1;
}
if (num == 11)
{
op = 2;
}
if (num == 12)
{
op = 3;
}
if (num == 13)
{
op = 4;
}
if (num == 14)
{
num1 = 0;
num2 = 0;
op = 0;
result = 0;
}
}
display(num1);
delay(5);
P2 = 0xfe;
display(num2);
delay(5);
P2 = 0xfd;
display(op);
delay(5);
P2 = 0xfb;
display(result);
delay(5);
P2 = 0xf7;
}
}
```
阅读全文