0

Hi i have made this code its so simple its should receive data from the computer and send it back via the serial but the problem is he do not what it is suppose to do when its run its keep sending -1 to the computer and if i send something to the arduini like 55 i receive and answer 53 i have no idea were is the problem in this code

long number = 0;

void setup() {
  Serial.begin(9600);
}
   void loop() {
   number = Serial.read();
   delay(1000);
   Serial.println(number);
}

2 Answers2

2

You need to include DEC as the second argument to the Serial.println() call to get the correct numbers out. Read up on this here: Arduino Serial Print.

In other words, make change below:

Serial.println(number, DEC); // DEC is needed to get the correct values
Ricardo
  • 3,390
  • 2
  • 26
  • 55
Meretrix
  • 33
  • 5
1

Serial.read() returns one character from the input. Serial.println will try to convert a variable into ASCII characters, and print that. Your variable, number gets the ASCII code of the first typed character in its first byte. The Serial.println call will interpret that and the next 3 bytes (whatever they happen to be...?) as a value to be printed.

Your problem is in not understanding the conversion of digit strings into values and vice-versa, and of how the Serial.xxx functions work.

You'll need to collect the terminal input character-by-character into an array, then convert it to a numeric value (assuming you're eventually going to do more with it than print it back out). Then you could Serial.println() that (or another) value out to the terminal.

JRobert
  • 15,407
  • 3
  • 24
  • 51