利用矩阵按键和LCD1602实现计算器功能(加减除、十进制和二进制转换) 注:除法运算结果显示保留两位小数
时间: 2024-02-15 12:02:30 浏览: 32
下面是一个简单的示例代码,实现了加减乘除和十进制、二进制之间的转换,并且在除法运算时保留两位小数。这份代码主要使用了 Arduino 的 LiquidCrystal 库。
```c
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int operand1 = 0;
int operand2 = 0;
char operatorSymbol = '+';
bool isBinaryMode = false;
void setup() {
lcd.begin(16, 2);
lcd.print("Calculator");
delay(1000);
lcd.clear();
}
void loop() {
int key = getKeyPressed();
if (key != -1) {
if (key >= 0 && key <= 9) {
if (operatorSymbol == '=') {
clearResult();
}
if (isBinaryMode) {
operand1 = operand1 * 2 + key;
} else {
operand1 = operand1 * 10 + key;
}
lcd.print(key);
} else if (key == 10) { // A: +
applyOperator('+');
} else if (key == 11) { // B: -
applyOperator('-');
} else if (key == 12) { // C: *
applyOperator('*');
} else if (key == 13) { // D: /
applyOperator('/');
} else if (key == 14) { // *
isBinaryMode = !isBinaryMode;
if (isBinaryMode) {
operand1 = convertToBinary(operand1);
} else {
operand1 = convertToDecimal(operand1);
}
clearResult();
lcd.setCursor(0, 1);
lcd.print(isBinaryMode ? "B" : "D");
} else if (key == 15) { // #
clearResult();
operand1 = 0;
operand2 = 0;
operatorSymbol = '+';
isBinaryMode = false;
}
}
}
int getKeyPressed() {
int key = -1;
int row = -1;
for (int i = 0; i < 4; i++) {
digitalWrite(i + 6, LOW);
for (int j = 0; j < 4; j++) {
if (digitalRead(j + 2) == LOW) {
row = i;
key = j + i * 4;
}
}
digitalWrite(i + 6, HIGH);
}
if (row != -1) {
return key;
} else {
return -1;
}
}
void applyOperator(char op) {
if (operatorSymbol == '=') {
operand1 = operand2;
}
operatorSymbol = op;
clearResult();
lcd.print(op);
}
void clearResult() {
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 1);
}
void displayResult(int result) {
if (isBinaryMode) {
lcd.print(String(result, BIN));
} else {
lcd.print(result);
}
}
int convertToBinary(int decimal) {
int binary = 0;
int base = 1;
while (decimal > 0) {
binary += (decimal % 2) * base;
decimal /= 2;
base *= 10;
}
return binary;
}
int convertToDecimal(int binary) {
int decimal = 0;
int base = 1;
while (binary > 0) {
decimal += (binary % 10) * base;
binary /= 10;
base *= 2;
}
return decimal;
}
void calculate() {
if (operatorSymbol == '+') {
operand2 = operand1;
} else if (operatorSymbol == '-') {
operand2 -= operand1;
} else if (operatorSymbol == '*') {
operand2 *= operand1;
} else if (operatorSymbol == '/') {
float result = (float) operand2 / (float) operand1;
clearResult();
lcd.print(result, 2);
delay(3000);
clearResult();
operand2 = (int) result;
}
displayResult(operand2);
operatorSymbol = '=';
}
```
其中,`getKeyPressed()` 函数用于读取矩阵按键的输入,返回值为按下的键的编号(0-15),如果没有按键按下则返回 -1。`applyOperator()` 函数用于应用运算符,根据当前的运算符和操作数进行相应的运算。`convertToBinary()` 和 `convertToDecimal()` 函数用于实现十进制和二进制之间的转换。`calculate()` 函数用于计算结果,并将结果显示在 LCD1602 显示器上。