#include <Wire.h>
#include <Keypad.h> // 引用Keypad程式庫
#include <LiquidCrystal_I2C.h> // LiquidCrystal I2C by Marco Schwartz https://github.com/marcoschwartz/LiquidCrystal_I2C
LiquidCrystal_I2C lcd(0x27, 16, 2);
const byte rows = 4; // 按键行数
const byte cols = 4; // 按键列数
// 依照行、列排列的按鍵字元(二维数组)
char keymap[][cols] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', '=', '/'}};
byte rowPins[] = {9, 8, 7, 6}; // 设定行引脚
byte colPins[] = {5, 4, 3, 2}; // 设定列引脚
Keypad myKeypad = Keypad(makeKeymap(keymap), rowPins, colPins, rows, cols);
void setup()
{
Serial.begin(9600);
lcd.init(); // 初始化LCD
lcd.backlight(); // 设置LCD背景等亮
lcd.setCursor(0, 0); // 设置显示指针(第0列,第0行)
}
double firstNum = 0; // 运算符左边的数
long secondNum = 0; // 运算符右边的数
bool isFirstNum = true; // 是否是运算符左边的数
char operatr = ' '; // 保存运算符
void loop()
{
// 阻塞等待按键被按下,返回按下的键,getKey()为非阻塞返回按下的键
char key = myKeypad.waitForKey();
if (key != NO_KEY)
{
if (key == 'C' || operatr == 'C')
{
firstNum = 0;
secondNum = 0;
isFirstNum = true;
operatr = ' ';
lcd.clear();
lcd.setCursor(0, 0);
}
if ('0' <= key && key <= '9')
{
if (isFirstNum)
{
firstNum = firstNum * 10 + key - '0';
}
else
{
secondNum = secondNum * 10 + key - '0';
}
lcd.print(key);
}
if (key == '+' || key == '-' || key == '*' || key == '/' || key == '=')
{
if (firstNum != 0.0 || key != '/')
{
switch (operatr)
{
case '+':
firstNum += secondNum;
break;
case '-':
firstNum -= secondNum;
break;
case '*':
firstNum *= secondNum;
break;
case '/':
firstNum /= secondNum;
break;
}
if (key == '=')
{
lcd.setCursor(0, 1);
lcd.print("=");
lcd.print(firstNum);
operatr = 'C';
}
else
{
operatr = key;
secondNum = 0;
isFirstNum = false;
lcd.print(key);
}
}
}
}
}