How does serial work?

Hello!
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 arduino.cc already, but they didn’t help much. What i can’t understand is what Serial.read 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 serial.read you read them. But do bytes get erased as they get read with serial.read?

Take this random sketch for example:

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

my only explanation to this code is that every time serial.read 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 arduino.cc 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 serial.read 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.