Arduino question

Hi! :slight_smile: I’m new to the Arduino world and recently I created this dog age calculator:

float dogAge;
float humanAge;

void setup() {

void loop(){
Serial.println(“Enter your dog’s age”); //prompt the user for input
while(Serial.available()==0){} // wait
dogAge = Serial.parseFloat(); //read input
humanAge = (7)* dogAge; //calculate human age
Serial.println(" Your dog is “); //print result
Serial.println(” years old, in human age.");

It works all right at first , but then the serial port goes crazy and prints :“your dog is 00 years old, in human age.” without me having written any input, then it asks the question again and works fine. This repeats over time, What is the reason? Thanks for your time

When you type something on the terminal, like "15", you are also sending a newline '\n' which parseFloat() does not use so the next time through the loop(), Serial.available() is still not equal to 0 and the second parseFloat() returns 0.

To debug, you should try reading/printing how many characters are available after parseFloat() and adjust your code to read/discard/use them.

There may be one or none characters available after parseFloat(). The Serial Monitor may still be sending a '\r' character, depending on the line-ending option chosen at the bottom of the window.

The simple way is to detect zeros since nobody should enter a zero and simply ignore them. Don't print anything.

What does it do for negative numbers entered? What should it do?

Hi Newbie Jorge! Please read the instructions about how to post your code using tags. Thanks.

As @blh64 mentioned, if your code does not explicitly read the entire input buffer, you may need to clear it before attempting the next read. This is easily done by reading until it is empty:


You can put it in an inline function:

inline void serial_flush() {while(Serial.available());}

or a macro,

define serial_flush() (while(Serial.available());)

and then make a call to serial_flush() anytime you need to.

Yes, but at the logical point where you would want to call this flush macro, the trailing newline has not arrived yet.

Serial is S. L. O. W.

Fair enough. Caught out by the smilies. There is a difference however, between posting code intended to be copied and tested and offering up suggestions. While technically you are correct, in my own defense you Honour, I was nor really posting code, just a shorthand version of what may have otherwise been a long and convoluted explanation. You're not a lawyer by any chance?