Sending Hex data to Serial Port

I'm having difficulty in sending the data" 5A A5 07 82 0084 5A01 0001" using Arduino to Realterm.

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

void loop()
{
byte message[7] = {0x5A, 0xA5, 0x07, 0x82, 0x0084, 0x5A01, 0x0001};
Serial.write(message, 7);
delay(5000);
}`

This is the code.
It sends 2 byte data only, 5A01 does not go only 01 does.

byte message[7] = {0x5A, 0xA5, 0x07, 0x82, 0x0084, 0x5A01, 0x0001};

Because byte can only hold values up to 0xFF!

Do you need to send the data as text, including spaces where you show them?

PS. Please always use code tags when posting code, error messages or serial monitor output.

Define your byte message array outside the loop function to make it global.
Then use a for loop inside the loop and use the loop index to define what byte you want to send.

1 Like

That’s more than 7 bytes, do you need a 10 bytes payload?

Hi ,
For your understanding, test this sketch.

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

void loop()
{
//  0x31  = char 1  , 0x32 = char  2 , 0x33 = char  3, 0x34 = char  4, 0x35 = char  5, 0x36 = char  6, 0x37 = char  7.
byte message[7] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37};
Serial.write(message, 7);
delay(5000);
}

You are not sending "hex data", you are sending binary values.

What does Realterm do with unprintable binary values like 0x07 (in hex representation) ?

I want to send 2 byte and 4 byte HEX data in the particular order to HMI screen.

I want to send 2 byte data and 4 byte data together

You are right, I should have sent HEX, but I don't know how to send HEX data in the particular order having 2 byte and 4 byte data

You still don't understand. "HEX" is a human readable representation of binary data, using only the printable ASCII characters 0-9 and A-F.

If you will explain what you are really trying to do, perhaps you will get a some understandable answers.

so you want to send 7 data elements’ some being 1 byte and some being multi-bytes and corresponding to {0x5A, 0xA5, 0x07, 0x82, 0x0084, 0x5A01, 0x0001}

You need to worry about the endianness of the 2 bytes’ or 4 bytes’ ones, is it MSB first or LSB first?

The code to send the full payload in MSB first mode would be

const byte message[] = {0x5A, 0xA5, 0x07, 0x82, 0x00, 0x84, 0x5A, 0x01, 0x00, 0x01};
Serial.write(message, sizeof message);

Another option if you can describe the payload in a struct with the 1 byte and multibyte fields is to fill in that struct (declared using the packed attribute) and send the struct. In that case you’ll get little endian alignment for the multi byte attributes

1 Like

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