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!