如何在Arduino中将字符转换为整数

6

我在一个char变量中接收到一些数据,而teststring中的结果始终是一个数字。如何将这个数字转换为int变量?

之后我可以将int变量放在延迟时间上。下面是我的一段代码:

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);
3个回答

7

使用:

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

或者,如果您只想使用正值:
代码:
unsigned long number = strtoul(input, NULL, 10);

参考文献:http://www.mkssoftware.com/docs/man3/atol.3.asp

或者,

int convertedstring = atoi(teststring.c_str());

错误:无法将“String”转换为“const char *”,以便将其作为参数“1”传递给“int atoi(const char *)”。 - milhas
这是我的尝试: long number = atol(teststring); - milhas
这个链接可以帮助你:https://dev59.com/YGbWa4cB1Zd3GeqPa9MI - Bouraoui KACEM
此外,这个链接非常有用:http://forum.arduino.cc/index.php/topic,103511.0.html - Bouraoui KACEM
1
它正在工作!int convertedstring = atoi(teststring.c_str()); 谢谢。 - milhas

0

将字符串转换为长整型 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;
    }

1
“String to Long Arduino IDE” 是什么意思? - Peter Mortensen

0
你的Arduino环境中是否有访问atoi函数的权限?
如果没有,你可以在其中编写一些简单的转换代码:
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;
}

看起来你可能有一个bug,指针s即使第一个字符不是'-'也总是被递增了? - ohhorob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接