Arduino: String to int gets strange values

21,509

Solution 1

You need to use the function int value = atoi(valueArray); where valueArray is a null terminated string.

Solution 2

There is even an (undocumented) toInt() method in the String class:

int myInt = myString.toInt();

Solution 3

The toInt () method is very useful in this aspect, but I found that it is able to convert only strings of length five or less, especially a value less than 65535 as its the maximum value int can take. Over this value, it just gives random numbers (overflowing values). Please be aware of this when you use this method as it killed a lot of my useful time to figure this out. Hope it helps.

Share:
21,509
Admin
Author by

Admin

Updated on February 15, 2020

Comments

  • Admin
    Admin about 4 years

    I want to convert a String to an int, and all I could find is that you have to convert the String to a char array and then cast this array to an int, but my code produces strange values and I can't figure out what the problem is.

    void ledDimm(String command)
    {
        // Get the Value xx from string LEDDimm=xx
        String substring = command.substring(8, command.length());
    
        Serial.println("SubString:");
        Serial.println(substring);
        Serial.println("SubString Length:");
        Serial.println(substring.length());
    
        // Create a Char Array to Store the Substring for conversion
        char valueArray[substring.length() + 1];
    
        Serial.println("sizeof ValueArray");
        Serial.println(sizeof(valueArray));
    
        // Copy the substring into the array
        substring.toCharArray(valueArray, sizeof(valueArray));
    
        Serial.println("valueArray:");
        Serial.println(valueArray);
    
        // Convert char array to an int value
        int value = int(valueArray);
    
        Serial.println("Integer Value:");
        Serial.println(value);
    
        // Write the Value to the LEDPin
        analogWrite(LEDPin, value);
    }
    

    And the serial output looks like this:

    Received packet of size 11
    From 192.168.1.4, port 58615
    Contents:
    LEDDimm=100
    SubString:
    100
    SubString Length:
    3
    sizeof ValueArray
    4
    valueArray:
    100
    Integer Value:
    2225
    

    I expected to get an int with the value of 100 but the actual int is 2225?! What have I done wrong here?

  • KittMedia
    KittMedia about 8 years
    This should be a comment rather than an answer as it doesn’t answer the queston.
  • Sujay Phadke
    Sujay Phadke over 7 years
    Not undocumented anymore: arduino.cc/en/Reference/StringToInt