[SOLVED] Negative input into Serial Monitor

Talk about Arduino board, sheilds. Sharing Arduino projects, program, problems, solutions, suggestions..... many more, all are welcome.

[SOLVED] Negative input into Serial Monitor

Postby JDM » Tue Nov 06, 2012 1:33 pm

Hi. Can anyone tell me on how can i put a negative number into the serial monitor? Everytime i put a -1 (for example), this happens:

Screen Shot 2012-11-06 at 1.30.05 PM.png
Screen Shot 2012-11-06 at 1.30.05 PM.png (18.21 KiB) Viewed 2478 times

It seems that the serial monitor reads a minus sign as -3, then read 1 as 1 (which is correct, except the negative sign).

Here's the code:

CODE: SELECT_ALL_CODE
void loop() {

     while (!Serial.available());   // wait until there was signal send from computer
     inByte = Serial.read();
     inByte = inByte-48;        // minus 48 (30 hex) to get the decimal value (got from Cytron tutorial)

     Serial.print("I received: ");
     Serial.println(inByte);
               
}


I've been googling around but not yet found any solution :(
JDM
Novice
 
Posts: 16
Joined: Thu Oct 25, 2012 4:18 pm

Re: Negative input into Serial Monitor

Postby shahrul » Tue Nov 06, 2012 2:00 pm

inByte is char (8 bit value)

Then you type '-' & '1'. 2 character.
ASCII for '-' equal to 45. Then 45 minus 48, it get -3.
User avatar
shahrul
Professional
 
Posts: 812
Joined: Sat May 16, 2009 9:54 pm
Location: Selangor

Re: Negative input into Serial Monitor

Postby JDM » Tue Nov 06, 2012 2:32 pm

Oooo i see. Now i understand. Thanks!

Any idea on how i can make it to read 2 character at once?
JDM
Novice
 
Posts: 16
Joined: Thu Oct 25, 2012 4:18 pm

Re: Negative input into Serial Monitor

Postby shahrul » Tue Nov 06, 2012 2:46 pm

You do if(Serial.available()); first.
Then while (!Serial.available())
{what_ever_code_here();};
User avatar
shahrul
Professional
 
Posts: 812
Joined: Sat May 16, 2009 9:54 pm
Location: Selangor

Re: Negative input into Serial Monitor

Postby JDM » Tue Nov 06, 2012 4:02 pm

Thanks! :mrgreen:

BTW after playing around with your recommendation, this is what i've done to differentiate between a negative & positive input.

CODE: SELECT_ALL_CODE
    inByte = Serial.read();
   
    if (inByte == 45) {                     // read negative input. -ve == 45
      while (!Serial.available());          // wait until there was signal send from computer
      inByte = Serial.read();
      inByte = -(inByte-48);                // minus 48 (30 hex) to get the decimal value
      Serial.print("I received: ");
      Serial.println(inByte);
    }
 
    if (inByte > 45) {                      // read positive input
      inByte = inByte-48;
      Serial.print("I received: ");
      Serial.println(inByte);
    }


Thanks again! :D
JDM
Novice
 
Posts: 16
Joined: Thu Oct 25, 2012 4:18 pm


Return to Arduino Based

Who is online

Users browsing this forum: No registered users and 4 guests