Serial.read

I know this may seem simple, but I'm stumped. What the heck is going on?

int incomingByte;   // 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);
        }
}

How come when I input a 1 into the Serial monitor I get a 49 out? I thought it was supposed to give me a 1 back.

Hi doubtfulalpha

int incomingByte;   // for incoming serial data

Declaring this as an integer causes Serial.print to treat the character received as an integer rather than a char.

49 decimal is the ASCII value for the character '1'.

Try declaring incomingByte as char instead. And to avoid confusion, it would be better (though not essential) to call the variable incomingChar.

Regards

Ray

I knew it was something simple. Appreciate it!

If you are only translating one digit character to a number, you could use:

incomingByte = Serial.read() - '0';

Therefore, if ASCII 49 arrives as input (a '1' digit character), it is processed as:

incomingByte = Serial.read() - '0';
incomingByte = 49 - 48;
incomingByte = 1; // This is numeric.

@HS - Serial read returns an int not a char!

In this case the op reads the ascii code of the char '1' which is 49. He then prints the value. Had he used write instead he would have got '1'.

Mark