Problem with Serial Communication

Hello all,

I have a problem when sending data to the Arduino through the serial monitor.

int IncByte;

void loop(){

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

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

When I send 1 through the serial monitor I get back 49. If I send 2 it returns 50, and so forth. If I send a two digit number I get back two separate numbers, instead of one number. If I send negative numbers I don't get back negative numbers, I get a couple of separate positive numbers. :o

I need to be able to send a negative integer and store that value inside the arduino, as well as positive integers with two or more digits. Am I missing something?...

Thanks for any help!

When sending thing on the serial, you are actually sending numerical values.

You might want to have a look at http://en.wikipedia.org/wiki/Ascii to see what the values represent.

-1 will be sent as character '-' then character '1' and thus you will recieve two numerical values. Each value represent a character. In this case 45 and 49.

http://arduino.cc/en/Reference/Char

Here is one way of converting the ascii characters into an integer value. This fragment receives ascii digits (optionally preceeded by a minus sign) and prints the integer value. It assumes the first non digit character indicates the end of the digit string. For example, if you send -123? it will print -123

int val = 0;
int sign = 1;

void loop()
{
  if( Serial.available())
  {
    char ch = Serial.read();
    if(ch >= '0' && ch <= '9') // is this an ascii digit between 0 and 9?
       val = (val * 10) + (ch - '0');      // yes, accumulate the value
    else if( ch == '-')
       sign = -1; 
    else
    {       
       val = val * sign ;  // set blinkrate to the accumulated value
       Serial.println(val);
       val = 0; // reset val to 0 ready for the next sequence of digits
       sign = 1;
    } 
  }
}

Another way is to use the C atoi function, this requires that you capture all the digits in an array and then call atoi with the a pointer to the array ( a search for atoi turns up many examples of its use)

I see, perfect! Thanks to both of you for your help!