我的背景不在C(它在Real Studio中 - 类似于VB)而且我真的很难分割逗号分隔的字符串,因为我不习惯低级字符串处理.
我正在通过串口向Arduino发送字符串.这些字符串是特定格式的命令.例如:
@20,2000,5!
@10,423,0!
Run Code Online (Sandbox Code Playgroud)
'@'是标题,表示新命令和'!' 是标记命令结束的终止页脚.'@'之后的第一个整数是命令id,其余的整数是数据(作为数据传递的整数数可以是0-10个整数).
我写了一个获取命令的草图(剥离了'@'和'!')并调用了一个函数,handleCommand()当有一个命令要处理时.问题是,我真的不知道如何拆分这个命令来处理它!
这是草图代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
假设我的PC发送Arduino字符串"@ 20,2000,5!".我的草图最终得到一个command包含"20,2000,5" 的String变量(称为),并且commandRecieved布尔变量设置为True,因此handleCommand()调用该函数.
我想在(目前无用)做handleCommand()功能是分配20称为可变id2000 5和整数数组叫data,即:data[0] = 2000,data[1] = 5,等.
我已经读过了strtok(),atoi()但坦率地说,我无法理解他们和指针的概念.我确信我的Arduino草图也可以进行优化.
由于您使用的是Arduino核心String类型,strtok其他string.h功能都不合适.请注意,您可以将代码更改为使用标准C以null结尾的字符串,但使用Arduino String将允许您在不使用指针的情况下执行此操作.
这种String类型给你indexOf和substring.
假设一个带有@和!被剥离的字符串,找到你的命令和参数看起来像这样:
// given: String command
int data[MAX_ARGS];
int numArgs = 0;
int beginIdx = 0;
int idx = command.indexOf(",");
String arg;
char charBuffer[16];
while (idx != -1)
{
arg = command.substring(beginIdx, idx);
arg.toCharArray(charBuffer, 16);
// add error handling for atoi:
data[numArgs++] = atoi(charBuffer);
beginIdx = idx + 1;
idx = command.indexOf(",", beginIdx);
}
data[numArgs++] = command.substring(beginIdx);
Run Code Online (Sandbox Code Playgroud)
这将为您提供data数组中的整个命令,包括命令编号at data[0],同时您已指定只有args应该在data.但必要的变化很小.
| 归档时间: |
|
| 查看次数: |
14080 次 |
| 最近记录: |