Go Down

Topic: More then 1 digit (Read 1 time) previous topic - next topic


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. :)

Code: [Select]

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


Sep 10, 2010, 02:42 am Last Edit: Sep 10, 2010, 02:44 am by PaulS Reason: 1
Create an array to store the data in, and an index into that array:
Code: [Select]
char inData[10];
byte index = 0;

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

    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.
The art of getting good answers lies in asking good questions.

Go Up