I'm trying to make a basic calculator with the Serial monitor but it doesn't seem to work.
int a;
int b;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available()) {
Serial.println("First Number: ");
a = Serial.read();
Serial.println("Second Number: ");
b = Serial.read();
Serial.println(a + b);
}
}
asked Apr 30, 2016 at 3:36
1 Answer 1
Serial.read() reads in only the first byte of the data from the serial.This is not what we want, We everything that the user has entered to be treated as an Integer and then read it into the variables. You should use Serial.parseInt() for the job.
See the modified program below:
int a;
int b;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
Serial.println("Enter the First number");
while(!Serial.available()); // wait till the user has entered something
a = Serial.parseInt(); // treat what the user has entered as an Integer and read the whole number
Serial.println("Enter the second number");
while(!Serial.available());
b = Serial.parseInt();
Serial.println(a+b); // Print the sum
}
lang-cpp