-1

I have an indescribable bug where read and write commands give back an array of numbers that are the digits of the input number except +48. Kinda hard to explain. Basically if I type 0 into this code:

    void setup(){
      Serial.begin(9600); //Begin serial connection
    }
    void loop(){
      if(Serial.available()){ //If serial available...
        double ser = Serial.read(); //Read serial value and write it to 'ser'
        Serial.println(ser); //Print 'ser'
      }
    }

I receive 48. 1 means 49, 2 means 50, 3 means 51... And then two digit numbers, which are the same except for each digit. 10 returns 49 48, 33 returns 51 51, 22 returns 50 50.

1 Answer 1

1

Serial.read returns a character. The character '0' is 48 in decimal. So this is doing what you expect (or what I expect, anyway). I suggest not using double there, eg.

    char ser = Serial.read(); //Read serial value and write it to 'ser'
4
  • Thanks, but I have to output the value I get to a servo, which needs an int and it still separates the different characters into an array. Do you mind telling me a way to convert it into a full int?
    – Carrot M
    Oct 11, 2015 at 5:02
  • which needs an int and it still separates the different characters into an array - I don't understand that. What array?
    – Nick Gammon
    Oct 11, 2015 at 8:27
  • When transmitted textually, multi-digital value will indeed appear as something like a character array of the ASCII encoding of its digits. Nov 10, 2015 at 18:06
  • Often we send 4 characters like "1234" over the serial link and want to store them in a single integer like "int position = 1234". One way to do it is to store the characters into a temporary buffer, and then use "atoi()" or "atol()". Another way is convert digits to an integer on the fly. Yet another way is to use Serial.parseInt().
    – David Cary
    Feb 8, 2016 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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