#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
// Inicializar LCD con dirección I2C 0x27 (puede ser 0x3F en algunos casos)
LiquidCrystal_I2C lcd(0x27, 16, 2); // pines A4 y A5
// Definir la matriz del teclado
const byte FILAS = 4;
const byte COLUMNAS = 4;
char teclas[FILAS][COLUMNAS] = {
{'1', '2', '3', '/'},
{'4', '5', '6', '*'},
{'7', '8', '9', '-'},
{'C', '0', '=', '+'}
};
byte pinesFilas[FILAS] = {9, 8, 7, 6};
byte pinesColumnas[COLUMNAS] = {5, 4, 3, 2};
// Inicializar teclado
Keypad teclado = Keypad(makeKeymap(teclas), pinesFilas, pinesColumnas, FILAS, COLUMNAS);
// Variables para almacenar los números y operación
String num1 = "";
String num2 = "";
char operacion = '\0';
bool ingresandoSegundo = false;
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Calculadora");
delay(2000);
lcd.clear();
}
void loop() {
char tecla = teclado.getKey();
if (tecla) {
if (isdigit(tecla)) { // Si es un número
if (ingresandoSegundo) {
num2 += tecla;
} else {
num1 += tecla;
}
lcd.print(tecla);
}
else if (tecla == '+' || tecla == '-' || tecla == '*' || tecla == '/') { // Si es un operador
if (num1 != "") {
operacion = tecla;
ingresandoSegundo = true;
lcd.print(tecla);
}
}
else if (tecla == '=') { // Si es el igual
if (num1 != "" && num2 != "" && operacion != '\0') {
float resultado = calcular(num1.toFloat(), num2.toFloat(), operacion);
lcd.setCursor(0, 1);
lcd.print("= ");
lcd.print(resultado);
delay(3000);
reset();
}
}
else if (tecla == 'C') { // Si se presiona "C", se borra todo
reset();
}
}
}
// Función para realizar la operación
float calcular(float a, float b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return (b != 0) ? a / b : 0; // Evita la división por cero
default: return 0;
}
}
// Función para reiniciar la calculadora
void reset() {
num1 = "";
num2 = "";
operacion = '\0';
ingresandoSegundo = false;
lcd.clear();
}