How to wait for serial input? and nothing is done with the serial input

Hello,

I have this small code I need to make for school (1st year electrical engineer). But i can seem to figure out how let the serial wait before I give it a new number.

the task: I need to make a code that makes it possible to count in the serial monitor 10 times. and it needs to keep adding up upon the last number.

here is the code:

int Number = 0;
int Sum = 0;
int Getal = 1;

void setup() {
 Serial.begin(9600);
}


void Get_Number() {
  Serial.println("Please insert you're next number: ");
  Getal++;
   while (Serial.available () == 0) { Number = Serial.read(); }    //het allereerste getal wat ingevoerd wordt en later als basis wordt gebruikt
}



void loop() {

while( Getal != 11) {
   Get_Number();

    Sum = Number + Sum;
    Serial.print( "Your number is now:");
    Serial.println (Number, DEC);
   delay(1000);
   }
  }

current situation:
I am able to upload the code, and then the serial monitor asks me to insert my 1st number (and waits), and when i enter '5' for example this happens:

Please insert you're next number: 
Your number is now:-1
Please insert you're next number: 
Your number is now:-1
Please insert you're next number: 
Your number is now:-1
Please insert you're next number: 
Your number is now:-1
Please insert you're next number: 
Your number is now:-1
Please insert you're next number: 
Your number is now:-1
Please insert you're next number: 
Your number is now:-1
Please insert you're next number: 
Your number is now:-1
Please insert you're next number: 
Your number is now:-1
Please insert you're next number: 
Your number is now:-1

nothing is done with the input and then i just keeps saying " Please insert you're next number:
Your number is now:-1 " for the next 9 times.

"Getal" is just another word for "Number" in Dutch. just to clarify!

    while (Serial.available() == 0)
    {
        Number = Serial.read();
    }  //het allereerste getal wat ingevoerd wordt en later als basis wordt gebruikt

Serial.read() returns -1 when there is nothing to read so Number will be set to -1. This will be repeated until Getl equals 11 so what your sketch is doing is expected behaviour

Change the while in Get_Nimber() to an if and change the test so that a new number is read only when Serial.available() tells you that there is something to read

a number is composed of multiple characters. For example if you type 420 you'll have sent the ASCII code for '4' followed by the ASCII code for '2' and then the ASCII code for '0'.

if you hit enter, depending how you configured the Serial monitor in the IDE (assuming this is what you use) you'll send some extra bytes like Carriage return and line feed.

for example try this code

void setup() {
  Serial.begin(115200);
  Serial.println(F("Type something and validate"));
}

void loop() {
  if (Serial.available()) {
    char c = Serial.read(); // get the character that was sent
    // print the HEX code for the character on 2 digits
    Serial.print("0x");
    if (c < 0x10) Serial.write('0');
    Serial.print(c, HEX);
    Serial.write('\t'); // add a tab and show the characters (interpret some of the non visible ones)
    switch (c) {
      case '\r': Serial.println("CR"); break;
      case '\n': Serial.println("LF"); break;
      case '\t': Serial.println("TAB"); break;
      case ' ' : Serial.println("SPACE"); break;
      default  : Serial.println(c); break;
    }
  }
}

and type something in the Serial monitor (set at 115200 bauds)

this will show you the byte stream you get.

➜ you need to first write a code that is able to receive multiple bytes and parse that as one number.

I would suggest to study Serial Input Basics to handle this

Then If you need to receive 10 numbers, you have another to call this function to receive a number until you got the 10 numbers.

1 Like

@jasper1234567890

You wish to enter 5 (for example) from the InputBox of the Serial Monitor and then the OutputBox of Serial Monitor should show the following pattern at 1-sec interval -- correct?

5 6 7 8 9 10 11 12 13 14

look this over

int sum;

