Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my Arduino serial port gives me semi-random numbers?

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?

like image 529
Kim Avatar asked Nov 19 '25 17:11

Kim


1 Answers

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;.

like image 111
Mathews Sunny Avatar answered Nov 21 '25 22:11

Mathews Sunny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!