How does serial work?

I am new to the arduino and i’m trying to understand how serial communication works. My previous non-atmel microcontrollers didn’t have the buffer for serial comms, maybe that’s why i can’t understand properly how it works on the arduino.

I went through the learning/getting started/reference sections on already, but they didn’t help much. What i can’t understand is what does.

Now, if i well understood data gets sent to the arduino and the arduino stores it in the buffer. Then with serial.available you check how many bytes you’ve got in the buffer, and finally with you read them. But do bytes get erased as they get read with

Take this random sketch for example:

 if( Serial.available() == 3 ){ // got 3 bytes
      int r =;  
      int g =;
      int b =;}

my only explanation to this code is that every time gets called the byte is read and then cancelled from the buffer.
Is this right or am i missing something? I am asking just to be sure, because this isn’t written in the references.

The serial buffer is a circular buffer, so the byte is read, and the tail pointer is advanced.
In a sense, then yes, it is “cancelled”.

oh i think i got it. So in case i expect a large amount of bytes (>128) i’ll have to flush the buffer sometimes, cause won’t do that. So i guess that serial.available also uses(or is based on) the same pointer right? Or does it not?

That’s right - there are two pointers to the 128 bytes buffer.
Characters received are put at the location pointed to by “head”, and read characters are taken off at “tail”.
If head == tail, buffer is empty, and so the difference of the values of the pointers gives “available”.

Got it! Thank you very much!

Just a point,
Never use :-Serial.available() == 3

Always use:- Serial.available() >= 3

The first case will jam up if more than 3 bytes are read before you come to this statement.