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:
- A character is received into the internal hardware RX buffer (
UDRx
) - An interrupt is triggered
- An interrupt service routine (ISR) is executed
- The character in
UDRx
is read and, if there is room, stored in a circular buffer (_rx_buffer
). - The
head
pointer of_rx_buffer
is incremented and wrapped if needed.
When you actually read a character with Serial.read()
the following happens:
- If the
head
andtail
ofrx_buffer
are equal, return-1
- Get the character at
tail
from_rx_buffer
- Increment
tail
and wrap if needed - 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 step3Beginner– Beginner2017年04月12日 12:31:23 +00:00Commented Apr 12, 2017 at 12:31
-
Step three in which block?Majenko– Majenko2017年04月12日 12:31:46 +00:00Commented 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– Beginner2017年04月12日 12:32:04 +00:00Commented Apr 12, 2017 at 12:32
-
-
You should read the ATMega328P datasheet - the section about the USART.Majenko– Majenko2017年04月12日 13:15:21 +00:00Commented Apr 12, 2017 at 13:15