Arduino Serial Available: Or is Serial data Ready Yet? Normally your program will work the way you expect but sometimes it won't. What are the interactions that could make your program Fail? Find out Here.

Arduino serial available is a function that you use in conjunction with the following functions:

    Serial.begin()
    Serial.read()


Before you can use Serial.available() you will need to use Serial.begin(<baud>) to initialise the Serial port to the chosen Baud rate (the default is 9600).

You then use the function Serial.available() to check whether any data has been received from the serial port. If data is available then you call Serial.read() to actually get the data out.

For example, if you have sent five characters over the serial port from the PC and call Serial.available(), it will return 5. You can then use Serial.read() to read each character one by one until the buffer buffer is empty. Each time you read out a byte from the buffer the value returned by Serial.available() will go down by one.

In fact you can use Serial.read() without first using Serial.available() and you'll receive a -1 value if there is no data ready. For instance you could poll the serial data port in a fast loop with this operation. However it is a waste of resource and would only be useful in specialised applications - you might be checking for when data is at the port in the fastest way possible.

Arduino Serial Available: Operation

The class object Serial is defined HardwareSerial.h and provides two circular buffers which are explained in more depth in the Serial.read() page. Serial available essentially returns the difference in pointer positions of the two pointers that manage the circular buffer.

It means that when bytes are received into the buffer the tail pointer is incremented with the difference between head and tail pointers giving the number of bytes received.

    Serial.available() returns this number.

The important point is that the buffer allows your program to be doing something else while data is being received (code for the serial port  is interrupt driven so it works in the background).

It means that there could be more than one byte of data in the buffer by the time your program gets round to reading the data; Serial.available() reports this number.

Note that Serial.read() only gets one byte so you have to keep reading the data until Serial.available() goes to zero.

Arduino Serial Available: Example Sketch 1

This example shows a simple loop printing any received character.

 

void setup() {
  Serial.begin(9600);
}

void loop() {
char ch;

  if (Serial.available() > 0) {
    ch = Serial.read();
    Serial.println(ch);
  }
}

Arduino Serial Read: Serial monitor output Ex1

This is the output you will see in the serial monitor

Type in a string of data in the serial monitor where the transparent text is shown:

"Message (Enter to send message to 'Arduino Uno' on 'COM4')".


Arduino Serial Read

Here the text "hello<Enter>" was typed.

Arduino Serial Available: Example Sketch 2

This example simulates delays i.e. when the processor is busy doing other tasks (here simulated using the the delay function).

The purpose of this example is to show you that using the serial port is not a cut-and-dried operation; in some design cases the serial link will not behave the way you expect.

This example stops the code using a blocking delay and causes the received serial data to be read in a seemingly random way - sometimes it will gather the whole message but at other times it will output two strings (but the complete data string is eventually read).

An explanation for this action is given below.
// Example showing Arduino Serial available code
void setup() {
  Serial.begin(9600);
}

void loop() {
char mybuf[64];
char *p = mybuf;
int num_chars;

  // Print out characters received from the buffer.
  if (num_chars = Serial.available()) {
    while(Serial.available()) {
      *p++ = Serial.read();
    }
    *p = '\0';
    p = mybuf;

    Serial.print("Number of chars in serial buffer: ");
    Serial.println(num_chars);
    Serial.println(mybuf);
  }

  delay(100); // Simulate processor doing lots of other work.
}
// This is a message for you.

Arduino Serial Read: Serial monitor output Ex2

This is the output that is produced for example 2.


Arduino serial available smiulation processor loaded

Note the example effectively illustrate problems in serial reception is asynchronous systems when the processor is busy with another task. It specifically shows the asynchronously received data may arrive in bursts between read.

In the above example the message has been entered two times. In the 1st output the complete message is generated at the Arduino, but in the 2nd it is split.

The important point is that no data is lost, you can see the total number of bytes adds up to 30 in both cases. This means the interrupt is functioning whatever your program is doing and shows that the circular buffers in the Serial class work easily in the background.

The reason for the split output is due to the asynchronicity of the serial link. i.e. the Arduino does not know when a transmission is starting so when going round the code loop, the Arduino is detecting some data available, but in the middle of a transmission from the PC.

It means the Arduino says - Yes I've got some data so lets start printing - it does not know how much data is to come, so does not wait. Whether or not this occurs depends entirely if the code Serial.available() is executed in the middle of a serial transmission or outside it (as in the 1st case).

However you can see that even with this asynchronicity - the circular buffers ensure that no data is lost.

If there were no interrupt driven circular buffers in the HardwareSerial.h code then the 1st half of the message would be printed out and the rest would be lost as the processor would be busy printing out the message and ignoring incoming data!

To obtain the complete message you will need to code in an end detector character, adding the previous data bursts to a storage string. When the end character is found you flag that to the main code to indicate that a complete message is ready to be decoded.

Arduino Serial Available: Conclusion

The function Serial.available() lets your program decide when the read a serial buffer i.e. when there is some data available.

For simple human to Arduino control the Serial class works easily using serial buffers provided in Arduino code to reliably capture serial data.

From the examples shown above you can see that serial link communication depends on the nature of the sending device and how much your Arduino is doing. Is a human typing slowly and then hitting enter - giving the processor tons of time or is the sending device generating continuous data e.g. a fast data logging system.

The second example above shows that although no data is lost, you may get bursts of data depending on how much the processor is doing. By knowing that there could be a problem you can code around it.

For example you could detect an end character that signals the end of an input so you can continue filling your own buffer. When the character is received you act on the buffer contents thus receiving all the data as a complete unit.

 
The two other functions that for a basic part of Serial code are:

    Serial.begin()
    Serial.read()



Comments

Have your say about what you just read! Leave me a comment in the box below.

Don’t see the comments box? Log in to your Facebook account, give Facebook consent, then return to this page and refresh it.



Privacy Policy | Contact | About Me

Site Map | Terms of Use