I've searched this forum so I'm sorry if this has already been answered, but I'm just getting my feet wet with the Arduino Uno and C++ and right now I'm trying to create a basic calculator using the IDE Serial Monitor. My code so far is below. Everything works great, but if I use a "non-approved" operator (i.e. not +, -, *, /, or ^) it still prints the Serial.print(num1); Serial.print(calc); Serial.print(num2); Serial.print("="); Serial.println(result); after the default from the switch in the calculation.
Is there a way to insert an If statement, or something similar, into the loop so it wont print the calculation steps if the output of the switch is it's default?
float num1;
float num2;
char calc;
float result;
void setup() {
Serial.begin(9600);
Serial.println("What would you like to calculate?");
}
void loop() {
while(Serial.available() > 0) {
num1 = Serial.parseFloat();
calc = Serial.read();
num2 = Serial.parseFloat();
calculation();
Serial.print(num1);
Serial.print(calc);
Serial.print(num2);
Serial.print("=");
Serial.println(result);
}
}
void calculation() {
switch (calc) {
case '+' :
result = num1 + num2;
break;
case '-' :
result = num1 - num2;
break;
case '*' :
result = num1 * num2;
break;
case '/' :
result = num1 / num2;
break;
case '^' :
result = pow(num1, num2);
break;
default :
Serial.println("You did not enter +, -, *, /, or ^");
}
}