I am new to Arduino and I have the following:

int     delaynum;
char    cval[12];

void setup()
 Serial.print("Enter Number");

 int i=0;
    char ch=Serial.read();
void loop()

The code output in virtual bread board:(i Entered 100)

Output 1

But when i remove Serial.flush() The output like (i Entered 100)

Output 2

I am Expecting the output:

Enter Number (I want to enter number 100 after the output)


Why the code not working ?

I am using Arduino IDE with virtual bread board(ATMega328p)

  • it is an error of the emulation. Serial.flush() only waits until the data are sent completely.
    – Juraj
    May 1, 2020 at 10:07

1 Answer 1


Not knowing what virtual breadboard does on a normal Arduino it would do the following:
Serial.flush() clears the buffer and this needs some time normaly you wait minimum for around 100 ms to write/read to that buffer again.
As your code runs in setup (so just once) the serial is not available as its still flushing and so your result.
As the name setup says this should only be used to setup HW/SW but not to run routines as you may get all sorts of weird results.
If you use "\n" aka newline terminators in your communication you can go for them and flushing would be only necessary if the connection is interrupted and you have to resend data.

Waits for the transmission of outgoing serial data to complete.

If you send a character, it is placed in a buffer for transmission. It takes time for each character to be sent because serial is slow. Once it is in the buffer, it will be sent automatically in the background while the program immediately moves on to the next statement. This is done so the program won't waste time waiting for characters to be sent.

flush() is a way to wait for it to be sent, instead of immediately moving on in the user program.

So after calling flush() you can be sure that all data has been sent, and the buffer is empty. So in your case where you placed it it makes no sense.

  • Can you explain in more detail and Arduino use same buffer for both input and output or serial.flush() flush both input and output buffers? May 1, 2020 at 8:55
  • See my edit above. Please mark as accepted if its ok May 1, 2020 at 9:20
  • So in your case where you placed it it makes no sense, why? Arduino does not wait in setup function and what is solution for this can you explain please i am new to this. May 1, 2020 at 9:33
  • Please read on Arduino.cc the basic101 I am not gonna teach here we solve one problem at a time May 1, 2020 at 10:09
  • somehow this answer doesn't say anything to answer the problem
    – Juraj
    May 1, 2020 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.