0

I want to get this code to recognise different commands and be able to parse the rest of the command, fore example I send "/sleep 5", and it will sleep for 5 seconds. However, I keep on getting this error "cannot convert 'String' to 'const char*'". here is my code:

#define maxCommandLength 64

String commands[] = {"/test", "/say", "/reset", "/sleep"};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Power on.");
}
char serial[maxCommandLength];
boolean valid;
void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Clearing command buffer(char 'serial'");
  for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
    serial[i] = ' ';
  }
  if (Serial.available()) {
    Serial.readBytesUntil(' ', serial, maxCommandLength);
  }
  if (serial[0] == '/') { //if it is a command
    Serial.print("Command recieved. \nCommand class:");
    Serial.println(serial);
    //test if command is valid
    for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
      valid = strcmp(serial,commands[i]);
      if(valid){
        break;
      }
    }
    //execution of command
    Serial.readBytesUntil(' ', serial, maxCommandLength);
    //.......
  }
}

2 Answers 2

1

there is no reason for command to be a String array. Instead make it a const char**:

const char** commands = {"/test", "/say", "/reset", "/sleep"};
2
  • I found that yours wouldn't compile, but this would: const char* commands[] = {"/test", "/say", "/reset", "/sleep"}; Commented Mar 16, 2018 at 3:51
  • @RowanRadosav-McRae If this answers your question please accept the answer. Commented Mar 16, 2018 at 6:58
1

You can call the .c_str() method of String class returning (temporary) const char * representation of underlying string, in your case:

valid = strcmp(serial,commands[i].c_str());
//                               ^^^^^^^^    

should work. Just make sure you don't keep the returned const char * around longer than necessary because by spec it is no guaranteed to remain valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.