#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
// 设置 I2C LCD 的地址和尺寸
LiquidCrystal_I2C lcd(0x27, 16, 2);
// 设置 4x4 薄膜按键的行和列
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'.','0','=','/'}
};
byte rowPins[ROWS] = {5, 4, 3, 2};
byte colPins[COLS] = {A3, A2, A1, A0};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String input = ""; // 保存用户输入
float result = 0; // 计算结果
char operation = 0; // 保存操作符
bool newCalculation = true;
unsigned long lastEqualPress = 0;
int cursorPos = 0; // 记录当前光标的位置
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Calculator");
delay(2000);
lcd.clear();
cursorPos = 0; // 初始化光标位置
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key >= '0' && key <= '9' || key == '.') {
if (newCalculation) {
input = ""; // 新计算时清空输入
newCalculation = false;
cursorPos = 0; // 重置光标位置
lcd.clear();
}
input += key;
lcd.print(key); // 显示当前输入的数字或小数点
cursorPos++; // 更新光标位置
}
else if (key == '+' || key == '-' || key == '*' || key == '/') {
calculate();
operation = key;
input = "";
cursorPos = result >= 1000000000 ? 2 : 1; // 设置光标位置, 根据结果的长度调整位置
lcd.setCursor(0, 0);
lcd.print(result);
lcd.setCursor(cursorPos, 0); // 将光标移到运算符后面
lcd.print(" ");
lcd.print(operation);
cursorPos++; // 更新光标位置
}
else if (key == '=') {
unsigned long now = millis();
if (now - lastEqualPress < 500) { // 检测双击
input = "";
result = 0;
operation = 0;
lcd.clear();
newCalculation = true;
cursorPos = 0; // 重置光标位置
} else {
calculate();
lcd.setCursor(0, 1);
lcd.print("Result:");
lcd.setCursor(8, 1);
lcd.print(result);
newCalculation = true;
}
lastEqualPress = now;
}
}
}
void calculate() {
if (input != "") {
float currentValue = input.toFloat();
if (operation == '+') result += currentValue;
else if (operation == '-') result -= currentValue;
else if (operation == '*') result *= currentValue;
else if (operation == '/') {
if (currentValue != 0) result /= currentValue;
else lcd.print("Err:Div/0");
} else {
result = currentValue;
}
}
}