#include <LiquidCrystal.h>
#include <Keypad.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'C','0','#','/'}
};
byte rowPins[ROWS] = {37, 39, 41, 43}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {45, 47, 49, 51}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
int num = 1;
long n1 = 0;
long n2 = 0;
int clear = 0;
long result;
char op;
int opcount = 0;
void setup() {
lcd.begin(16,2);
Serial.begin(9600);
}
void loop() {
char key = keypad.getKey();
if(key){
// check if key pressed is a number
if(key != '+' && key != '-' && key != '*' && key != '/' && key != 'C' && key != '#'){
if (clear == 1){ //quick check to see if the screen needs to be cleared first
lcd.clear();
clear = 0;
}
lcd.print(key); //prints the number
if(num == 1){ //checks if were typing the first number or second number
n1 = n1*10 + (key - '0'); //adds the number inputted to the overall number
}else{
n2 = n2*10 + (key - '0');
}
}
else if(key == '#'){ //compute the result
clear = 1; //sets clear to 1 to clear the screen on next input
num = 1; //sets the number being edited by input back to the first number
//compute the result of the input operation
if(op == '+'){
result = n1 + n2;
}
else if(op == '-'){
result = n1 - n2;
}
else if(op == '*'){
result = n1 * n2;
}
else if(op == '/'){
if(n2 != 0){ //making sure no dividing by zero
result = n1 / n2;
}
else{
lcd.clear();
lcd.print("ERR: DIV BY 0");
}
}
if(n2 == 0 && op == '/'){ //checking if we divided by zero to choose what to print
//do nothing: error message already taken care of
}
else{
lcd.setCursor(0,1);
lcd.print("= ");
if(opcount == 1){ //if only one operator entered
lcd.print(result);
}
else if(opcount == 0){ //if no operators entered, just reprint what the first number is
lcd.print(n1);
}
else{ //more than 1 operator entered, throw an error
lcd.clear();
lcd.setCursor(0,0);
lcd.print("ERR: >1 OPS");
}
lcd.setCursor(0,0); //make sure the cursor is in the right spot
}
//reseting the numbers and variables
n1 = 0;
n2 = 0;
opcount = 0;
op = ' ';
}
else if(key == 'C'){ //clearing the screen and resetting all data
lcd.clear();
n1 = 0;
n2 = 0;
num = 1;
opcount = 0;
op = ' ';
clear = 0; //make sure the screen doesnt get recleared by accident
}
else{ //key press is an operator
if (clear == 1){ //clearing the screen if necessary
lcd.clear();
clear = 0;
}
lcd.print(key);
num = 2; //changing the number being edited
op = key; //setting the operator
opcount += 1;
}
}
}