Sending Text to Hex in serial Port

42 views (last 30 days)
Hello, I have managed to send hex commands to a pump using the serial port (that requires the commands to be in hex)
msg=[0xFF 0x2F 0x31 0x41 0x31 0x30 0x30 0x52 0x0D]
The Number thats part of the hex code above is 3000
i.e. the (0x33 0x30 0x30 0x30) part.
I am wanting to change the number at will i.e. 100, 500, 1000 etc, but dont want to hard code it.
I see the dec2hex can help
>> a=dec2hex('3000')
a =
But how to I put the output of the dec2hex into the format that I need in msg (i.e. prefix each one wit 0x and put a space inbetween)?

Accepted Answer

Walter Roberson
Walter Roberson on 11 Apr 2022
msg=[0xFF 0x2F 0x31 0x41 0x31 0x30 0x30 0x52 0x0D]
msg = 1×9
255 47 49 65 49 48 48 82 13
That does not create msg as a character vector with '0xFF<space>' and so on. Instead it converts the values to uint8. Look at the values:
whos msg
Name Size Bytes Class Attributes msg 1x9 9 uint8
ans =
'ÿ/1A100R '
So you would do something like
msg_hdr = [0xFF 0x2F 0x31 0x41];
msg_trailer = [0x52 0x0D];
msg = [msg_hdr, uint8(num2str(VALUE)), msg_trailer];
write(device, msg, 'uint8');
Jason on 11 Apr 2022
Again out of curiosity, why are you using fprintf for the serial port and not write or writeline?
Walter Roberson
Walter Roberson on 11 Apr 2022
%variation 1
y_umlaut = char(255);
carriage_return = char(13); %not char(10)
msg = y_umlaut + "/1A" + VALUE + "R" + carriage_return;
write(device, msg, 'uint8')
%variation 2
configureTerminator(device, "CR");
y_umlaut = char(255);
msg = y_umlaut + "/1A" + VALUE + "R";
writeline(device, msg)
%variation 3
fprintf(device, '\o377/1A%dR\r', VALUE);
%variation 4
fprintf(device, '\xff/1A%dR\r', VALUE);

Sign in to comment.

More Answers (0)




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!