string 如何在Arduino上使用分隔符读取字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11197097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read a string value with a delimiter on Arduino?
提问by yital9
I have to manage servos from a computer.
我必须通过计算机管理伺服系统。
So I have to send manage messages from computer to Arduino. I need manage the number of servo and the corner. I'm thinking of sendin something like this : "1;130" (first servo and corner 130, delimeter ";").
所以我必须从计算机向 Arduino 发送管理消息。我需要管理舵机的数量和角落。我正在考虑发送这样的内容:“1;130”(第一个伺服和角落 130,分隔符“;”)。
Are there any better methods to accomplish this?
有没有更好的方法来实现这一点?
Here is my this code :
这是我的代码:
String foo = "";
void setup(){
Serial.begin(9600);
}
void loop(){
readSignalFromComp();
}
void readSignalFromComp() {
if (Serial.available() > 0)
foo = '';
while (Serial.available() > 0){
foo += Serial.read();
}
if (!foo.equals(""))
Serial.print(foo);
}
This doesn't work. What's the problem?
这不起作用。有什么问题?
回答by Ihab Hajj
- You can use Serial.readString() and Serial.readStringUntil() to parse strings from Serial on arduino
- You can also use Serial.parseInt() to read integer values from serial
- 您可以使用 Serial.readString() 和 Serial.readStringUntil() 在 arduino 上解析来自 Serial 的字符串
- 您还可以使用 Serial.parseInt() 从串行读取整数值
Code Example
代码示例
int x;
String str;
void loop()
{
if(Serial.available() > 0)
{
str = Serial.readStringUntil('\n');
x = Serial.parseInt();
}
}
The value to send over serial would be "my string\n5" and the result would be str = "my string" and x = 5
通过串行发送的值将是“我的字符串\n5”,结果将是 str = “我的字符串”和 x = 5
Note: Serial.available() inherits from the Stream utility class.https://www.arduino.cc/reference/en/language/functions/communication/serial/available/
注意:Serial.available() 继承自 Stream 实用程序类。https://www.arduino.cc/reference/en/language/functions/communication/serial/available/
回答by Odis Harkins
This is a Great sub I found. This was super helpful and I hope it will be to you as well.
这是我发现的一个很棒的潜艇。这非常有帮助,我希望它也会对你有帮助。
This is the method that calls the sub.
这是调用 sub 的方法。
String xval = getValue(myString, ':', 0);
This is The sub!
这是子!
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {
0, -1 };
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
回答by Joakim
Most of the other answers are either very verbose or very general, so I thought I'd give an example of how it can be done with your specific example using the Arduino libraries:
大多数其他答案要么非常冗长,要么非常笼统,所以我想我会举一个例子,说明如何使用 Arduino 库通过您的特定示例来完成它:
You can use the method Serial.readStringUntilto read until your delimiter from the Serial
port.
您可以使用Serial.readStringUntil方法从Serial
端口读取直到您的分隔符。
And then use toIntto convert the string to an integer.
然后使用toInt将字符串转换为整数。
So for a full example:
所以对于一个完整的例子:
void loop()
{
if (Serial.available() > 0)
{
// First read the string until the ';' in your example
// "1;130" this would read the "1" as a String
String servo_str = Serial.readStringUntil(';');
// But since we want it as an integer we parse it.
int servo = servo_str.toInt();
// We now have "130\n" left in the Serial buffer, so we read that.
// The end of line character '\n' or '\r\n' is sent over the serial
// terminal to signify the end of line, so we can read the
// remaining buffer until we find that.
String corner_str = Serial.readStringUntil('\n');
// And again parse that as an int.
int corner = corner_str.toInt();
// Do something awesome!
}
}
Of course we can simplify this a bit:
当然,我们可以稍微简化一下:
void loop()
{
if (Serial.available() > 0)
{
int servo = Serial.readStringUntil(';').toInt();
int corner = Serial.readStringUntil('\n').toInt();
// Do something awesome!
}
}
回答by Jon
You need to build a read buffer, and calculate where your 2 fields (servo #, and corner) start and end. Then you can read them in, and convert the characters into Integers to use in the rest of your code. Something like this should work (not tested on Arduino, but standard C):
您需要构建一个读取缓冲区,并计算您的 2 个字段(伺服 # 和拐角)开始和结束的位置。然后您可以读入它们,并将字符转换为整数以在其余代码中使用。像这样的东西应该可以工作(未在 Arduino 上测试,但在标准 C 上):
void loop()
{
int pos = 0; // position in read buffer
int servoNumber = 0; // your first field of message
int corner = 0; // second field of message
int cornerStartPos = 0; // starting offset of corner in string
char buffer[32];
// send data only when you receive data:
while (Serial.available() > 0)
{
// read the incoming byte:
char inByte = Serial.read();
// add to our read buffer
buffer[pos++] = inByte;
// check for delimiter
if (itoa(inByte) == ';')
{
cornerStartPos = pos;
buffer[pos-1] = 0;
servoNumber = atoi(buffer);
printf("Servo num: %d", servoNumber);
}
}
else
{
buffer[pos++] = 0; // delimit
corner = atoi((char*)(buffer+cornerStartPos));
printf("Corner: %d", corner);
}
}
回答by Aziz
It looks like you just need to correct
看起来你只需要更正
foo = ''; >>to>> foo = "";
foo += Serial.read(); >>to>> foo += char(Serial.read());
I made also shomething similar..:
我也做了类似的东西..:
void loop(){
while (myExp == "") {
myExp = myReadSerialStr();
delay(100);
}
}
String myReadSerialStr() {
String str = "";
while (Serial.available () > 0) {
str += char(Serial.read ());
}
return str;
}