利用矩阵按键和LCD1602实现计算器功能(加减除、十进制和二进制转换) 注:除法运算结果显示保留两位小数
时间: 2024-02-15 14:02:45 浏览: 67
好的,我来为你提供一份基于Arduino的代码实现:
```c++
#include <LiquidCrystal.h>
// 定义LCD1602引脚
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
// 定义矩阵按键引脚
const int ROWS = 4;
const int COLS = 4;
int rowPins[ROWS] = {9, 8, 7, 6};
int colPins[COLS] = {13, 10, A5, A4};
char keys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'.', '0', '=', '/'}
};
// 定义计算器变量
float num1 = 0;
float num2 = 0;
float result = 0;
char op = '+';
bool isDecimal = false;
bool isBinary = false;
// 初始化LCD1602
void initLCD() {
lcd.begin(16, 2);
lcd.print("Calculator");
lcd.setCursor(0, 1);
lcd.print("by Arduino");
}
// 按键检测
char getKey() {
for (int i = 0; i < COLS; i++) {
pinMode(colPins[i], OUTPUT);
digitalWrite(colPins[i], LOW);
}
for (int i = 0; i < ROWS; i++) {
pinMode(rowPins[i], INPUT_PULLUP);
}
char key = 0;
for (int i = 0; i < ROWS; i++) {
if (digitalRead(rowPins[i]) == LOW) {
for (int j = 0; j < COLS; j++) {
if (digitalRead(rowPins[i]) == LOW) {
key = keys[i][j];
}
}
while (digitalRead(rowPins[i]) == LOW);
}
}
return key;
}
// 清空计算器
void clear() {
num1 = 0;
num2 = 0;
result = 0;
op = '+';
isDecimal = false;
isBinary = false;
lcd.clear();
}
// 显示结果
void showResult() {
lcd.clear();
if (isDecimal) {
lcd.print(result, 2);
} else if (isBinary) {
lcd.print((int)result, BIN);
} else {
lcd.print(result);
}
}
// 计算结果
void calculate() {
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
lcd.setCursor(0, 1);
lcd.print("Error!");
return;
}
result = num1 / num2;
break;
}
isDecimal = false;
isBinary = false;
if (result < 0) {
result = 0;
}
showResult();
}
// 主函数
void setup() {
initLCD();
}
void loop() {
char key = getKey();
if (key >= '0' && key <= '9') {
if (!isDecimal) {
num1 = num1 * 10 + (key - '0');
lcd.print(key);
} else {
num1 += (key - '0') / pow(10, lcd.printFloat(num1, 2));
}
} else if (key == '.') {
isDecimal = true;
lcd.print('.');
} else if (key == '+' || key == '-' || key == '*' || key == '/') {
op = key;
lcd.setCursor(0, 1);
lcd.print(op);
num2 = num1;
num1 = 0;
isDecimal = false;
} else if (key == '=') {
num2 = num1;
num1 = 0;
calculate();
} else if (key == 'C') {
clear();
} else if (key == 'B') {
isBinary = true;
result = num1;
showResult();
}
}
```
这段代码实现了基本的加减乘除和清空功能,以及十进制和二进制的转换功能。你可以根据自己的需求进行修改和扩展。
阅读全文