interrupt loop while receiving data

I am totally confused about Serial.available command :frowning:
I’d like to stop the main program in order to receive the next command. Anyhow the Arduino skips my Command and simply goes on and on.

I have written a little test program to show my problem:
It should wait for an input, write “Send me something” and then wait again for some input. But it does only wait for the first input and the skips the Serial.available command continuously.

char a;

void setup() {
  pinMode(6, OUTPUT);
  digitalWrite(6, LOW);

void loop() {
  Serial.println("Send me something");
  while (Serial.available() == 0) // if there is data to read
    a =;


Serial.available() returns the number of bytes (chars) available for reading.

If somehow more chars were entered then read then Serial.available() would never return 0 after that.

Instead of using while wrap the read(), print(a) and flush() in a IF statement which tests available().


This really makes sense, as an additional command without any allocation empties the buffer and makes it work in a very inadequate way :frowning:

Up to me the if statement makes no sense, as it's no terminating command. I really want the arduino to stop doing the stuff within the loop until the new values are sent to the arduino. I just cann't find any good solution, also not on the internet, although this must be a daily problem :sweat_smile:

I’d like to stop the main program in order to receive the next command.

To pause the program waiting for input, you could use

 while (Serial.available() <= 0) {}

What you do when you break from the while loop after waiting for serial input depends on what is being sent.

Have a look at the examples in Serial Input Basics. The variable newData is set to true when data has arrived. You can test for that before allowing something else to happen. The showData() function uses it like that.


this is exactly what I was looking for! I should have read any tutorial first, but I thought arduino has an appropriate command by itself and I just can't get it :slight_smile:

This is a very nice tutorial, and I think with this tool I will be able to put together my own solution!

Thank you for your kind words.