Go Down

Topic: How can I read more than one byte using the UART? (Read 1 time) previous topic - next topic

elegance

Serial.read()
Returns only the first byte of incoming serial data available (or -1 if no data is available).

How can I read more than one byte using the UART ?

Thank you very much.

Yot

Something along the lines of

While serial data available is bigger than 0.
{
  read one byte and stuff it in an array
}

Jeroen

PaulS

Expanding a bit on Yot's hint:

Code: [Select]
char inData[10]; // Or whatever size you need
byte index = 0;

void loop()
{
  while(Serial.available() > 0)
  {
     char aChar = Serial.read();

     inData[index] = aChar; // Add the character to the array
     index++;   // Point to the next position
     inData[index] = '\0'; // NULL terminate the array
  }
}


Now, there are lots of things wrong with this code (although it will work).

First, the character is added to the array, whether there is room or not. There should be some checking to make sure there is room for the character. The reason that it is left out is that I have no idea what you want to do if there is not room.

The next thing that is missing is what to do when the end-of-packet marker arrives. I can't include that code because I have no idea what your end of packet marker is.

There is nothing to reset the array index to 0, because I don't know what constitutes, for you, a beginning of packet marker.

There is nothing to distinguish between the while loop ending because all the serial data was read, or because an end-of-packet marker was received.

So, while your question seems really simple, there is a lot to consider. If you provide more details about what is sending the data, what start and end of packet markers are sent, and what to do about dropped characters and oversize packets, the answer to your question could be more complete.


Go Up