Pages: [1]   Go Down
Author Topic: How can I read more than one byte using the UART?  (Read 1587 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 22
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Global Moderator
The Netherlands
Offline Offline
Sr. Member
*****
Karma: 1
Posts: 287
don't panic...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Something along the lines of

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

Jeroen
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Expanding a bit on Yot's hint:

Code:
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.
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 22
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thank you very much!  
Logged

Pages: [1]   Go Up
Jump to: