Haciendo una calculadora usando un teclado matricial en Tinkercad
En tinkercad hacer uso de los siguientes elementos:
- Arduino UNO
- Teclado matricial 4X4
- 1 resistencia 220 K Ohms
- LCD 16 x 2
Armar el circuito como se especifica en la siguiente imagen y probar este código, el cual es una calculadora con las 4 operaciones básicas.
#include <Keypad.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
long first = 0;
long second = 0;
double total = 0;
char customKey;
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'C','0','=','/'}
};
byte rowPins[ROWS] = {7,6,5,4}; // Asignamos a las filas los pinouts correspondientes
byte colPins[COLS] = {3,2,1,0}; //Asignamos a las columnas los pinouts correspondientes
//Instanciamos la clase NewKeypad
Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup()
{
lcd.begin(16, 2); // start lcd
lcd.setCursor(0,0);
lcd.print("Calculadora CSI");
lcd.setCursor(0,1);
delay(4000);
lcd.clear();
lcd.setCursor(0, 0);
}
void loop()
{
customKey = customKeypad.getKey();
switch(customKey)
{
case '0' ... '9': // Seleccionamos los valores del 0 al 9 de nuestro teclado.
lcd.setCursor(0,0);
first = first * 10 + (customKey - '0');
lcd.print(first);
break;
case '+':
first = (total != 0 ? total : first);
lcd.setCursor(0,1);
lcd.print("+");
second = SecondNumber(); // Obtengo el segundo numero
total = first + second;
lcd.setCursor(0,3);
first = 0, second = 0; // Inicializamos los valores
lcd.print(total);
break;
case 'C':
total = 0;
lcd.clear();
break;
case '-':
first = (total != 0 ? total : first);
lcd.setCursor(0,1);
lcd.print("-");
second = SecondNumber(); // Obtengo el segundo numero
total = first - second;
lcd.setCursor(0,3);
first = 0, second = 0; // Inicializamos los valores
lcd.print(total);
break;
case '*':
first = (total != 0 ? total : first);
lcd.setCursor(0,1);
lcd.print("*");
second = SecondNumber(); // Obtengo el segundo numero
total = first * second;
lcd.setCursor(0,3);
first = 0, second = 0; // Inicializamos los valores
lcd.print(total);
break;
case '/':
first = (total != 0 ? total : first);
lcd.setCursor(0,1);
lcd.print("/");
second = SecondNumber(); // Obtengo el segundo numero
total = first / second;
lcd.setCursor(0,3);
first = 0, second = 0; // Inicializamos los valores
lcd.print(total);
break;
}
}
long SecondNumber()
{
while( 1 )
{
customKey = customKeypad.getKey();
if(customKey >= '0' && customKey <= '9')
{
second = second * 10 + (customKey - '0');
lcd.setCursor(0,2);
lcd.print(second);
}
if(customKey == '=') break;
}
return second;
}
Comentarios
Publicar un comentario