void
loop (void)
{
    if (Serial.available ())  {
        char buf [90];
        int n = Serial.readBytesUntil ('\n', buf, sizeof(buf)-1);
        buf [n] = '\0';

        if ('z' == buf [0])
            sum = 0;
        else {
            int val = atoi (buf);
            sum += val;
            Serial.print (val);
            Serial.print (" ");
            Serial.println (sum);
        }
    }
}

void
setup (void)
{
    Serial.begin (9600);
}

no, like this: (everything that is thick printed is my input)

5
6
Your Number: 11
1
Your Number: 11+1 (12)
9
Your Number: 21

etc.

for the rest of you guys that posted something, thank you! i will try to study those post and try to get it working. and i will report back if i have any new questions!

1 Like

Please, note the following points (also few are mentioned in post #3 @J-M-L) with respect to reeceiving a data item (for example: 23) from the InputBox of Serial Monitor by Arduino UNO. (Assume that you have selected Newline option in the Line ending box of Serial Monitor as termination character.)

1. You enter 23 (for example) in the InputBox and click on the Send Button of the Serial Monitor, the following ASCII discrete data items (the ASCII Codes of 2 3 Newline) travels towards Arduino one after another in bit form.

0x32 0x33 0x0A
(Hex codes are written for convenience, space for clarity)

2. The data items (also called frames) are automatically received by UNO and are saved in a FIFO type Serial Buffer in the background on interrupt basis.

3. Depending on the Baud Rate (Bd), the frames will take some definite amount of time to arrive at UNO and get saved in the Serial Buffer.

4. It is normal idea to check that the Serial Buffer contains at least one data item before making an attempt to read a character/data from the Buffer. This is done by executing the following code:

byte n = Serial.available();
if(n != 0)  //Serial Buffer contains at least one character
{
      char ch = Serial.read();
}

5. Multiple data items are saved in a null-character terminated char type array and then the atoi() function is applied to convert the array content into a single data item.

6. The following sketch is testd for five entries:

byte numCounter = 0;
int numAdd = 0;
char myData [20];

void setup()
{
  Serial.begin(9600);
  Serial.print("Enter your first max 2-digit number: ");
}

void loop()
{
  byte n = Serial.available();
  if (n != 0)
  {
    byte m = Serial.readBytesUntil('\n', myData, sizeof myData - 1);
    myData[m] = '\0'; //adding null character
    int myNum = atoi(myData); //converting ASCII coded discrete data items into a single data item
    Serial.println(myNum);
    numAdd = numAdd + myNum;
    Serial.println(numAdd);
    //-------------------
    numCounter++;
    if (numCounter == 5)
    {
      while (true);
    }
    Serial.print("Enter next max 2-digit number to add: ");
  }
}

7. Output:

Enter your first max 2-digit number: 5
5
Enter next max 2-digit number to add: 6
11
Enter next max 2-digit number to add: 24
35
Enter next max 2-digit number to add: 15
50
Enter next max 2-digit number to add: 1
51

We analyzed your code and came up with this:

Problems in Your Code:

  1. Incorrect Use of Serial.read():
    Serial.read() reads a single byte from the input buffer, returning an ASCII value of the character, not the actual number. The line:
while (Serial.available() == 0) { Number = Serial.read(); }

has two main issues:

  • The while loop waits until data is available but immediately tries to read a value even when Serial.available() is still 0.
  • Serial.read() reads only one character at a time, and because it's inside the while loop, the assignment Number = Serial.read(); only executes once data is available, which is incorrect.
  1. Increments Getal Unnecessarily:
    The line Getal++; increases Getal every time Get_Number() is called, which may not be necessary depending on your logic.
  2. No Handling of User Input as a String:
    Reading numbers directly from Serial.read() without converting input properly leads to logical errors, especially for multi-digit numbers.
int Number = 0;
int Sum = 0;
int Getal = 1;

void setup() {
  Serial.begin(9600);
}

void loop() {
  Get_Number();
}

void Get_Number() {
  Serial.println("Please insert your next number: ");
  
  // Wait for input , This will block the code
  while (Serial.available() == 0) {
    // Do nothing, just wait
  }

  // Read the input as a string, and then convert string to int.
  String input = Serial.readStringUntil('\n'); // Reads until newline character
  Number = input.toInt(); // Convert the input string to an integer
  
  Serial.print("You entered: ");
  Serial.println(Number);  // Display the ASCII number read as an integer

  // Additional code can be added here based on what you want to do with Number
}

** We did the following Changes Because:**

  1. Serial.readStringUntil('\n'):
    This reads the input from the Serial Monitor as a complete string until the Enter key (\n) is pressed, ensuring you capture multi-digit numbers correctly.
  2. input.toInt():
    Converts the string input into an integer, allowing you to handle the input correctly.
  3. Waiting Loop Fix:
    The waiting loop now properly pauses until input is available without immediately reading data prematurely.

This code will prompt the user for input, correctly read the number from the Serial Monitor, and convert it into an integer for further processing.

I have done somework on the code and i think i almost got i working.
but it still has trouble with adding the numbers up.

here is the code atm:

String Number;
String Sum;

void setup() {
 Serial.begin(115200);
}


void Get_Number() {
  Serial.println("Please insert you're next number: ");
  while (Serial.available() == 0) { }
  String Input = Serial.readStringUntil("\n"); // reads until enter is pressed
  Number = Input.toInt(); // converts the given number into a whole 

}



void loop() {

   Get_Number();
Serial.print("You enterd: ");
Serial.println(Number);
Serial.println();
Serial.print("\t");
   String Sum = Number + Sum;
    Serial.print( "Your number is now: ");
    Serial.println (Sum);
    Serial.println( "\t");
   delay(500);
   }

I removed the counter to 10 atm so i can focus on getting it working.

this is what i get in serial:

You enterd: 5

	Your number is now: 
	
Please insert you're next number: 
You enterd: 7

	Your number is now: 7
	
Please insert you're next number: 
You enterd: 9

	Your number is now: 9
	
Please insert you're next number:

as you can see it is able to display the number given but it is unable to convert Number into Sum. I think this is because Sum holds no value on the first run.
So 5 + ?? = blank.
but i cant put a value on Sum.

also when i try to put sum into HEX or DEC it doenst work. for you guys it is probalby obvious but for me not atm.

this project is due to 36hrs but don't feel guilty. this is 100% my fault for asking the arduino forum or one of my theachers this late.

why aren't sum and number ints instead of String?

I copied the String option form one of the codes above and otherwise i got an error with this line:

String Input = Serial.readStringUntil("\n");

i also saw i can do this as: Serial.readBytesUntil("\n");

but that also gaves error with int

    String Sum = Number + Sum;

This declares a new String variable named Sum which is not the same as the global variable with the same name

You cannot add Strings together like you can with numeric variables. What that line of code will do instead is to concatenate the two Strings together rather than adding them. So, if Number is say "9" and the new Sum variable is "" then the result is "9"

trying changing

to

int Number;
int Sum;

I just remove the String and i workes "better" now it does it like this:

Please insert you're next number: 
You enterd: 5

	Your number is now: 5


Please insert you're next number: 
You enterd: 8

	Your number is now: 85


Please insert you're next number: 
You enterd: 9

^ also pretty funny

If i use Serial.readBytesUntil("\n");
and change the string to int' s will that work? or will i still miss something?

this is the code atm:

String Number;
String Sum;

void setup() {
 Serial.begin(115200);
}


void Get_Number() {
  Serial.println("Please insert you're next number: ");
  while (Serial.available() == 0) { }
  String Input = Serial.readStringUntil("\n"); // reads until enter is pressed
  Number = Input.toInt(); // converts the given number into a whole 

}



void loop() {

   Get_Number();
Serial.print("You enterd: ");
Serial.println(Number);
Serial.print("\n");
Serial.print("\t");
   Sum = Number + Sum;
   Sum = Sum.toInt();
    Serial.print( "Your number is now: ");
    Serial.println (Sum);
    Serial.println( "\n");
   delay(500);
   }

If i convert the Strings to Int i get this error:

Compilation error: no matching function for call to 'HardwareSerial::readBytesUntil(const char [2])'

probably expected but what do i do about it?

code:

int Number;
int Sum;

void setup() {
 Serial.begin(115200);
}


void Get_Number() {
  Serial.println("Please insert you're next number: ");
  while (Serial.available() == 0) { }
  int Input = Serial.readBytesUntil("\n"); // reads until enter is pressed
  Number = Input.toInt(); // converts the given number into a whole 

}



void loop() {

   Get_Number();
Serial.print("You enterd: ");
Serial.println(Number);
Serial.print("\n");
Serial.print("\t");
   Sum = Number + Sum;
   Sum = Sum.toInt();
    Serial.print( "Your number is now: ");
    Serial.println (Sum);
    Serial.println( "\n");
   delay(500);
   }

Try this

int Number;
int Sum;

void setup()
{
    Serial.begin(115200);
}

void Get_Number()
{
    Serial.println("Please insert you're next number: ");
    while (Serial.available() == 0) {}
    Number = Serial.parseInt();  // read an int

}

void loop()
{
    Get_Number();
    Serial.print("You enterd: ");
    Serial.println(Number);
    Serial.print("\n");
    Serial.print("\t");
    Sum = Number + Sum;
    Serial.print("Your number is now: ");
    Serial.println(Sum);
    Serial.println("\n");
    delay(500);
}

you're changing more than this

i will come back on Serial.parseInt(); later (because i do wanna know why i need to use that and what it does) but first i wanna get this working because it works but not correctly.

You enterd: 1

	Your number is now: 10


Please insert you're next number: 
You enterd: 0

	Your number is now: 10


Please insert you're next number: 

here is a piece of serial. and i already had 9 before this. and you can see i enterd 1, that makes 10. but then what the program does is that is goes through Get_Number(); again.

int Number;
int Sum;


void setup() {
Serial.begin(115200); }



void Get_Number() {
  Serial.println("Please insert you're next number: ");
  while (Serial.available() == 0) {}
  Number = Serial.parseInt(); //read an int


}



void loop() {

   Get_Number();
Serial.print("You enterd: ");
Serial.println(Number); //gives the enterd number
Serial.print("\n");
Serial.print("\t");
   Sum = Number + Sum;
    Serial.print( "Your number is now: ");
    Serial.println (Sum); // Displays the current sum of all the Previous numbers
    Serial.println( "\n");
   delay(500);
   }

Think --
1. When ioInt() method is applied on a String type variable, the result is an integer number. So, the data type of the variable Number should be int.

2. As Number variable is of type int, the Sum should also be of type int.

3. The quoted variables are declared as follows; now, the output is:

Please insert you're next number: 
5
You enterd: 5

	Your number is now: 5
	
Please insert you're next number: 
6
You enterd: 6

	Your number is now: 11
	
Please insert you're next number: 
17
You enterd: 17

	Your number is now: 28
	
Please insert you're next number: 

Your sketch after moderation:

int Number;
int Sum;

void setup()
{
  Serial.begin(115200);
}

void loop() 
{
  Get_Number();
  //--------------------
  Serial.print("You enterd: ");
  Serial.println(Number);
  Serial.println();
  //--------------------
  Serial.print('\t');
  //Sum = Number + Sum;
  Sum = Sum + Number;
  Serial.print("Your number is now: ");
  Serial.println(Sum);
  //---------------------
  Serial.println( '\t');
}

void Get_Number()
{
  Serial.println("Please insert you're next number: ");
  while (Serial.available() == 0) { }
  String Input = Serial.readStringUntil('\n'); // reads until enter is pressed
  Number = Input.toInt(); // converts the given number into a whole
  Serial.println(Number);
}
String Input = Serial.readStringUntil('\n'); // reads until enter is pressed

Why us a String when what you want the user to enter is an integer ?