Serial out multiple hex

Hello,

I can send out a string of text using software serial....

MySerial.print("some text")

But how do I send out a string of hex? At the moment I am using.

MySerial.print(0x00);
MySerial.print(0x00);
MySerial.print(0x00);
MySerial.print(0x00);

Which works but I would prefer to have this on one line.

Thanks

Yeah kidding myself there actually needed to do the following,

DriveSerial.print("@");
DriveSerial.print("A");
DriveSerial.print(0,HEX);
DriveSerial.print(0,HEX);
DriveSerial.print(0,HEX);
DriveSerial.print(0,HEX);

still, would like to have them all on the same line.

Hi,

Try something like:

DriveSerial.print("@A\x00\x00\x00\x00")

I haven't tested it but AFAIK it should work.

--Phil.

Phil,

I'm afraid that won't work because the first \x00 will be interpreted as the zero byte which terminates all C strings. I haven't tried it either, but I'm sure that only

@A

will be printed.

Mikal

Random,

If you want to condense your code so that all the hex printing happens on one line, you might try writing a short helper function to print arrays of values, per this example:

// This function prints "siz" HEX values from the "buf" array
void PrintHexBuffer(unsigned char *buf, size_t siz)
{
  for (size_t i=0; i<siz; ++i)
    Serial.println(buf[i], HEX);
}

void setup()
{
  Serial.begin(9600);
  unsigned char hex_buf[] = {0x00, 0x13, 0x2F, 0xFF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF};
  PrintHexBuffer(hex_buf, sizeof(hex_buf));
}

void loop()
{
}

Mikal

I'm afraid that won't work because the first \x00 will be interpreted as the zero byte which terminates all C strings.

Ahh, good point.

So, I guess another approach would be to create a function similar to the one you showed and use the string with embedded \x00 but manually specify the string length--which is obviously a potential source of strange errors.

--Phil.

So, I guess another approach would be to create a function similar to the one you showed and use the string with embedded \x00 but manually specify the string length--which is obviously a potential source of strange errors.

Yeah, I think that would work, but as you point out, strings with embedded '\x00' bytes have the potential to be confusing and a little risky. Since their only advantage over unsigned char arrays is the (very slightly) condensed string syntax, I think I might still recommend arrays in this case.

Cheers!

Mikal