我正在尝试编写代码来存储来自串行终端的 { 和 } 之间的命令文本。到目前为止,我有:
byte index = 0; // Index into array; where to store the character
char cmdArr[10];
boolean startOfLine = false;
boolean endOfLine = false;
void setup()
{
Serial.begin(38400);
}
void serialEvent()
{
while (Serial.available())
{
char cmd = (char)Serial.read();
if (cmd == '{')
{
startOfLine = true;
}
if (cmd == '}')
{
endOfLine = true;
//cmdArr[index] = '\0'; //null terminate the C string; I'm not sure if this is needed
}
if (startOfLine && cmd != '{' && cmd != '}')
{
cmdArr[index++] = cmd;
}
if (startOfLine && endOfLine)
{
int i;
for (i = 0; i < 10; i++)
{
//Do something with the command
}
startOfLine = false;
endOfLine = false;
break;
}
}
}
void loop()
{
}
我能够遍历 cmdArr 以打印出数组值。例如,现在命令存储如下: char cmdArr[10] = {'p', 'h', 'c', '\0'}; 是否可以存储 char cmdArr[10] = {"phc"}; 之类的命令?另外,我将如何清除/清空该命令以准备下一个命令?
似乎正在运行的新代码。我求助于使用字符串,因为它似乎是最简单的方法:
String cmdData; //Store the complete command on one line to send to sensor board.
boolean startOfLine = false;
boolean endOfLine = false;
void setup()
{
Serial.begin(38400);
Serial3.begin(38400);
}
void serialEvent()
{
while (Serial.available())
{
char cmd = (char)Serial.read();
if (cmd == '{')
{
startOfLine = true;
}
if (cmd == '}')
{
endOfLine = true;
}
if (startOfLine && cmd != '{' && cmd != '}')
{
//Serial.print("Send command");
cmdData += cmd;
}
if (startOfLine && endOfLine)
{
startOfLine = false;
endOfLine = false;
cmdData += '\r';
Serial3.print(cmdData);
cmdData = "";
}
}
}
void serialEvent3()
{
char cmd3 = (char)Serial3.read();
Serial.print(cmd3);
}
void loop()
{
}