Question

I am currently trying to build a very basic serial shell with my arduino.

I am able to get an output from the device using Serial.read() and can get the character it has outputted, but I cannot work out how to then add that character to a longer to form the full command.

I tried the logical thing but it doesn't work:

char Command[];

void loop(){
  if(Serial.available() > 0){
    int clinput = Serial.read();
    Command = Command + char(clinput);
}

Can anybody help? Thank You.

Was it helpful?

Solution

Use std::string if you can. If you can't :

snprintf(Command, sizeof(Command), "%s%c", Command, clinput);

or (remeber to check that Command does not grow too much...)

size_t len = strlen(Command);
Command[len] = clinput;
Command[len + 1] = '\0';

OTHER TIPS

You have to write character by character into an array. For example like this:

#define MAX_COMMAND_LENGTH 20

char Command[MAX_COMMAND_LENGTH];
int commandLength;    

void loop(){
  if(Serial.available() > 0){
    int clinput = Serial.read();
    if (commandLength < MAX_COMMAND_LENGTH) {
      Command[commandLength++] = (char)clinput;
    }
}

BTW: This is not complete. E.g. commandLength has to be initialized with 0.

You need to allocate enough space in command hold the longest commmand and then write characters into it as the come in. When you run out of characters, you null terminate the command and then return.

char Command[MAX_COMMAND_CHARS];

void loop() {
  int ix = 0; 
  // uncomment this to append to the Command buffer
  //ix = strlen(Command);

  while(ix < MAX_COMMAND_CHARS-1 && Serial.available() > 0) {
     Command[ix] = Serial.read();
     ++ix;
  }

  Command[ix] = 0; // null terminate the command
}

Use std::ostringstream with std::string:

#include <sstream>
#include <string>

std::string loop()
{
    std::ostringstream oss;
    while ( Serial.available() > 0 ){
        oss << static_cast<char>(Serial.read());
    }
    return oss.str();
}

You can also concatenate multiple instances of std::string with operator+.

Since its also tagged C,

char *command = (char *)malloc(sizeof(char) * MAXLENGTH);
*command = '\0';

void loop(){
  char clinput[2] = {}; //for nullifying the array
  if(Serial.available() > 0){
    clinput[0] = (char)Serial.read();
    strcat(command, clinput);
}
 char command[MAX_COMMAND];
 void loop(){
     char *p = command;
    if(Serial.available() > 0){
      int clinput = Serial.read();
    command[p++] = (char)clinput;
   }
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top