Edit char[] with variable data

Hello everyone,

I'm struggling with the following problem and I can't figure how to solve it by myself.

I receive volume level and I need to send this information. I need to edit char command[] with my volume variable.

I send TCP data with the following code.

        char command[] = "\x53\x25\x81\x00\x1A";
        client.write((uint8_t *)command, sizeof(command));

This code is working well.

An example to illustrate my problem :

volume = 50%, converted to HEX = 0x32. I need to replace the part x00 with x32, is it possible ?

        char command[] = "\x53\x25\x81\x32\x1A";
        client.write((uint8_t *)command, sizeof(command));

Thank you !

Approach your requirement from a different angle. Instead of editing the command string consider building it from the data that you need

char command[30];

void setup()
{
  Serial.begin(115200);
  char volume[] = "32";
  sprintf(command, "\\x53\\x25\\x81\\%s\\x1A", volume);
  Serial.println(command);
}
void loop()
{
}

The reason for the double backslashes is that they have a special meaning when used singly so need to be used this way to indicate that in this use case you really do want a backslash

If the volume is actually an integer you don't need to convert it to a string first

char command[30];

void setup()
{
  Serial.begin(115200);
  int volume = 32;
  sprintf(command, "\\x53\\x25\\x81\\x%d\\x1A", volume);
  Serial.println(command);
}
void loop()
{
}

Try these 2 examples and investigate the sprintf() function some more. If required you can use multiple variables in the same command to build the required string

0x32 in Hex is 50 in decimal. so seems you just want to write the volume value in the right byte
if you have

char command[] = "\X53\X25\X81\X00\X1A";

then just do command[3] = volume; // assuming volume is a byte whose value is 50

if you want to see what's in the buffer, do this

void setup() {
  Serial.begin(115200);
  char command[] = "\x53\x25\x81\x00\x1A";
  for (byte c: command) Serial.println(c, HEX);
}

void loop() {}

By the look of it, it's not a really a string, it's actually a byte buffer. I would write it like that instead of using the \Xnn escape sequence notation of a cString.

byte command[]  = {0x53, 0x25, 0x81, 0x00, 0x1A, 0x00};// do we need the trailing 0x00 ?

you are sending six bytes:
byte command[6] = {0x53, 0x25, 0x81, 0x00, 0x1A, 0x00};
Did you want to send five bytes? That would be:
byte command[5] = {0x53, 0x25, 0x81, 0x00, 0x1A};

In either case, use something like this to change the value of the byte containing 0x00:

  byte precentVolume = 50;
  command[3] = precentVolume;
  client.write(command, sizeof command);

Thank you ! I've used your solution, problem solved !

Good, have fun!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.