做一个计算器_用51单片机做一个简单的计算器小程序
时间: 2023-08-04 21:23:06 浏览: 62
好的,我可以为您提供一些思路和代码示例。
首先,您需要一个51单片机开发板和一些基础的电路元件,例如LED灯、按钮等。然后,您可以使用Keil C51等IDE进行编程。
下面是一个简单的计算器小程序的示例代码:
```
#include <reg51.h>
sbit BTN0 = P1^0; // 按钮0
sbit BTN1 = P1^1; // 按钮1
sbit BTN2 = P1^2; // 按钮2
sbit BTN3 = P1^3; // 按钮3
sbit BTN4 = P1^4; // 按钮4
sbit BTN5 = P1^5; // 按钮5
sbit BTN6 = P1^6; // 按钮6
sbit BTN7 = P1^7; // 按钮7
sbit LED0 = P2^0; // LED0
sbit LED1 = P2^1; // LED1
sbit LED2 = P2^2; // LED2
sbit LED3 = P2^3; // LED3
sbit LED4 = P2^4; // LED4
sbit LED5 = P2^5; // LED5
sbit LED6 = P2^6; // LED6
sbit LED7 = P2^7; // LED7
void delay(unsigned int t)
{
unsigned int i, j;
for(i=0; i<t; i++)
for(j=0; j<125; j++);
}
void main()
{
unsigned char num1 = 0, num2 = 0, result = 0;
unsigned char op = 0; // 运算符
while(1)
{
if(BTN0 == 0) // 按钮0按下
{
num1 = 0;
num2 = 0;
result = 0;
op = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
while(BTN0 == 0); // 等待按钮释放
}
else if(BTN1 == 0) // 按钮1按下
{
if(op == 0) // 如果还没有选择运算符
{
num1 = num1 * 10 + 1;
LED0 = 1;
}
else
{
num2 = num2 * 10 + 1;
LED4 = 1;
}
while(BTN1 == 0); // 等待按钮释放
}
else if(BTN2 == 0) // 按钮2按下
{
if(op == 0)
{
num1 = num1 * 10 + 2;
LED1 = 1;
}
else
{
num2 = num2 * 10 + 2;
LED5 = 1;
}
while(BTN2 == 0);
}
else if(BTN3 == 0) // 按钮3按下
{
if(op == 0)
{
num1 = num1 * 10 + 3;
LED2 = 1;
}
else
{
num2 = num2 * 10 + 3;
LED6 = 1;
}
while(BTN3 == 0);
}
else if(BTN4 == 0) // 按钮4按下
{
if(op == 0)
{
num1 = num1 * 10 + 4;
LED0 = 1;
LED2 = 1;
}
else
{
num2 = num2 * 10 + 4;
LED4 = 1;
LED6 = 1;
}
while(BTN4 == 0);
}
else if(BTN5 == 0) // 按钮5按下
{
if(op == 0)
{
num1 = num1 * 10 + 5;
LED1 = 1;
LED3 = 1;
}
else
{
num2 = num2 * 10 + 5;
LED5 = 1;
LED7 = 1;
}
while(BTN5 == 0);
}
else if(BTN6 == 0) // 按钮6按下
{
if(op == 0)
{
num1 = num1 * 10 + 6;
LED2 = 1;
LED3 = 1;
}
else
{
num2 = num2 * 10 + 6;
LED6 = 1;
LED7 = 1;
}
while(BTN6 == 0);
}
else if(BTN7 == 0) // 按钮7按下
{
if(op == 0) // 如果还没有选择运算符
{
op = 1;
LED7 = 1; // 在LED7上显示运算符“+”
}
else // 如果已经选择运算符
{
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;
}
// 显示结果
if(result >= 100)
{
LED0 = 1;
LED1 = 1;
}
if(result >= 10)
{
LED2 = 1;
LED3 = 1;
}
LED4 = 1;
LED5 = 1;
LED6 = 1;
while(BTN7 == 0);
delay(500); // 延时一段时间
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 0;
LED5 = 0;
LED6 = 0;
LED7 = 0;
num1 = 0;
num2 = 0;
result = 0;
op = 0;
}
while(BTN7 == 0);
}
}
}
```
这个程序实现了加法、减法、乘法和除法运算,可以通过LED灯在单片机上显示结果。您可以根据需要进行修改和扩展。