#include <Wire.h> // Библиотека для I2C
#include <LiquidCrystal_I2C.h> // Библиотека для I2C LCD
#include <Keypad.h> // Библиотека для работы с матричной клавиатурой
// Настройка I2C LCD
LiquidCrystal_I2C lcd(0x27, 16, 2); // Адрес 0x27, если другой адрес - измените
// Настройка матричной клавиатуры
const byte ROWS = 4; // 4 строки
const byte COLS = 4; // 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] = {A5, A4, A3, A2}; // Пины столбцов, к которым подключена клавиатура
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const int ClearBTN = 8; // Пин для кнопки очистки экрана
uint64_t value = 0;
void setup() {
Serial.begin(115200);
lcd.init(); // Инициализация LCD
lcd.backlight(); // Включение подсветки
lcd.clear(); // Очистка экрана
pinMode(ClearBTN, INPUT_PULLUP); // Настройка пина кнопки очистки как вход с подтяжкой
}
void updateCursor() {
if (millis() / 250 % 2 == 0 ) {
lcd.cursor();
} else {
lcd.noCursor();
}
}
// Переменные для хранения операций и чисел
char operation = 0;
String memory = "";
String current = "";
uint64_t currentDecimal;
bool decimalPoint = false;
// Функция для выполнения вычислений
double calculate(char operation, double left, double right) {
switch (operation) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
}
}
// Функция обработки ввода с клавиатуры
void processInput(char key) {
if ('-' == key && current == "") {
current = "-";
lcd.print("-");
return;
}
switch (key) {
case '+':
case '-':
case '*':
case '/':
if (!operation) {
memory = current;
current = "";
}
operation = key;
lcd.setCursor(0, 1);
lcd.print(key);
lcd.setCursor(current.length() + 1, 1);
return;
case '=':
float leftNum = memory.toDouble();
float rightNum = current.toDouble();
memory = String(calculate(operation, leftNum, rightNum));
current = "";
lcd.clear();
lcd.setCursor(1, 0);
lcd.print(memory);
lcd.setCursor(0, 1);
lcd.print(operation);
return;
}
if ('.' == key && current.indexOf('.') >= 0) {
return;
}
if ('.' != key && current == "0") {
current = String(key);
} else if (key) {
current += String(key);
}
lcd.print(key);
}
// Основной цикл
void loop() {
updateCursor();
char key = keypad.getKey();
if (key) {
processInput(key);
}
// Проверка состояния кнопки очистки
if (digitalRead(ClearBTN) == LOW) {
lcd.clear();
memory = "";
current = "";
operation = 0;
}
}