serial/fprintf of non-string?
9 views (last 30 days)
Show older comments
Walter Roberson on 3 May 2015
Edited: Walter Roberson on 3 Jul 2015
The documentation of serial/fprintf shows four possible modes in the representative forms, and in each case the data to be sent is shown as a string. However, the format parameter can include any of many different non-character item specifiers, and one of the examples is
fprintf(s,['ch:%d scale:%d'],[1 20e-3],'sync');
which demonstrates a case where the data to be sent is not a string.
Despite this, a user is reporting to me that in R2013a that they were told
Error using serial/fprintf (line 84)
The third input argument must be a string.
Error in Untitled (line 10)
fprintf(s, '*%d', data(:)) ;
where data is uint8 (obtained via imread)
Unfortunately I cannot test this on my own system as I do not have a serial port. Could someone confirm that non-string data can be used in serial fprintf, and could they test whether uint8 is the problem?
(Assume for the moment that the serial buffer is large enough to hold the entire output; do not test with large arrays as the default output buffer is only 512 bytes.)
Nalini Vishnoi on 6 May 2015
I can reproduce the behavior on a system with a serial port. The documentation (mostly the syntax section) of serial/fprintf indicates that the data to be sent to the device needs to be a string. However in the example you mentioned the format parameter includes different non-character item specifiers (specifically %d - which is signed decimal notation). When I opened that function, I noticed that serial/fprintf function accepts only 'string' and 'double' data types. Hence the error while trying to pass an array which is of type 'uint8'. If you have not tried already, you can try these workarounds:
1. Cast the uint8 value as double:
>> fprintf(s, '*%d', double(data(:))) ;
2. Use sprintf to build the 'cmd' string which is then passed as an argument to serial/fprintf function:
>> str = sprintf('%u\n',data);
>> fprintf(s, str);
3 Use fwrite function which writes binary data (could be uint8) to the device.
>> fwrite(s, data, 'uint8');
I work with MathWorks and would communicate the ambiguity in the documentation of the function and the possibility of allowing other data types (such as 'uint8') as accepted arguments, to the respective development teams.
More Answers (0)
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!