// Simple Calculator using Arduino and Serial Communication
float operand1, operand2, result;
char operation;
void setup() {
Serial.begin(9600);
}
void loop() {
// Wait for user input
while (!Serial.available()) {
// Do nothing while waiting for input
}
// Read the first operand
operand1 = Serial.parseFloat();
Serial.print("Enter operation (+, -, *, /): ");
// Wait for user input
while (!Serial.available()) {
// Do nothing while waiting for input
}
// Read the operation
operation = Serial.read();
Serial.print("Enter the second operand: ");
// Wait for user input
while (!Serial.available()) {
// Do nothing while waiting for input
}
// Read the second operand
operand2 = Serial.parseFloat();
// Perform the calculation based on the operation
switch (operation) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if (operand2 != 0) {
result = operand1 / operand2;
} else {
Serial.println("Error: Division by zero");
continue; // Skip the rest of the loop if division by zero
}
break;
default:
Serial.println("Error: Invalid operation");
continue; // Skip the rest of the loop if an invalid operation
}
// Display the result
Serial.print("Result: ");
Serial.println(result, 4); // Display result with 4 decimal places
}