How to convert a char to int in Arduino

25,675

Use:

long number = atol(input); // Notice the function change to atoL

Or, if you want to use only positive values:

Code:

unsigned long number = strtoul(input, NULL, 10);

Reference: http://www.mkssoftware.com/docs/man3/atol.3.asp

Or,

int convertedstring = atoi(teststring.c_str());
Share:
25,675
milhas
Author by

milhas

Updated on February 14, 2020

Comments

  • milhas
    milhas about 4 years

    I receive some data in a char variable, and the result in teststring is always a number. How can I convert this number to a variable int?

    After that I can put the int variable on delay time. There is a piece of my code:

    String readString = String(30);
    String teststring = String(100);
    int convertedstring;
    
    teststring = readString.substring(14, 18); (Result is 1000)
    
    digitalWrite(start_pin, HIGH);
    delay(convertedstring); // Result of teststring convert
    digitalWrite(start_pin, LOW);
    
  • milhas
    milhas over 9 years
    Error: cannot convert 'String' to 'const char*' for argument '1' to 'int atoi(const char*)'
  • milhas
    milhas over 9 years
    That's my try: long number = atol( teststring );
  • Bouraoui KACEM
    Bouraoui KACEM over 9 years
  • Bouraoui KACEM
    Bouraoui KACEM over 9 years
  • milhas
    milhas over 9 years
    It-s working! int convertedstring = atoi(teststring.c_str()); Tnk you
  • ohhorob
    ohhorob over 6 years
    Looks like you might have a bug where the pointer s is always incremented even when the first character is not '-'?
  • Peter Mortensen
    Peter Mortensen about 6 years
    What do you mean by "String to Long Arduino IDE"?