milhas
milhas

Reputation: 83

How to convert a char to int in Arduino

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);

Upvotes: 6

Views: 27868

Answers (3)

hink3
hink3

Reputation: 1

Do you have access to the atoi function in your Arduino environment?

If not, you can just write some simple conversion code in there:

int my_atoi(const char *s)
{
    int sign=1;
    if (*s == '-')
        sign = -1;
    s++;
    int num = 0;
    while(*s)
    {
        num = ((*s)-'0') + num*10;
        s++;
    }
    return num*sign;
}

Upvotes: 0

Bouraoui KACEM
Bouraoui KACEM

Reputation: 821

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());

Upvotes: 7

FWaqidi
FWaqidi

Reputation: 1

String to Long Arduino IDE:

    //stringToLong.h

    long stringToLong(String value) {
    long outLong=0;
        long inLong=1;
        int c = 0;
        int idx=value.length()-1;
        for(int i=0;i<=idx;i++){

            c=(int)value[idx-i];
            outLong+=inLong*(c-48);
            inLong*=10;
        }
        return outLong;
    }

Upvotes: 0

Related Questions