필터 지우기
필터 지우기

Sending Text to Hex in serial Port

조회 수: 20 (최근 30일)
Jason
Jason 2022년 4월 11일
댓글: Walter Roberson 2022년 4월 11일
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개)

카테고리

Help CenterFile Exchange에서 Serial and USB Communication에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by