Pages: [1]   Go Down
Author Topic: More then 1 digit  (Read 619 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I want to use more than 1 digit (for example 12, 68) in the code below for Serial.read and for Serial.print but I don't know how. I've searched the forum but I couldn't find anything. Could someone help me?
I'm new to arduino, so please don't make it to difficult for me. smiley

Code:
int incomingByte = 0;      // for incoming serial data

void setup() {
      Serial.begin(9600);      // opens serial port, sets data rate to 9600 bps
}

void loop() {

      // send data only when you receive data:
      if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();

            // say what you got:
            Serial.print("I received: ");
            Serial.println(incomingByte, DEC);
      }
}
Logged

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

Create an array to store the data in, and an index into that array:
Code:
char inData[10];
byte index = 0;

Then, replace the if test with a while loop:
Code:
void loop()
{
  while(Serial.available() > 0)
  {
     char aChar = Serial.read();

     inData[index] = aChar;
     index++;
     inData[index = '\0';
  }

  // Do something with inData, like call atoi...
}

There are two issues with this code. One is that it does no error checking, like making sure there is room in the array before storing the new value in the array.

The other is that there is no way to tell which bytes in the serial buffer form a packet.

If you send "12" and "68" and there is a delay in reading the serial data, the buffer will contain "1268". Where does one value end and the next one begin?

If there is any delay in receiving the serial data, after you send "12", the Arduino may read the 1 before the 2 arrives, and assume it got a complete packet.

It's better to include start-of-packet and end of packet markers, like "<12><68>". This way, it is easy to see what constitutes a packet.
« Last Edit: September 09, 2010, 07:44:39 pm by PaulS » Logged

Pages: [1]   Go Up
Jump to: