I want to implement a function in another micro-controller which works like serial.available(). I don't know how it works. I read about Serial.available() in this link.

Whenever I write a string on the terminal, it prints the length of the string. Can anyone tell me how it works?

1 Answer 1


It reports the difference between the head and the tail of the circular buffer the incoming characters are stored in.

The way serial reception on the Arduino works is:

  1. A character is received into the internal hardware RX buffer (UDRx)
  2. An interrupt is triggered
  3. An interrupt service routine (ISR) is executed
  4. The character in UDRx is read and, if there is room, stored in a circular buffer (_rx_buffer).
  5. The head pointer of _rx_buffer is incremented and wrapped if needed.

When you actually read a character with Serial.read() the following happens:

  1. If the head and tail of rx_buffer are equal, return -1
  2. Get the character at tail from _rx_buffer
  3. Increment tail and wrap if needed
  4. Return the character

So when you use Serial.available() it just returns head - tail (taking into account the wrapping, so the sum is slightly more complex than a simple subtraction).

You should examine the files HardwareSerial.h and HardwareSerial.cpp in the Ardino AVR core software.

  • i understand till step3
    – Beginner
    Apr 12, 2017 at 12:31
  • Step three in which block?
    – Majenko
    Apr 12, 2017 at 12:31
  • The character in UDRx is read and, if there is room, stored in a circular buffer (_rx_buffer).
    – Beginner
    Apr 12, 2017 at 12:32
  • first block....
    – Beginner
    Apr 12, 2017 at 12:34
  • You should read the ATMega328P datasheet - the section about the USART.
    – Majenko
    Apr 12, 2017 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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