单片机简单的计算器c语言程序,51单片机实现简单计算器C语言程序+Proteus仿真
时间: 2024-02-12 13:08:36 浏览: 92
51单片机实现简易计算器功能
以下是一个简单的计算器C语言程序,使用51单片机实现,同时还包括Proteus仿真。注意,这只是一个简单的示例,仅供参考。您可以根据自己的需求和具体情况进行修改和优化。
```
#include <reg51.h>
// 定义按键端口
sbit key1 = P3^0;
sbit key2 = P3^1;
sbit key3 = P3^2;
sbit key4 = P3^3;
sbit key5 = P3^4;
sbit key6 = P3^5;
sbit key7 = P3^6;
sbit key8 = P3^7;
// 定义LED端口
sbit led1 = P2^0;
sbit led2 = P2^1;
sbit led3 = P2^2;
sbit led4 = P2^3;
sbit led5 = P2^4;
sbit led6 = P2^5;
sbit led7 = P2^6;
sbit led8 = P2^7;
// 定义计算器变量
unsigned char num1, num2, op, result;
// 定义函数
void delay(unsigned int time);
void init();
void compute();
void main()
{
init();
while(1)
{
// 判断按键
if(key1 == 0)
{
num1 = 1;
led1 = 1;
delay(50);
led1 = 0;
while(key1 == 0);
}
if(key2 == 0)
{
num1 = 2;
led2 = 1;
delay(50);
led2 = 0;
while(key2 == 0);
}
if(key3 == 0)
{
num1 = 3;
led3 = 1;
delay(50);
led3 = 0;
while(key3 == 0);
}
if(key4 == 0)
{
op = '+';
led4 = 1;
delay(50);
led4 = 0;
while(key4 == 0);
}
if(key5 == 0)
{
num2 = 4;
led5 = 1;
delay(50);
led5 = 0;
while(key5 == 0);
}
if(key6 == 0)
{
num2 = 5;
led6 = 1;
delay(50);
led6 = 0;
while(key6 == 0);
}
if(key7 == 0)
{
num2 = 6;
led7 = 1;
delay(50);
led7 = 0;
while(key7 == 0);
}
if(key8 == 0)
{
compute();
led8 = 1;
delay(50);
led8 = 0;
while(key8 == 0);
}
}
}
void delay(unsigned int time)
{
unsigned int i, j;
for(i=0; i<time; i++)
{
for(j=0; j<120; j++);
}
}
void init()
{
num1 = 0;
num2 = 0;
op = 0;
result = 0;
led1 = 0;
led2 = 0;
led3 = 0;
led4 = 0;
led5 = 0;
led6 = 0;
led7 = 0;
led8 = 0;
}
void compute()
{
switch(op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
result = 0;
break;
}
num1 = result;
num2 = 0;
op = 0;
}
```
在Proteus中,可以创建一个51单片机电路,并将其与上面的C语言程序进行连接。您可以使用仿真按钮进行仿真和测试。
阅读全文