Incomplete sending from fprintf
조회 수: 4 (최근 30일)
이전 댓글 표시
I am attempting to send 9 ASCII characters to a device connected to the computer via the serial port object s.
s = serial('Com5')
fopen(s)
The 9 ASCII characters are 8 bit ASCII characters represented by the following set of numbers:
OutputCommand = [255 9 19 8 0 50 0 0 171]
I create the string that I want with the following command
OutputString = native2unicode(OutputCommand)
After this command, OutputString now has the value 'ÿ 2 «' which I confirmed was length 9 (as it contains hidden characters, including 3 null characters.
However, when I do
fprintf(s, OutputString)
and then check s, the data sent has only gone up by 4 bytes. If I copy the result of OutputString and do
fprintf(s, 'ÿ 2 «')
then 7 bytes are written.
There numbers stay the same even if the termination character for s is changed.
Why does this occur? My hypothesis is that the null character (value 0 in ASCII) counts as an alternative termination character, so 4 bytes are sent normally (the 4 before the termination character), and when the string is copied the null characters are stripped out, so there are 6 characters + the normal termination character (which counts, when null doesn't, for some reason).
Is there a way to prevent this from happening?
댓글 수: 0
답변 (2개)
Walter Roberson
2012년 6월 20일
fwrite(s, OutputString)
And now, there is no way to prevent the MATLAB string-based I/O routines from treating an embedded NUL as a terminator. You might, though, possibly get further with
fprintf(s, "%s\n", OutputString)
No promises.
댓글 수: 0
Noah Jaxon
2019년 8월 8일
Had the same problem in Matlab2014. This has apparently been resolved since - Matlab2018, but for older versions use fwrite(com,message) instead. Output is strict uint8 format.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Predictive Maintenance Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!