3

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

5

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
}
answered Apr 30, 2016 at 4:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.