我的背景不在 C 语言中(它在 Real Studio 中——类似于 VB),而且我真的很难拆分逗号分隔的字符串,因为我不习惯低级字符串处理。
我正在通过串行向 Arduino 发送字符串。这些字符串是某种格式的命令。例如:
@20,2000,5!
@10,423,0!
'@' 是指示新命令的标头和 '!' 是标记命令结束的终止页脚。'@' 之后的第一个整数是命令 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;
}
假设我的 PC 向 Arduino 发送字符串“@20,2000,5!”。command
我的草图以包含“20,2000,5”的字符串变量(称为)结束,commandRecieved
布尔变量设置为 True,因此handleCommand()
调用了该函数。
我想在(当前无用的)handleCommand()
函数中做的是将 20 分配给一个名为的变量,将id
2000 和 5 分配给一个名为 的整数数组data
,即:data[0] = 2000
、data[1] = 5
等。
我已经阅读过strtok()
,atoi()
但坦率地说,我无法理解它们和指针的概念。我确信我的 Arduino 草图也可以优化。