89c51单片机简易计算器
时间: 2023-10-06 09:14:23 浏览: 239
实现一个简易的计算器,可以使用 89c51 单片机和一些基本的电子元件。
首先,需要连接一个 16x2 LCD 显示器,用于显示计算器的输入和输出。然后,需要连接一些按钮,用于输入数字和操作符。这些按钮可以使用矩阵键盘或单独的按钮连接到单片机的 GPIO 引脚上。
接下来,需要编写程序来读取按钮输入和显示结果。程序应该能够处理加、减、乘、除四种基本的数学运算,并能够处理小数点和清除输入。
以下是一个简单的代码示例:
```c
#include <reg51.h>
#define LCD_RS P1_0
#define LCD_RW P1_1
#define LCD_E P1_2
#define LCD_D4 P1_3
#define LCD_D5 P1_4
#define LCD_D6 P1_5
#define LCD_D7 P1_6
void delay(unsigned int ms) {
unsigned int i, j;
for (i = 0; i < ms; i++) {
for (j = 0; j < 120; j++) {
// do nothing
}
}
}
void lcd_cmd(unsigned char cmd) {
LCD_RS = 0;
LCD_RW = 0;
LCD_E = 1;
LCD_D4 = cmd >> 4;
LCD_D5 = cmd >> 5;
LCD_D6 = cmd >> 6;
LCD_D7 = cmd >> 7;
delay(1);
LCD_E = 0;
delay(1);
LCD_D4 = cmd & 0x0F;
LCD_D5 = (cmd & 0x1F) << 1;
LCD_D6 = (cmd & 0x3F) << 2;
LCD_D7 = (cmd & 0x7F) << 3;
delay(1);
LCD_E = 1;
delay(1);
LCD_E = 0;
delay(1);
}
void lcd_data(unsigned char data) {
LCD_RS = 1;
LCD_RW = 0;
LCD_E = 1;
LCD_D4 = data >> 4;
LCD_D5 = data >> 5;
LCD_D6 = data >> 6;
LCD_D7 = data >> 7;
delay(1);
LCD_E = 0;
delay(1);
LCD_D4 = data & 0x0F;
LCD_D5 = (data & 0x1F) << 1;
LCD_D6 = (data & 0x3F) << 2;
LCD_D7 = (data & 0x7F) << 3;
delay(1);
LCD_E = 1;
delay(1);
LCD_E = 0;
delay(1);
}
void lcd_init() {
lcd_cmd(0x33);
lcd_cmd(0x32);
lcd_cmd(0x28);
lcd_cmd(0x0C);
lcd_cmd(0x06);
lcd_cmd(0x01);
delay(10);
}
unsigned char read_key() {
unsigned char key = 0xFF;
unsigned char row, col;
for (row = 0; row < 4; row++) {
P2 = ~(1 << row);
col = P2 & 0x0F;
if (col != 0x0F) {
key = row * 4 + col;
break;
}
}
return key;
}
unsigned char get_digit() {
unsigned char digit = 0;
while (1) {
unsigned char key = read_key();
if (key != 0xFF) {
if (key == 0x0D) { // enter
break;
} else if (key == 0x0C) { // clear
digit = 0;
break;
} else if (key >= 0x00 && key <= 0x09) { // 0-9
digit = digit * 10 + (key & 0x0F);
lcd_data(key + '0');
} else if (key == 0x0A) { // .
lcd_data('.');
}
while (read_key() != 0xFF) {
// wait for key release
}
}
}
return digit;
}
unsigned char get_operator() {
unsigned char op = 0;
while (1) {
unsigned char key = read_key();
if (key != 0xFF) {
if (key == 0x0D) { // enter
break;
} else if (key == 0x0C) { // clear
op = 0;
break;
} else if (key == 0x0B) { // +
op = '+';
lcd_data('+');
} else if (key == 0x07) { // -
op = '-';
lcd_data('-');
} else if (key == 0x03) { // *
op = '*';
lcd_data('*');
} else if (key == 0x06) { // /
op = '/';
lcd_data('/');
}
while (read_key() != 0xFF) {
// wait for key release
}
}
}
return op;
}
void main() {
lcd_init();
lcd_cmd(0x80);
while (1) {
unsigned char a = get_digit();
unsigned char op = get_operator();
unsigned char b = get_digit();
lcd_cmd(0xC0);
if (op == '+') {
lcd_data(a + b);
} else if (op == '-') {
lcd_data(a - b);
} else if (op == '*') {
lcd_data(a * b);
} else if (op == '/') {
lcd_data(a / b);
} else {
lcd_data('E');
}
while (read_key() != 0xFF) {
// wait for key release
}
}
}
```
这段代码实现了一个简单的计算器,可以通过矩阵键盘输入数字和操作符,并在 LCD 显示器上显示结果。需要注意的是,这个计算器并没有处理优先级和括号等复杂的数学运算,只能处理两个数字之间的基本四则运算。
阅读全文