我的背景不在C中(它在Real Studio中 - 类似于VB),我真的很费力地分割逗号分隔的字符串,因为我不习惯低级别字符串处理。分割逗号分隔的整数字符串
我正在通过串行发送字符串到Arduino。这些字符串是特定格式的命令。例如:
@20,2000,5!
@10,423,0!
'@'是表示新命令和'!'的标题,是标记命令结束的终止脚注。 '@'后面的第一个整数是命令ID,其余的整数是数据(作为数据传递的整数数量可以是0-10个整数)。
我写了一个草图,它获取命令(剥离'@'和'!'),并在有命令处理时调用handleCommand()
函数。问题是,我真的不知道如何分割这个命令来处理它!
这里的草图代码: “@ 20,2000,5”
String command; // a string to hold the incoming command
boolean commandReceived = false; // whether the command has been received in full
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// main loop
handleCommand();
}
void serialEvent(){
while (Serial.available()) {
// all we do is construct the incoming command to be handled in the main loop
// get the incoming byte from the serial stream
char incomingByte = (char)Serial.read();
if (incomingByte == '!')
{
// marks the end of a command
commandReceived = true;
return;
}
else if (incomingByte == '@')
{
// marks the start of a new command
command = "";
commandReceived = false;
return;
}
else
{
command += incomingByte;
return;
}
}
}
void handleCommand() {
if (!commandReceived) return; // no command to handle
// variables to hold the command id and the command data
int id;
int data[9];
// NOT SURE WHAT TO DO HERE!!
// flag that we've handled the command
commandReceived = false;
}
说我的电脑发送的Arduino的字符串。我的草图以String变量(称为command
)结束,其中包含“20,2000,5”,并且commandRecieved
布尔变量设置为True,因此调用handleCommand()
函数。
我想什么在(目前无用)做handleCommand()
功能是分配20到被叫id
和2000和5至被叫data
整数数组变量,即:
data[0] = 2000
,data[1] = 5
等我已经阅读了关于strtok()
和atoi()
,但坦率地说,我只是无法摆脱他们和指针的概念。我相信我的Arduino草图也可以进行优化。
这两个都是做这个的好方法。你也可以尝试sscanf,如果它是可用的 – Gir 2012-08-11 15:33:01
你能提供任何示例代码?我在上图中努力想出C代码。我真的不知道如何使用我提到的两种方法... – Garry 2012-08-11 15:38:29