Problem to understand the program flow inside void loop()

#include<string.h> 
int ledStrip = 3; 
int serialReading = 0; 
int brightness = 0; 

char command[12];  
int pos = 0; 
int flag = 0; 

void setup() {
  pinMode(ledStrip, OUTPUT); 
  Serial.begin(9600); 

}

void loop() {
  
 while(Serial.available()>0)
 {
  char inByte = Serial.read(); 
   command[pos] = inByte; 
   pos++; 
   flag = 1; 
   Serial.println("Inside while"); 
 }
  
  if(flag==1)
  {
    for(int i = 0; i<pos; i++)
    {
      Serial.print(command[i]); 
      command[i] = '0'; 
    }
    Serial.print('\n'); 
    pos = 0; 
    flag = 0; 
    Serial.println("Inside if"); 
  }
 
  
}

Say some byte is available in the serial buffer, so the execution should be up to while() loop until the condition inside while() turns out to be false. Only then the if statement should be executed.
But when I send some messages through the Serial monitor, I get something like this:


My question is, why the program execution moves to if without completely the while() loop?

Welcome to the forum

What exactly are you typing into the Serial monitor and what is the Line ending set to in the Serial monitor ?

The while exits for the normal reason. The condition becomes false.

The buffer is empty.

Processor fast, serial communications s l o w.

a7

Because Serial.avaliable became less then 1 when the serial available was removed from the serial buffer with char inByte = Serial.read(); .

I typed "byte" and the line ending is "newline".

I first noticed it on Tinkercad. Later I executed the same program on an Arduino Nano. Both of them produced same output.

I cannot type faster than the Uno runs the above code. Can you?

I would hope so.

They are executing the code you wrote, and showing you exactly what we all are saying. Characters arrive s l o w e r than the processor can eat them, so it starves and leaves the while loop.

a7

Maybe I don't have a clear idea of how the whole process of reading and writing to the serial monitor works. Any detailed insight will help.

That means, as I write "byte", 'b' reaches first, then 'y' then 't', and so on. And there's a time gap between reaching those characters?

The sketch is taking characters out of the serial buffer much faster than characters are arriving from your PC. If you want to read a full line before processing it, only set 'flag' when the '\n' is put in the buffer.

    if (inByte == '\n')
           flag = 1;

This thing


and words like "serial basics" may provide enlightenment.

Thanks a lot, since I'm new to the forum, I don't know much about different features here.

I hope it'll work. I'm working on implementing it. Thank you so much.

or try using Serial.readBytesUntil ()

Working on it. Thank you.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.