Serial Error Reason ?

Hi all, again :)

I've tried to make simple protocol, where the PC sends a 4 digit number and the 1st digit of the num is the variable, here 'x', and the other 3 are values of the variable.

For example. 1211 ---> var is 'x' ---> x = 211 ;

The code is below :)

int var_select ;
int trueval ;
int x ;
int y ;
int z ;

int serialData = 0;

void setup()
{
  Serial.begin(9600);  
}


long int getSerial()
{
  if (Serial.available() > 0)
  {
    serialData = Serial.read();
    serialData = serialData - '0' ;
    Serial.println(serialData);
    return serialData ;
  } 
}

void loop()
{
   getSerial();
   if(serialData == 1)
   {
   getSerial();
   trueval = serialData * 100 ;
   getSerial();
   trueval = trueval + serialData * 10 ;
   getSerial();
   trueval = trueval + serialData ;
   x = trueval ;
   Serial.println(x) ;
   serialData = 0 ;
   }
    
}

It sets the variable properly to the 3 digit value. The problem is in the function long int getSerial()

Only when I comment out ' Serial.println(serialData); ' , the serial monitor prints garbage for some reason. Allow it to print, then suddenly it works fine.

w/o ' Serial.println(serialData); '

---> Entry : 1231 111 111 111 etc on the serial monitor

with ' Serial.println(serialData); '

---> Entry : 1231 1 2 3 231

Guys HELP :) PLEASE :)

What happens when you call getSerial() when there is no serial input waiting?

Well, getSerial() is called within the loop. When there is no input waiting, do you mean when we don't type anything into the serial monitor ?, if that's the case, then nothing happens either ways ( according to plan ) .

Any idea ?

vikramnayak: if that's the case, then nothing happens either ways ( according to plan ) .

Yes, but you are assuming something does happen when you try to process the data you received here:

getSerial();
trueval = serialData * 100 ;
getSerial();
trueval = trueval + serialData * 10 ;
getSerial();
trueval = trueval + serialData ;

The improper way to do it would be to make getSerial blocking until data has been received. The proper way to do it, is to not act on data until some kind of terminating byte is sent.

Also, are you returning serialData when it is a global variable?

This code assumes that it will get a char digit what happens when it gets the letter, the CR and the LF?

long int getSerial()
{
  if (Serial.available() > 0)
  {
    serialData = Serial.read();
    serialData = serialData - '0' ;
    Serial.println(serialData);
    return serialData ;
  } 
}

Why a long it cant be more than a byte?

Mark