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() {
   void loop() {
   number = Serial.read();
  • Serial.read() returns -1 when there was nothing to read. Just discard the -1. – Wirewrap Oct 18 '15 at 7:11
  • here i made so change to the code the value for number is no longer 5 now its 0 and i changed int for long and therer no longer int before number = Serial.read(); when i send 3 its answer me 51 10 – Eric Cooper Oct 18 '15 at 20:26
  • When you send a 3 what answer do you expect? – Wirewrap Oct 18 '15 at 21:48
  • @EricCooper True, if you send "3" you'll get ASCII 51, ASCII 10. (asciitable.com/index/asciifull.gif) The NUMBER 51 is CHARACTER "3" also, a newline character (10) is added to the end of your serial message when you send it. – Paul Oct 20 '15 at 16:41

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
| improve this answer | |
  • I didn't even know this, but it's worth noting that he's printing the ASCII representive of the sent character. – Paul Oct 20 '15 at 16:50

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.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.