3

I have a basic problem with my Arduino Uno.
My example code gets a number over Serial port and should print it back.

int incomingByte = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("Hello World");  
}

void loop() {
  if (Serial.available() > 0) {

    // read the incoming byte:
    incomingByte = Serial.read();

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

When I send 0, I receive 48.

0->48
1->49
2->50
3->51

a->97
b->98
A->65

So why doesn't it send the same numbers back to me?

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Kim
  • 57
  • 5

1 Answers1

9

In your program the output is ASCII equivalent of the input that the Arduino receives. ASCII equivalent of 0 is 48, 1 is 49, a is 97, A is 65 and so on.

The reason is you are storing your input to incomingByte variable (incomingByte = Serial.read();) but you declare incomingByte variable as int. When a character is assigned to integer variable, its corresponding ASCII value will be stored to the integer variable.

So if you want to print a character that you send to the Arduino, you want to change int incomingByte = 0; to char incomingByte;.

dda
  • 6,030
  • 2
  • 25
  • 34
Mathews Sunny
  • 1,796
  • 7
  • 21
  • 31