2017-03-21 86 views
-3

我想从Arduino上的字符串中提取几个整数。我正在使用已连接到手机的Bluefruit蓝牙模块。从字符串中提取整数

手机上的应用程序通过Bluefruit的TX/RX发送一串数据到Arduino。

我成功地从应用程序接收数据,我可以在我的计算机上的串行监视器中看到它。字符串格式为:x:xxx,xxx,xxx,第一个数字为1至6,其他数字为3至0-255。

因此,例如:1:171,54,201

该字符串还包括一个回车,因为下一个字符串总是开始于一个新的生产线。

任何人都可以帮助我提取这些整数并将它们设置为变量?

+3

你到目前为止尝试过什么? – Trevor

回答

1

您可以使用C sscanf()功能:

#include <stdio.h> 

char line[] = "1:171,54,201"; // read a line from Bluetooth 
int num1, num2, num3, num4; 

if (sscanf(line, "%d:%d,%d,%d", &num1, &num2, &num3, &num4) == 4) 
{ 
    // use numbers as needed 
} 

或者C++的包装,std::sscanf()

#include <cstdio> 

char line[] = "1:171,54,201"; // read a line from Bluetooth 
int num1, num2, num3, num4; 

if (std::sscanf(line, "%d:%d,%d,%d", &num1, &num2, &num3, &num4) == 4) 
{ 
    // use numbers as needed 
} 

如果您有可用(这显然Arduino的不)的STL,您可以使用STL std::istringstream类改为:

#include <string> 
#include <sstream> 

std::string line = "1:171,54,201"; // read a line from Bluetooth 
int num1, num2, num3, num4; 

std::istringstream iss(line); 
char ignore; 

if (iss >> num1 >> ignore >> num2 >> ignore >> num3 >> ignore >> num4) 
{ 
    // use numbers as needed 
} 

或者:

#include <string> 
#include <sstream> 

bool readInt(std::istream &in, char delim, int &value) 
{ 
    std::string temp; 
    if (!std::getline(in, temp, delim)) return false; 
    return (std::istringstream(temp) >> value); 
} 

std::string line = "1:171,54,201"; // read a line from Bluetooth 
int num1, num2, num3, num4; 

std::istringstream iss(line); 

if (readInt(iss, ':', num1) && readInt(iss, ',', num2) && readInt(iss, ',', num3) && readInt(iss, '\n', num4)) 
{ 
    // use numbers as needed 
} 
+0

这似乎是一个很好的解决方案。我正在尝试它,但我有问题,它说,字符串不是标准的一部分。此外,我不能包括我正在更新Arduino IDE以查看是否可以解决问题。 –

+0

@Lucavanderknaap Arduino“C++”不是真正的“C++”,它更像是一个受限制的子集/方言。 STL在供应商的Arduino上不可用,然而对于微控制器来说,有很小的限制实现。 – user2176127

+0

@RemyLebeau我添加了.h到字符串,现在它包含它,但我仍然有错误,“字符串不是std的成员” –

0

有了一个快速谷歌搜索类似的问题,我发现了如何将字符串IP地址转换成数字与下面的代码an example

std::string ip ="192.168.1.54"; 
std::stringstream s(ip); 
int a,b,c,d; //to store the 4 ints 
char ch; //to temporarily store the '.' 
s >> a >> ch >> b >> ch >> c >> ch >> d; 

然而,由于您的问题是“稍微”不同,你可以做到以下几点:

std::string givenExample = "1:171,54,201" 

//Since it is known that the value will be 1-6, just take 
//the ASCII value minus 30 hex (or '0') to get the actual value. 
int firstNumber = ((int)givenExample.at(0) - 0x30); //or minus '0' 

givenExample.erase(0, 2); //Remove "1:" from the string 

std::stringstream s(givenExample); 
int secondNumber, thirdNumber, fourthNumber; 
char ch; 
s >> secondNumber >> ch >> thirdNumber >> ch >> fourthNumber; 

然而,如果你的第一个例子比较第二,知识产权字符串是几乎次与您的示例相同的格式:由字符分隔的4个整数。所以两者都会起作用,这取决于哪一个对你更有意义。至于你如何读取(处理回车)数据,这取决于你从Arduino接收到的串行数据流的接口。

+0

'int firstNumber =(int)givenExample.at(0);'将使firstNumber包含49是第一个字符是'1'。从中提取数字'48'(或'0') – Fureeish

+0

良好的通话,谢谢!我已经更新了我的答案。 – Trevor

+0

不幸的是,arduino上没有STL,所以我不能使用它。无论如何,谢谢 –