Hi,
I am trying to receive serial commands for a project, where each received command ends with \n.
This works well, and I can check which command is received using If else statements.
But one command is 3 fixed characters, say CMD, followed by a 3 digit value (0 to 360).
So the actual command received is CMD***\n where *** is (000-360).
Using the following code, I can easily receive data until a \n is received then check for the command using if statements:
if (Serial1.available()) {
command = Serial1.readStringUntil('\n');
command.trim();
if (command.equals("CMD")) {
Serial1.write("OK. DO SOMETHING\n");
}
else if (command.equals("LED")) {
Serial1.write("OK, turn on LED");
}
else {
Serial1.write("BAD COMMAND\n");
}
So the above code will receive serial commands until \n is received. Then check for which command is received.
But the command CMDxxx, where xxx is a number 0 to 360.
This does not work, but can I use a wild card in the
if (command.equals("CMD")) {
Like:
if (command.equals("CMD",'***')) {
So it will still trap the CMD command with 3 other characters directly after it. But not actually check the 3 numbers apart from that they exist.
I then need to strip out the 3 numbers.
Does that make sense? Or have I just confused the issue here?
I will have around 10 commands, all are three characters. Only one command will have a parameter to set a a particular value (0 to 360).
As in CMDxxx, but I suppose I could split it and receive the CMD first then look for the xxx and convert it to a value, but just seems a bit messy.
If all commands are 3 characters long except CMDxxx which is 6, it is not that complicated to do.
If the string read has more than 3 characters, you confirm that it contains "CMD" as I suggested in #5 and then extract the number.
Otherwise (it would have 3 characters), you execute the statements corresponding to those commands.
OK, I now understand that after reading the Arduino docs.
Only thing I would need to do is to check that when the CMDxxx is received that the xxx is only 3 characters. So the Indexof traps the CMD part but it would also work with CMDxxxxxxxx...., so I need to check the total length of the command received.
Yes, that particular command will always be in the format ATMxxx so 7 will be 007.
The commands are coming from Labview, so will be tightly controlled.
Thanks to everyone for your replies. Its much appreciated.
@dogboy i think you are making this over complicated. it's pretty routine to read a cmd with some argument of arbitrary length. since it sounds like you want a cmd that specifies a value from 0 to 360 degrees it seems unnecessary to require that those values be specified by one of 360 commands: CMD001, CMD002, ...CMD360.
and what about the possibility of specifying negative values, relative value.