Arduino的:字符串int获取奇怪的值 [英] Arduino: String to int gets strange values

查看:269
本文介绍了Arduino的:字符串int获取奇怪的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换一个字符串 INT ,以及所有我能找到的是,你必须要转换字符串到字符数组,然后施放此数组的 INT ,但我的code产生奇怪的价值观,我想不出是什么问题。

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

我有望获得与100的价值,但实际的int是2225一个int?我有什么错在这里做什么?

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

推荐答案

您需要使用的功能 int值=的atoi(valueArray); ,其中 valueArray 是一个空结尾的字符串。

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

这篇关于Arduino的:字符串int获取奇怪的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