I have written a simple calculator program for an LCD keypad shield. It works fine except for the multiplication case. It gives me zero. However, I have noticed that when I enclose the expression num1 * num2 in parenthesis it does work. Why is that so?
#include <LiquidCrystal.h>
LiquidCrystal lcd (8, 9, 4, 5, 6, 7);
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
lcd.clear();
}
void loop() {
float ans = 0;
lcd.print("Starting Calc");
delay(500);
lcd.clear();
lcd.print("Enter 1st Num");
while (Serial.available() == 0) {}
float num1 = Serial.parseFloat();
lcd.clear();
lcd.print("Enter 2nd Num");
while (Serial.available () == 0) {}
float num2 = Serial.parseFloat();
lcd.clear();
lcd.print("Enter Operator");
lcd.setCursor(0, 1);
lcd.print(" R+, U*, D/, L- ");
int val = analogRead(A0);
while (val > 1000) {
val = analogRead(A0);
}
if (val == 0) { // addition
ans = num1 + num2;
}
if (val >= 97 && val <= 98) { // multiplication
ans = num1 * num2;
}
if (val >= 253 && val <= 254) { // division
ans = num1 / num2;
}
if (val >= 407 && val <= 408) { // subtraction
ans = num1 - num2;
}
lcd.clear();
lcd.print("Answer is = ");
lcd.print(ans);
delay(2000);
}
Modified Code
#include <LiquidCrystal.h>
LiquidCrystal lcd (8, 9, 4, 5, 6, 7);
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
lcd.clear();
}
void loop() {
float ans = 0.0;
lcd.print("Starting Calc");
delay(500);
lcd.clear();
lcd.print("Enter 1st Num");
while (Serial.available() == 0) {}
float num1 = Serial.parseFloat();
lcd.clear();
lcd.print("Enter 2nd Num");
while (Serial.available () == 0) {}
float num2 = Serial.parseFloat();
lcd.clear();
lcd.print("Enter Operator");
lcd.setCursor(0, 1);
lcd.print(" R+, U*, D/, L- ");
// here we split our logic.. first repeatedly read input value until valid operator read
// secondly we perform the arithmetic operation accordingly
char input = ' '; // space = no operator read so far
int val;
do {
val = analogRead(A0);
// see how if statements are written concisely for readability
// if only one statement after condition you can skip curly brackets
if (val == 0) input = '+';
if (val >= 97 && val <= 98) input = '*';
if (val >= 253 && val <= 254) input = '/';
if (val >= 407 && val <= 408) input = '-';
} while (input == ' ');
Serial.println(input);
Serial.println(num1);
Serial.println(num2);
delay(1000);
// perform arithmetic operation
switch (val) { // not written in a standard way but very readable
case '+': ans = num1 + num2; break;
case '-': ans = num1 - num2; break;
case '*': ans = num1 * num2; break;
case '/': ans = num1 / num2; break;
}
lcd.clear();
lcd.print("Answer = ");
lcd.print(ans);
delay(2000);
}