Incomplete sending from fprintf

4 次查看(过去 30 天)
James Minor
James Minor 2012-6-20
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?

回答(2 个)

Walter Roberson
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.

Noah Jaxon
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.

类别

Help CenterFile Exchange 中查找有关 Predictive Maintenance Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by