Flo*_*ncu 18 arrays string arduino
我有一个返回char数组的函数,我希望它变成一个String,这样我就可以更好地处理它(与其他存储数据相比).我使用这个简单的应该工作,但它不是出于某种原因(bufferPos是数组的长度,buffer是数组,item是一个空字符串):
for(int k=0; k<bufferPos; k++){
item += buffer[k];
}
Run Code Online (Sandbox Code Playgroud)
在buffer有正确的价值观也是如此bufferPos,但是当我尝试转换,例如544900010837154,它仅持有54如果我添加Serial.prints到像这样:
for(int k=0; k<bufferPos; k++){
Serial.print(buffer[k]);
Serial.print("\t");
Serial.println(item);
item += buffer[k];
}
Run Code Online (Sandbox Code Playgroud)
输出是这样的:
5
4 5
4 54
9 54
0 54
0 54
0 54
1 54
0 54
8 54
3 54
7 54
1 54
Run Code Online (Sandbox Code Playgroud)
我错过了什么?感觉就像这么简单的任务,我没有看到解决方案......
小智 26
如果char数组以null结尾,则可以将char数组分配给字符串:
char[] chArray = "some characters";
String String(chArray);
Run Code Online (Sandbox Code Playgroud)
至于你的循环代码,它看起来是正确的,但我会尝试我的控制器,看看我是否得到同样的问题.
三年后,我遇到了同样的问题.这是我的解决方案,每个人都可以随意切割粘贴.最简单的事情让我们彻夜难眠!在ATMega和Adafruit Feather M0上运行:
void setup() {
// turn on Serial so we can see...
Serial.begin(9600);
// the culprit:
uint8_t my_str[6]; // an array big enough for a 5 character string
// give it something so we can see what it's doing
my_str[0] = 'H';
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // be sure to set the null terminator!!!
// can we see it?
Serial.println((char*)my_str);
// can we do logical operations with it as-is?
Serial.println((char*)my_str == 'Hello');
// okay, it can't; wrong data type (and no terminator!), so let's do this:
String str((char*)my_str);
// can we see it now?
Serial.println(str);
// make comparisons
Serial.println(str == 'Hello');
// one more time just because
Serial.println(str == "Hello");
// one last thing...!
Serial.println(sizeof(str));
}
void loop() {
// nothing
}
Run Code Online (Sandbox Code Playgroud)
我们得到:
Hello // as expected
0 // no surprise; wrong data type and no terminator in comparison value
Hello // also, as expected
1 // YAY!
1 // YAY!
6 // as expected
Run Code Online (Sandbox Code Playgroud)
希望这有助于某人!
小智 5
访问https://www.arduino.cc/en/Reference/StringConstructor轻松解决问题。
这为我工作:
char yyy[6];
String xxx;
yyy[0]='h';
yyy[1]='e';
yyy[2]='l';
yyy[3]='l';
yyy[4]='o';
yyy[5]='\0';
xxx=String(yyy);
Run Code Online (Sandbox Code Playgroud)