Sending Text to Hex in serial Port

33 次查看(过去 30 天)
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]
flush(device);
write(device,msg,"uint8")
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 =
'33'
'30'
'30'
'30'
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)?
Thanks

采纳的回答

Walter Roberson
Walter Roberson 2022-4-11
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');
  5 个评论
Jason
Jason 2022-4-11
Again out of curiosity, why are you using fprintf for the serial port and not write or writeline?
Walter Roberson
Walter Roberson 2022-4-11
%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);

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by