//ENEL301-Lab1, 26-Jan-2023
//Xinyun Zhou (UCID: 30141745), Aarti Chandiramani (UCID: 30145899), Aileen Mulaw (30161059), Juhi Mehra (UCID: 30140435)
#include <LiquidCrystal.h>
#include <Keypad.h>
using namespace std;
//Connecting LCD to the Arduino with the corresponding pins
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
//Defining the pins as we connected then in the simulation
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
//Setting rows and columns of keypad
const byte ROWS = 4;
const byte COLS = 4;
//Defining the operation from each key in keypad
char keys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', '=', '/'}
};
//Connecting keypad to the Arduino with the corresponding pins
byte rowPins[ROWS] = {22, 23, 25, 27};
byte colPins[COLS] = {29, 31, 33, 35};
//Initializing keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
//The following sets up the assembly to run once
//Setting the size of the LCD (cols,rows)
lcd.begin(16,2);
//Printing to the screen
String intro = "Welcome to ENEL 301 Arduino Calculator";
lcd.print(intro);
//
Serial.begin(9600);
delay(1000);
for (int i=0; i<=(intro.length()-16); i++){
lcd.scrollDisplayLeft();
delay(250);
}
lcd.clear();
delay(700);
lcd.print( "A = +, B = -");
lcd.setCursor(0,1);
lcd.print( "C = *, D = /");
delay(2500);
lcd.clear();
lcd.print("* = Clear");
lcd.setCursor(0,1);
lcd.print( "# = Equal");
delay(2500);
lcd.clear();
delay(700);
lcd.print("Please press any");
lcd.setCursor(0,1);
lcd.print("keys to start");
}
//User-defined variables and functions
String to_print = "";
String temp = "";
long firstval = 0.0;
long secondval = 0.0;
long finalval = 0.0;
int n = 0;
char op;
bool operation = false;
void check_op(char input){
if ((input == '+') || (input == '-') || (input == '/') || (input == '*')){
operation = true;
}
else{
operation = false;
}
}
long calculate(char input){
if(input == '+')
return (firstval + secondval);
if(input == '*')
return (firstval * secondval);
if(input == '/'){
if(secondval == 0){
to_print = "Error";
return;
}
else
return (firstval / secondval);
}
if(input == '-')
return (firstval - secondval);
if(input == '=')
return firstval;
//Add other operations
}
void loop() {
//The following allows for repeatable use of program
//Sets the location of cursor
lcd.setCursor(16,2);
char button = keypad.getKey();
if (button != NO_KEY){
lcd.clear();
Serial.println(button);
check_op(button);
to_print += button;
temp += button;
if (button == '='){
if (firstval == 0 && n == 0){
firstval = temp.toInt();
op = button;
}
secondval = temp.toInt();
finalval = calculate(op);
}
lcd.print(to_print);
lcd.setCursor(0,1);
lcd.print(finalval);
if (operation == true){
op = button;
firstval = temp.toInt();
n = 1;
temp = "";
}
if (button == 'C' || button == '='){
firstval = 0.0;
secondval = 0.0;
finalval = 0.0;
temp = "";
to_print = "";
if (button == 'C') lcd.clear();
}
}
}