Serial Read returns odd value...

When i try to serial read the character 'A' into an integer ser_in1 and print ser_in1, it prints 65-1, however it prints the ascii values for other characters correctly. Why is this? I have used this in the past and it has worked.

if(Serial.available() > 0)
  {
    ser_in1 = Serial.read();
    Serial.print(ser_in1);
    if(ser_in1 == 65)
    {
      ser_in2 = Serial.read();
      Serial.print(ser_in2);
      if(ser_in2 == 48)
        control_device(0);
      if(ser_in2 == 49)
        control_device(1);
    }
  }

This is what happens:

First you read the Serial buffer, and if it is 'A' you read it again, only problem is: now the buffer is empty. And thus, it returns -1.

:slight_smile:

Yes, My code is the same. So where did the -1 come from? i have never seen it before. The complete code is here...

#define outputpin 13

int ser_in1=0, ser_in2=0;
void setup()
{
  pinMode(outputpin,OUTPUT);
  Serial.begin(9600);
  
}

void loop()
{
  if(Serial.available() > 0)
  {
    ser_in1 = Serial.read();
    Serial.print(ser_in1);
    if(ser_in1 == 66)
    {
      ser_in2 = Serial.read();
      Serial.print(ser_in2);
      if(ser_in2 == 48)
        control_device(0);
      if(ser_in2 == 49)
        control_device(1);
    }
  }
}

void control_device(int state)
{
  digitalWrite(outputpin,state);
}

And the output i get when i pass 'B1' now is 66-149

How do i correct this? :-/

AlphaBeta already explained.

-1 is what you get if you Serial.read() when there is nothing in the buffer. Serial.available() said something was ready, but if only one char is ready, then you should only attempt one Serial.read().

65 == 'A'
-1 == don't read from Serial.read() if nothing is Serial.available()
66 == 'B'
-1 == don't read from Serial.read() if nothing is Serial.available()
49 == '1'

and so on.

  if(Serial.available() > 0)

How do i correct this? :-/

I think:

if(Serial.available() >= 2)

Should do the trick?