Software Serial and Strings

Hi,

I’m struggling with sending the correct info over serial to control module I’m using.
The module requires the structure DXXX (i.e D010 give 10%).

If I use the code below it works, but seems inefficient:

//Set Rx and Tx Pins
#include<SoftwareSerial.h>
SoftwareSerial myserial(11,12); //Rx,Tx


void setup() {
  // create Serial Object

Serial.begin(9600);
myserial.begin (9600);
}

void loop(){
int x = 0;

for(x=0; x< 10; x=x+2){ 

if(x == 0){
       myserial.write("D000");
   }
   
if(x == 2){
       myserial.write("D002");
   }
   
if(x == 4){
       myserial.write("D004");
      
   }
   
   if(x == 6){
       myserial.write("D006");

   }
   
   if(x == 8){
       myserial.write("D008");

   }

   if(x == 10){
       myserial.write("D010");

   }
    delay (1000);
}
}

But if I try the below it wont work, I’m pretty green to coding, but I think its not sending the correct structure for the module I’m sending commands too:

//Set Rx and Tx Pins
#include<SoftwareSerial.h>
SoftwareSerial myserial(11,12); //Rx,Tx

String zerototen, tentohund, zttcurrent;

void setup() {
  // create Serial Object

Serial.begin(9600);
myserial.begin (9600);

 //Create Strings
zerototen=String("D00");
tentohund=String("D0");
}

void loop(){


int x = 0;


for(x=0; x< 11; x=x+2){
zttcurrent=zerototen + x;

if(x<10){
     myserial.write("zttcurrent");  
     delay (1000);
    

}
}
}

Any pointers would be very much appreciated.

Many Thanks,

Dan

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

void loop()
{
  char buffer[10];
  for (int x = 0; x < 100; x += 2)
  {
    sprintf(buffer, "D%03d", x);
    Serial.println(buffer);
  }
}

A simple way:

void setup()
{
  Serial.begin(115200);

  for (uint8_t x = 0; x <= 100; x += 2) {
    Serial.print( 'D' );
    if (x < 100)
      Serial.print( '0' );
    if (x < 10)
      Serial.print( '0' );
    Serial.println(x);
  }
}

void loop() {}

Also, I would using AltSoftSerial. It is the best software serial library. Only one instance is allowed, and it is must be used on one of the Input Capture pins (pins 8 & 9 for a UNO, Mini or Nano, see docs here).

My NeoSWSerial is next best. It works on any two pins, but only at baud rates 9600, 19200 and 38400.

SoftwareSerial is the worst choice. It works on any two pins, but it is very inefficient. It disables interrupts for the entire time that a character is being sent OR received, and it cannot do both at the same time (unlike all the other serial choices). This can interfere with other parts of your sketch, other device communications, or with libraries.

And… Don’t use String™. It can cause really weird problems at random times. Just use char arrays, also called C strings, with a lowercase ‘s’.