Serial print the String in Arduino

Hi Guys,

Maybe this is a very basic question, but I tried it and work around it with no luck. Hope anyone can show me any tips for STRING in Arduino. I use it for multiple servos. Following code works fine:

void setup()
  Serial.begin(9600);
}

void loop() {
  Serial.print("#1P600T1000\r\n");
  delay(1000);
  Serial.print("#1P1500T500\r\n");
  delay(1000);
}

However, I try to use the code in FOR loop. It's not doing anything by following code:

void setup() {               
  Serial.begin(9600);
}

void loop() {
  for(int i=1;i<=30;i++){
    String servos = "#"+i;
    String cmd1 = servos+"P600T1000\r\n";
    String smd2 = servos+"P1500T500\r\n";
    Serial.print(cmd1);
    delay(1000);
    Serial.print(cmd2);
    delay(1000);
  }
}

I am trying to move 30 servos at the same time but they are not moving at all, even just one servo. I'm assuming the way I use STRING is kinda weird. Any ideas? Thanks for any suggestions or corrections.

Just to make question simple again:

Serial.print("#1P600T1000\r\n"); <--This works.

String servos = "#"+i;
    String cmd1 = servos+"P600T1000\r\n";  <--- This is not working...
    Serial.print(cmd1);

You are not initializing the string properly

Well I tried your code and it did print some strings but they were missing the first few i characters :slight_smile:

What your code is doing right now is taking the address of where the “#” zero terminated string is stored and moving it over by i bytes and assigning that to a String :slight_smile:

I’m really surprized it even worked at all.

String servos = “#”+i;  <— This is actually what’s not working
    String cmd1 = servos+“P600T1000\r\n”;  
    Serial.print(cmd1);

Try this:

String servos = String("#")+i; //servos is now correctly initialized with an instance of the String class
    String cmd1 = servos+“P600T1000\r\n”;
    Serial.print(cmd1);

I believe you almost have it.

I don’t have hardware to test it on, but, you may need 
     String servos = String("#")+i;
to be
     String servos = “#” + String(i);
I say this because, the “#” is already a string, but, the ‘i’ is an integer. When I went looking for ways to convert ints to ascii, I was shown String() will do that.

Once again, I am just shooting off an opinion. 

Thanks guys!!!

That works perfectly~

Actually…

that’s the problem with the initial code.

"#" is NOT a String(which is a class from the core arduino library) it is a char* (a pointer to a character)

The + opperator for pointers will perform pointer arithmetic 

The + operator for the class String will perform a concatenation with the string representation of the other operand (for supported data types)