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

I want to use more than 1 digit (for example 12, 68) in the code below for 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

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 =;

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

Seattle, WA USA
Online Online
Brattain Member
Karma: 633
Posts: 50217
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:
char inData[10];
byte index = 0;

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

     inData[index] = aChar;
     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: