基于 STC89C52 单片机的简易加减法计算器代码
时间: 2024-01-11 13:02:03 浏览: 91
以下是基于STC89C52单片机的简易加减法计算器的代码,供你参考:
```c
#include <reg52.h>
#include <stdio.h>
sbit KEY1 = P3^2;
sbit KEY2 = P3^3;
sbit KEY3 = P3^4;
sbit KEY4 = P3^5;
sbit D1 = P1^0;
sbit D2 = P1^1;
sbit D3 = P1^2;
sbit D4 = P1^3;
char code Table[] = {
0x3f, 0x06, 0x5b, 0x4f, 0x66,
0x6d, 0x7d, 0x07, 0x7f, 0x6f
};
unsigned char num1, num2, flag, oper, result;
unsigned char Stack[4];
unsigned char Top = 0;
void Delay(unsigned int i) {
while(i--);
}
void Display(unsigned char num) {
D4 = 1;
P0 = Table[num%10];
D4 = 0;
Delay(5);
D3 = 1;
P0 = Table[num/10%10];
D3 = 0;
Delay(5);
D2 = 1;
P0 = Table[num/100%10];
D2 = 0;
Delay(5);
D1 = 1;
P0 = Table[num/1000%10];
D1 = 0;
Delay(5);
}
void KeyDown() {
if(!KEY1) {
Delay(2000);
if(!KEY1) {
if(flag == 0) {
num1 = num1*10 + 1;
Display(num1);
} else {
num2 = num2*10 + 1;
Display(num2);
}
}
}
if(!KEY2) {
Delay(2000);
if(!KEY2) {
if(flag == 0) {
num1 = num1*10 + 2;
Display(num1);
} else {
num2 = num2*10 + 2;
Display(num2);
}
}
}
if(!KEY3) {
Delay(2000);
if(!KEY3) {
if(flag == 0) {
num1 = num1*10 + 3;
Display(num1);
} else {
num2 = num2*10 + 3;
Display(num2);
}
}
}
if(!KEY4) {
Delay(2000);
if(!KEY4) {
if(flag == 0) {
oper = '+';
flag = 1;
} else {
oper = '-';
flag = 2;
}
}
}
}
void Init() {
TMOD = 0x01;
TH0 = 0xfc;
TL0 = 0x18;
EA = 1;
ET0 = 1;
TR0 = 1;
}
void Time0() interrupt 1 {
TH0 = 0xfc;
TL0 = 0x18;
KeyDown();
}
void Calculate() {
switch(oper) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
default: break;
}
Stack[Top++] = result%10;
Stack[Top++] = result/10%10;
Stack[Top++] = result/100%10;
Stack[Top++] = result/1000%10;
while(Top != 0) {
Display(Stack[--Top]);
Delay(10000);
}
}
void main() {
Init();
while(1) {
if(flag == 2) {
Calculate();
flag = 0;
num1 = 0;
num2 = 0;
oper = 0;
}
}
}
```
以上是基于STC89C52单片机的简易加减法计算器的代码,其中包括按键扫描、数码管显示、加减法运算等功能。需要注意的是,代码中的硬件电路需要自行搭建,并且可能需要根据具体情况进行调整。另外,代码中的延时函数只是简单的延时,实际中需要根据具体情况进行调整。
阅读全文